<template>
  <div>
    <el-card :body-style="cardBodyStyle">
      <el-form :model="query" label-position="right" :inline="true">
        <el-row :gutter="10" style="margin-bottom: 5px;">
          <el-col :span="5">
            <el-form-item label="物料名称" style="margin-bottom: 0px;">
              <el-input v-model="query.itemNm" placeholder="请输入物料名称" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="年份" style="margin-bottom: 0px;">
              <el-date-picker
                  style="width: 100%"
                  v-model="query.year"
                  type="year"
                  value-format="YYYY"
                  placeholder="年份"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <ButtonBar @search="handleSearch" @add="handleAdd" @remove="handleRemoveBatch" @submit="submit"
               @download="download"></ButtonBar>

    <el-card :body-style="cardBodyStyle">
      <el-table :data="tableData" border highlight-current-row @selection-change="handleSelectionChange" :height="height">
        <el-table-column type="selection" fixed></el-table-column>
        <el-table-column type="index" label="序号" align="center" width="60" fixed="left">
          <template #default="scope">
            <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="true" prop="planNo" label="计划编号" fixed="left"
                         header-align="center" align="center" width="200"
                         show-overflow-tooltip>
          <template #default="scope">
            <el-button @click="handleInfo(scope.row)" type="primary" link>{{ scope.row.planNo }}</el-button>
          </template>
        </el-table-column>
        <el-table-column v-if="true" prop="deptNm" label="部门名称" width="160"
                         header-align="center" align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="itemCd" label="物料编码" width="200"
                         header-align="center" align="center"
                         show-overflow-tooltip>

        </el-table-column>
        <el-table-column v-if="true" prop="itemNm" label="物料名称"
                         header-align="center" align="center" width="160"
                         show-overflow-tooltip>
        </el-table-column>
<!--        <el-table-column v-if="true" prop="processInstanceStatus" label="状态"-->
<!--                         header-align="center" align="center"-->
<!--                         show-overflow-tooltip>-->
<!--        </el-table-column>-->

        <el-table-column v-if="true" prop="year" label="年份"
                         header-align="center" align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="applyDt" label="申请日期"
                         header-align="center" align="center" width="160"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="workModel.flowStatusName" label="流程状态" width="120" header-align="center" align="center"
                         show-overflow-tooltip>
          <template #default="{ row }">
            <div>
              <el-tag v-if="row.workId !== undefined && row.workModel.flowStatus === '110'">{{ row.workModel.flowStatusName }}</el-tag>
              <el-tag type="success" v-else-if="row.workId !== undefined && row.workModel.flowStatus === '170'">{{ row.workModel.flowStatusName }}</el-tag>
              <el-tag type="danger" v-else-if="row.workId !== undefined && (row.workModel.flowStatus === '130' || row.workModel.flowStatus === '180' || row.workModel.flowStatus === '190')">{{ row.workModel.flowStatusName }}</el-tag>
              <el-tag type="warning" v-else>'---'</el-tag>
            </div>

          </template>
        </el-table-column>
        <el-table-column v-if="true" prop="workModel.flowNode" label="当前节点" width="120" header-align="center" align="center"
                         show-overflow-tooltip>
          <template #default="{ row }">
            <div>
              <el-tag v-if="row.workId !== undefined && row.workModel.flowStatus === '110'">{{ row.workModel.flowNode }}</el-tag>
              <el-tag type="success" v-else-if="row.workId !== undefined && row.workModel.flowStatus === '170'">{{ row.workModel.flowNode }}</el-tag>
              <el-tag type="danger" v-else-if="row.workId !== undefined && (row.workModel.flowStatus === '130' || row.workModel.flowStatus === '180' || row.workModel.flowStatus === '190')">{{ row.workModel.flowNode }}</el-tag>
              <el-tag type="warning" v-else>'---'</el-tag>
            </div>

          </template>
        </el-table-column>

        <el-table-column v-if="true" prop="uom" label="计量单位"  width="160"
                         header-align="center" align="center" :formatter="formatter"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="specType" label="规格型号"  width="160"
                         header-align="center" align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="addName" label="添加人"  width="160"
                         header-align="center" align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="addTime" label="添加时间" width="200"
                         header-align="center" align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="remark" label="备注"
                         header-align="center" align="center" width="200"
                         show-overflow-tooltip>
        </el-table-column>


        <el-table-column label="操作" header-align="center" align="center" width="300px" fixed="right">
          <template #default="scope">
<!--            <el-button plain type="primay" @click="handleInfo(scope.row)">查看</el-button>-->
<!--            <el-button plain type="warning" @click="handleEdit(scope.row)">编辑</el-button>-->
<!--            <el-button plain type="danger" @click="handleDelete(scope.row )">删除</el-button>-->

            <el-button plain type="warning" @click="handleEdit(scope.row)" v-show="scope.row.workId === '' || scope.row.workModel.opType === '1'">编辑
            </el-button>
            <el-button plain type="danger" @click="handleDelete(scope.row )" v-show="scope.row.workId === '' || scope.row.workModel.opType === '1'">删除
            </el-button>
            <el-button plain type="success" @click="handleSubmit(scope.row ) "v-show="scope.row.workId === '' || scope.row.workModel.opType === '1'">发起
            </el-button>
            <el-button plain type="primary" @click="handleDetail(scope.row )" v-show="scope.row.workId !== ''">详情</el-button>
            <el-button plain type="info" @click="handleCancel(scope.row )" v-show="scope.row.workId !== '' && scope.row.workModel.opType !== '1' && scope.row.workModel.flowStatus !== '170'">撤回</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card :body-style="cardBodyStyle">
      <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="pageSizes"
                     :total="totalRows" background="background" layout="total, sizes, prev, pager, next, jumper"
                     @size-change="handleSizeChange" @current-change="handleCurrentChange">
      </el-pagination>
    </el-card>

    <el-dialog class="diaClass" :close-on-click-modal="false" draggable title="编辑" v-model="dialogVisible"
               width="1200px"
               top="5vh" @open="openDialog">
      <el-card>

        <el-form :model="form" label-width="120px" label-position="right" inline ref="ruleFormRef" :rules="rules">
          <el-row>
            <el-col :span="8">
              <el-form-item label="计划编号" prop="planNo">
                <el-input v-model="form.planNo" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="物料编码" prop="itemCd">
                <el-input v-model="form.itemCd" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="物料名称" prop="itemNm">
                <el-input v-model="form.itemNm" readonly>
                  <template #append>
                    <el-button :icon="Search" @click="itemDialog"/>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="申请日期" prop="applyDt">
                <el-date-picker
                    style="width: 100%"
                    v-model="form.applyDt"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="申请日期"
                />
              </el-form-item>
            </el-col>


            <el-col :span="8">
              <el-form-item label="年份" prop="year">
                <el-date-picker
                    style="width: 100%"
                    v-model="form.year"
                    type="year"
                    placeholder="年份"
                    value-format="YYYY"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="计量单位" prop="uom">
                <Selector_component :option-list="dictList.MEASURING_UNIT" :value="form.uom" :allow-select="true"
                                    @change="collectionTySelect"></Selector_component>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="规格型号" prop="specType">
                <el-input v-model="form.specType"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注"  >
                <el-input
                    v-model="form.remark"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    type="textarea"
                    placeholder="备注"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

      </el-card>


      <el-card :body-style="cardBodyStyle">
        <el-button type="success" plain @click="onAddItemWl" :disabled="planNoShow" >新增</el-button>
      </el-card>
      <el-card class="box-card" v-show="true">
        <el-table :data="tableDataMx" border highlight-current-row>
          <el-table-column type="index" label="行号" align="center" width="60">
            <template #default="scope">
              <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="true" prop="tradePartnerName" label="客户名称" header-align="center" align="center"
                           width="200"
                           show-overflow-tooltip>
            <template #default="scope">
            <span v-show="!scope.row.isEdit">
              {{ scope.row.tradePartnerName }}
            </span>
              <div :class="{'highlighted-cell': isCellHighlightedtradePartnerName(scope.row)}">
                <el-input
                    readonly
                    :title="scope.row.tradePartnerName"
                    v-show="scope.row.isEdit"
                    v-model="scope.row.tradePartnerName"
                >
                  <template #append>
                    <el-button :icon="Search" @click="ksDialog( scope.$index)"/>
                  </template>
                </el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column v-if="true" prop="qty" label="计划量" header-align="center" align="center" width="180"
                           show-overflow-tooltip>
            <template #default="scope">
            <span v-show="!scope.row.isEdit">
              {{ scope.row.qty }}
            </span>
              <div :class="{'highlighted-cell': isCellHighlightedqty(scope.row)}">
              <el-input-number v-show="scope.row.isEdit" v-model="scope.row.qty" :title="scope.row.qty"
                               style="width: 100%" min="0" :precision="2" @change="qtyChange($event, scope.$index)"
                               controls-position="right"></el-input-number>
              </div>
            </template>
          </el-table-column>
          <el-table-column v-if="true" prop="priceCash" label="现汇价格" header-align="center" align="center"
                           show-overflow-tooltip>
            <template #default="scope">
            <span v-show="!scope.row.isEdit">
              {{ scope.row.priceCash }}
            </span>
              <el-input-number v-show="scope.row.isEdit" v-model="scope.row.priceCash" :title="scope.row.priceCash"
                               style="width: 100%" min="0" :precision="2" :step="0.1"
                               controls-position="right"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column v-if="true" prop="priceBill" label="承兑价格" header-align="center" align="center"
                           show-overflow-tooltip>
            <template #default="scope">
            <span v-show="!scope.row.isEdit">
              {{ scope.row.priceBill }}
            </span>
              <el-input-number v-show="scope.row.isEdit" v-model="scope.row.priceBill" :title="scope.row.priceBill"
                               style="width: 100%" min="0" :precision="2" :step="0.1"
                               controls-position="right"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column v-if="true" prop="remark" label="备注" header-align="center" align="center"
                           show-overflow-tooltip>
            <template #default="scope">
            <span v-show="!scope.row.isEdit">
              {{ scope.row.remark }}
            </span>
              <el-input
                  :title="scope.row.remark"
                  v-show="scope.row.isEdit"
                  v-model="scope.row.remark"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" header-align="center" align="center" width="240px">
            <template #default="scope">
              <el-button plain type="warning" v-if="!scope.row.isEdit" @click="rowEdit(scope.row)">编辑</el-button>
              <el-button plain type="success" v-else @click="rowEditSave(scope.row , scope.$index)">保存</el-button>
              <el-button plain type=""  @click="rowCopy(scope.row)">复制</el-button>
              <el-button plain type="danger" @click="rowRemove(scope.row ,scope.$index)">删除</el-button>
            </template>
          </el-table-column>

        </el-table>
      </el-card>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="planNoSave()" v-if="planNoShow" plain>生成计划编号</el-button>
          <el-button type="success" @click="handleSave(ruleFormRef)"  v-else  plain>保存</el-button>
          <el-button type="danger" @click="handleCancelSave" plain>取消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog class="diaClass" :close-on-click-modal="false" draggable title="查看" v-model="dialogVisibleCk"
               width="1200px"
               top="5vh" @open="openDialog">
      <el-card>

        <el-form :model="form" label-width="120px" label-position="right" inline ref="ruleFormRef" :rules="rules">
          <el-row>
            <el-col :span="8">
              <el-form-item label="物料编码" prop="itemCd">
                <el-input v-model="form.itemCd" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="物料名称" prop="itemNm">
                <el-input v-model="form.itemNm" readonly>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="申请日期" prop="applyDt">
                <el-input v-model="form.applyDt" readonly></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>

            <el-col :span="8">
              <el-form-item label="年份" prop="year">
                <el-input v-model="form.year" readonly></el-input>

              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="计量单位" prop="uom">
                <Selector_component :option-list="dictList.MEASURING_UNIT" :value="form.uom" :allow-select="true"
                                    @change="collectionTySelect"></Selector_component>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="规格型号" prop="specType" >
                <el-input v-model="form.specType" readonly></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="specType">
                <el-input readonly
                    v-model="form.remark"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    type="textarea"
                    placeholder=""
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

      </el-card>

      <el-card class="box-card" v-show="true">
        <el-table :data="tableDataMx" border highlight-current-row>
          <el-table-column type="index" label="行号" align="center" width="60">
            <template #default="scope">
              <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="true" prop="tradePartnerName" label="客户名称" header-align="center" align="center"
                           width="240"
                           show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="true" prop="qty" label="计划量" header-align="center" align="center"
                           show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="true" prop="priceCash" label="现汇价格" header-align="center" align="center"
                           show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="true" prop="priceBill" label="承兑价格" header-align="center" align="center"
                           show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="true" prop="remark" label="备注" header-align="center" align="center"
                           show-overflow-tooltip>
          </el-table-column>

        </el-table>
      </el-card>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" @click="handleCancelSaveInfo" plain>取消</el-button>
        </div>
      </template>
    </el-dialog>


    <Popup_base_wl ref="PopupRef" @receive-from-child="retu"></Popup_base_wl>

    <Popup_base_ks ref="PopupRefKs" @receive-from-child="retuKs"></Popup_base_ks>
  </div>
</template>

<script setup>
import ButtonBar from '@/components/ButtonBar.vue'

import {
  ref,
  reactive,
  onMounted,
  getCurrentInstance
} from 'vue'

const {
  proxy
} = getCurrentInstance()

import style from '@/tools/style'
import Selector_component from "@/views/sal/components/Selector_component.vue";
import Popup_base_wl from "@/views/bas/Popup_base_wl.vue";
import {Search} from '@element-plus/icons-vue'
import Popup_base_ks from "@/views/bas/Popup_base_ks.vue";
import {workflowCancel, workflowSubmit} from "@/tools/workflow.js";
const cardBodyStyle = ref(style.card)


onMounted(() => {
  handleSearch()
  dictData()
  updateViewportHeight()
})


/**
 *   查询
 */




const query = ref({})
const tableData = ref([])
const tableDataMx = ref([])
const handleSearch = () => {
  currentPage.value = 1
  getTableData()
}


const getTableData = () => {
  var url = 'sal/PlanHead/query'
  var param = {
    page: currentPage.value,
    rows: pageSize.value,
    params: JSON.stringify(query.value)
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      tableData.value = response.data.data.records
      totalRows.value = response.data.data.total
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
/**
 *   查询
 */

/**
 * 分页
 */
const currentPage = ref(1)
const totalRows = ref(0)
const pageSizes = ref([ 10, 20, 30, 40])
const pageSize = ref(10)
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  getTableData()
}
/**
 * 分页
 */


/**
 * 新增
 */
const dialogVisible = ref(false)
const dialogVisibleCk = ref(false)
const form = ref({
  deptNm: "",
  itemCd: "",
  itemNm: "",
  stlGrd: "",
  specType: "",
  year: "",
  applyDt: "",
  uom: "",
  remark: "",
})
const ruleFormRef = ref()
// 校验
const rules = reactive({
  itemCd: [
    {required: true, message: '不允许为空', trigger: 'blur' | 'change'},
  ],
  itemNm: [
    {required: true, message: '不允许为空', trigger: 'blur' | 'change'},
  ],
  applyDt: [
    {required: true, message: '不允许为空', trigger: 'blur' | 'change'},
  ],
  year: [
    {required: true, message: '不允许为空', trigger: 'blur'},
  ],
  planNo: [
    {required: true, message: '不允许为空', trigger: 'blur' | 'change' },
  ],
})

const handleAdd = () => {
  form.value = {
    itemCd: "",
    itemNm: "",
    year: proxy.$dayjs().format('YYYY'),
    applyDt: proxy.$dayjs().format('YYYY-MM-DD'),
    uom: "",
    remark: "",
  }
  dialogVisible.value = true
  planNoShow.value = true

  tableDataMx.value = []
  // saveHead()
}

const saveHead = () =>{
  var url = 'sal/PlanHead/saveHead'
  var param = {
    json: JSON.stringify({}),
  }

  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == 0) {
      form.value.planNo = response.data.data.planNo
      form.value.id = response.data.data.id
      planNoShow.value = false
    } else {
      ElMessage({
        message: '操作失败' + response.data.msg,
        type: 'error'
      })
    }
  })
}
/**
 * 新增
 */


/**
 * 保存、修改、删除
 */

const openDialog = () => {
}

const handleSave = (ruleFormRef) => {
  ruleFormRef.validate((valid, fields) => {
    if (valid) {
      form.value.lineList = tableDataMx.value
      var url = 'sal/PlanHead/saveHead'
      var param = {
        json: JSON.stringify(form.value),
      }
      console.log(tableDataMx.value)
      if (tableDataMx.value.length <= 0) {
        ElMessage({
          message: '至少需要一条行数据',
          type: 'warning',
        })
        return
      }
      for (var mxi = 0; mxi < tableDataMx.value.length; mxi++) {
        if (tableDataMx.value[mxi].isEdit == true) {
          ElMessage({
            message: '第' + (mxi + 1) + '行数据未保存，请先保存或删除该数据后执行后续操作！',
            type: 'warning',
          })
          return;
        }
      }
      console.log(form.value.year)
      console.log(form.value)

      proxy.$axios.post(url, param).then(response => {
        if (response.data.code == 0) {
          form.value = response.data.data
          ElMessage({
            message: '保存成功',
            type: 'success',
          })
          getTableData()
          dialogVisible.value = false
        } else {
          // ElMessage.error('操作失败！' + response.data.msg)
          ElMessage({
            message: '操作失败' + response.data.msg,
            type: 'error'
          })
        }
      })

    } else {
      console.log('error submit!', fields)
    }
  })
}
const handleCancelSave = () => {
  dialogVisible.value = false
  getTableData()
}
const handleCancelSaveInfo = () => {
  dialogVisibleCk.value = false
}
const handleEdit = (row) => {
  tableDataMx.value = []
  dialogVisible.value = true
  planNoShow.value = false
  form.value = row
  rowLine(row.id)
}
const handleInfo = (row) => {
  tableDataMx.value = []
  dialogVisibleCk.value = true
  form.value = row
  rowLine(row.id)
}
const handleDelete = (row) => {
  ElMessageBox.confirm(
      '确定删除本条记录?',
      '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      }
  )
      .then(() => {
        var url = 'sal/PlanHead/remove'
        var param = {
          id: row.id
        }
        proxy.$axios.post(url, param).then(response => {
          if (response.data.code == 0) {
            ElMessage({
              type: 'success',
              message: '删除成功',
            })
            getTableData()
          } else {
            ElMessage({
              type: 'error',
              message: '删除失败' + response.data.msg
            });
          }
        });
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消',
        })
      })
}

const rowLine = (id) => {
  var url = 'sal/PlanLine/queryAll'
  var param = {
    params: JSON.stringify({fId: id})
  }
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == 0) {
      tableDataMx.value = response.data.data.records
    } else {
      ElMessage({
        type: 'error',
        message: '操作失败' + response.data.msg
      });
    }
  });
}

/**
 * 保存、修改、删除
 */

const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const handleRemoveBatch = () => {
  console.log('handleRemoveBatch')

  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要删除的数据!'
    })
    return
  }

  ElMessageBox.confirm('此操作将删除该数据, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    var ids = []
    multipleSelection.value.forEach((item, index) => {
      ids.push(item.id)
    })
    var url = 'sal/Head/removeBatch'
    var param = {
      ids: JSON.stringify(ids)
    }
    proxy.$axios.post(url, param).then(response => {
      if (response.data.code == '0') {
        ElMessage({
          type: 'success',
          message: '操作成功!',
        });
        getTableData()
        dialogVisible.value = false
      } else {
        ElMessage({
          type: 'error',
          message: '操作失败!' + response.data.msg
        });
      }
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}

const handleEditBatch = () => {
  console.log('handleEditBatch')
  if (multipleSelection.value.length != 1) {
    ElMessage({
      type: 'warning',
      message: '请选择一条数据编辑!'
    })
    return
  }
  handleEdit(multipleSelection.value[0])
}

const handleUpload = () => {
  console.log('handleUpload')
}

const handleDownload = () => {
  console.log('handleDownload')
}

const handleImport = () => {
  console.log('handleImport')
}

const handleExport = () => {
  console.log('handleExport')
}


// 明细 -add row、
const onAddItemWl = () => {

  tableDataMx.value.push({
    isInsert: true,
    isEdit: true,
    tradePartnerName: "",
    tradePartnerId: "",
    tradePartnerCode: "",
    qty: "",
    priceCash: "",
    priceBill: "",
    remark: "",
  })
}
// row 编辑
const rowEdit = (scope) => {
  scope.isEdit = true
}

const rowEditSave = (scope, index) => {
  if (!scope.tradePartnerName) {
    ElMessage({
      message: '请选择客商',
      type: 'warning',
    })
    tableDataMx.value[index].tradePartnerNamestatus = 'warning'
    return
  }
  if (scope.qty == 0) {
    ElMessage({
      message: '计划量不允许为0',
      type: 'warning',
    })
    tableDataMx.value[index].qtystatus = 'warning'
    return
  }

  // scope.isEdit = false
  // scope.fId = form.value.id
  // tableDataMx.value[index].isEdit = false
  tableDataMx.value[index].fId = form.value.id
  saveRow(tableDataMx.value[index],index)
}

const saveRow = (row,index) =>{
  var url = 'sal/PlanLine/save'
  var param = {
    json: JSON.stringify(row),
  }

  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == 0) {
      ElMessage({
        message: '数据添加成功',
        type: 'success'
      })
      tableDataMx.value[index].id = response.data.data.id
      tableDataMx.value[index].isEdit = false
    } else {
      ElMessage({
        message: '操作失败' + response.data.msg,
        type: 'error'
      })

    }
  })
}
const copySaveRow = (row) =>{
  var url = 'sal/PlanLine/save'
  var param = {
    json: JSON.stringify(row),
  }

  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == 0) {
      ElMessage({
        message: '数据添加成功',
        type: 'success'
      })
      tableDataMx.value.push(response.data.data)
    } else {
      ElMessage({
        message: '操作失败' + response.data.msg,
        type: 'error'
      })

    }
  })

}
const loading = ref(false)
// 行复制
const rowCopy = (row) => {
  var copy = {
    isInsert: true,
    isEdit: true,
    tradePartnerName: row.tradePartnerName,
    tradePartnerId: row.tradePartnerId,
    tradePartnerCode: row.tradePartnerCode,
    qty: row.qty,
    priceCash: row.priceCash,
    priceBill: row.priceBill,
    remark: row.remark,
    fId: row.fId
  }

  tableDataMx.value.push(copy)

  // copySaveRow(copy)
}
//  行删除
const rowRemove = (row,index) => {
  tableDataMx.value.splice(index, 1)
  if (row.id){
    rowDelete(row.id)
  }

}

const rowDelete = (id) =>{
  var url = 'sal/PlanLine/remove'
  var param = {
    id: id,
  }

  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == 0) {
      ElMessage({
        message: '数据删除成功',
        type: 'success'
      })

    } else {
      ElMessage({
        message: '操作失败' + response.data.msg,
        type: 'error'
      })
    }
  })
}

const dictList = ref({})
const dictData = () => {
  var url = 'framework/Common/querySelectorList'
  var param = {
    type: JSON.stringify(['MEASURING_UNIT' , 'item_sort3'])
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      dictList.value = response.data.data
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })

}


const collectionTySelect = (val) => {
  form.value.uom = val
}
const PopupRef = ref(null)
const itemDialog = () => {
  PopupRef.value.open()
}
const retu = (val) => {
  console.log("val", val)
  form.value.itemCd = val.itemCd
  form.value.itemId = val.id
  form.value.itemNm = val.itemNm
  form.value.itemType = val.itemType
  form.value.uom = val.unit

}
const retuKs = (val) => {
  console.log("val", val)
  tableDataMx.value[tableKsIndex.value].tradePartnerName = val.tradePartnerName
  tableDataMx.value[tableKsIndex.value].tradePartnerId = val.id
  tableDataMx.value[tableKsIndex.value].tradePartnerCode = val.tradePartnerCode
  tableDataMx.value[tableKsIndex.value].tradePartnerNamestatus = 'success'

  for(var i = 0; i < tableDataMx.value.length ; i++){
    if (tableDataMx.value[i].tradePartnerId == val.tradePartnerId){
      // 存在重复，
      tableDataMx.value[tableKsIndex.value].tradePartnerNamestatus = 'warning'
    }
  }
}
const formatter = (row, column, cellValue, index) => {
  if (!cellValue || cellValue == null || cellValue == '') {
    return cellValue
  }
  switch (column.property) {
    case 'uom':
      cellValue = dictList.value.MEASURING_UNIT.find(item => item.dicCode == cellValue).dicName
      break;
  }
  return cellValue
}

const PopupRefKs = ref(null)
const tableKsIndex = ref(null)
const ksDialog = (index) => {
  tableKsIndex.value = index
  PopupRefKs.value.open()
}
const submit = () => {
  ElMessage({
    type: 'info',
    message: '暂不支持提交'
  })
}

const download = () => {
  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要打印预览的数据!'
    })
    return
  }
  if (multipleSelection.value.length > 1) {
    ElMessage({
      type: 'warning',
      message: '选择打印的数据不能超过1条，请调整!'
    })
    return
  }
  // location.href = import.meta.env.VITE_BASE_API +
  //     '/sal/PlanHead/download?id=' + encodeURIComponent(multipleSelection.value[0].id)+ "&user="+ localStorage.getItem('userId') ;
  var url = import.meta.env.VITE_BASE_API +
      '/sal/PlanHead/download?id=' + encodeURIComponent(multipleSelection.value[0].id)+ "&user="+ localStorage.getItem('userId') ;

// 在新窗口打开该 URL
  window.open(url, '_blank');


}

const isCellHighlightedtradePartnerName = (row) => {

  return row.tradePartnerNamestatus === 'warning'; // 根据状态高亮单元格
};
const isCellHighlightedqty = (row) => {

  return row.qtystatus === 'warning'; // 根据状态高亮单元格
};
const qtyChange = (val , index) => {
  if (val > 0){
    tableDataMx.value[index].qtystatus = 'success'

  } else {
    tableDataMx.value[index].qtystatus = 'warning'
  }
};

const height = ref(600)
const updateViewportHeight = () => {
  height.value = window.innerHeight * 0.65
  console.log( window.innerHeight);
};

const planNoShow = ref(true)
const planNoSave = () =>{
  saveHead()
}
const flowId = ref('SalPlanFinance')
const handleSubmit = (row) => {
  ElMessageBox.confirm(
      '确定提交流程?',
      '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      }
  ).then(() => {
    var obj = {
      id : row.id
    }
    return workflowSubmit(
        flowId.value,
        '销售计划审批流程',
        '初始化提交',
        JSON.stringify(obj),
        row.workId,
        row.trackId)
  }).then((result) => {
    if(result.status === 'success'){

      console.log(result)
      // 将结果返回的workId和trackId保存
      var url = 'sal/PlanHead/submitFq'
      var process = {
        'id': row.id,
        'workId': result.workId,
        'trackId': result.trackId,
      }
      var param = {
        json: JSON.stringify(process),
      }
      proxy.$axios.post(url, param).then(response => {
        if (response.data.code === 0) {
          // form.value = response.data.data
          ElMessage({
            type: 'success',
            message: '提交审批成功',
          })
          getTableData()
        }
      })
    }
    else{
      ElMessage({
        type: 'error',
        message: '提交审批失败' + response.data.msg
      });
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消提交',
    })
  })
}


const handleDetail = (row) => {
  if(row.workId === null){
    ElMessage({
      type: 'info',
      message: '无法查看',
    })
  }else {

    sessionStorage.setItem('workflowQuery', JSON.stringify({
      flowId: flowId.value,
      workId: row.workId,
      trackId: row.trackId,
      date:new Date().getTime()
    }))

    proxy.$router.push({
      path: '/workflow/detail',
    })

  }
}

const handleCancel = (row) => {
  ElMessageBox.confirm(
      '确定撤回审批?',
      '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      }
  ).then(() => {
    return workflowCancel(row.workId, row.trackId);
  }).then((result) => {
    if(result.status === 'success'){
      ElMessage({
        type: 'success',
        message: '撤回审批成功',
      })
      getTableData()
    }else {
      ElMessage({
        type: 'error',
        message: '撤回审批失败，' + result.msg
      });
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消提交',
    })
  })
}

</script>

<style scoped>
::v-deep .diaClass .el-form-item {
  width: 100%
}
.el-form-item {
  width: 100%
}
::v-deep .el-dialog__body {
  background-color: #F2F6FC;
}

.el-date-editor--date {
  width: 100%;
}

.highlighted-cell {
  border: 1px solid red;
  border-radius: 5px;
  //padding: 1px;
  //color: #67c23a;
}
</style>
