<script setup>
import { ref, getCurrentInstance } from "vue";
import { useCrud } from "@/hooks/userCrud";

import dictDataUtil from "@/common/configs/dictDataUtil";
import {addBatch, queryFilter} from "@/api/statistic/categoryDetail";
// 传入一个url，后面不带/
const { form, data, option, search, page, toDeleteIds, Methords, Utils } =
  useCrud({
    src: "/api/v1/category/detail",
  });
const { dataList, createRow, updateRow, deleteRow, searchChange, resetChange } =
  Methords; //增删改查
const { selectionChange, multipleDelete } = Methords; //选中和批量删除事件
const { checkBtnPerm, downloadTemplate, exportData } = Utils; //按钮权限等工具
const tablesData = ref([]);
const crudRef = ref(null); //crudRef.value 获取avue-crud对象

const startToChooseProcess = () => {
  commonTableRef.value?.mergeOption({
    selection: true,
    reserveSelection: true,
  });
  commonTableRef.value?.startSelect({ targetId: targetId.value });
};
const doEdit = (row, index) => {
  row.operationCodes = row.operationCode;
  crudRef.value && crudRef.value.rowEdit(row, index);
};
// 设置表格列或者其他自定义的option
option.value = Object.assign(option.value, {
  viewBtn: false,
  addBtn: false,
  editBtn: false,
  column: [
    {
      label: "工序编码",
      prop: "operationCode",
      display: false,
      search: "true",


    },
    {
      label: "工序编号",
      prop: "operationCodes",
      readonly: true,
      editDisabled: true,
      hide: true,
      rules: [
        {
          required: true,
          message: "请选择工序编码",
          trigger: "blur",
        },
      ],
      click: () => {
        startToChooseProcess();
      },
    },
    {
      label: "工序名称",
      prop: "operationName",
      search: "true",
      disabled: "true",
    },

    {
      label: "目标值(%)",
      prop: "target",
      type: "number",
      min: 0,
      max: 100,
      rules: [
        {
          required: true,
          message: "请输入目标值",
          trigger: "blur",
        },
      ],
    },
  ],
});

const visible = ref(false);
const targetId = ref(null);
const toShowDrawer = (row) => {
  targetId.value = row.id;
  search.value.targetId = targetId.value;
  form.value.targetId = targetId.value;
  visible.value = true;
  dataList();
};

defineExpose({
  toShowDrawer,
});
const dialog = ref({
  visible: false,
  title: "新增工序目标值",
});
const multiple=ref(true);
const commonTableRef = ref({});
const commonTableType = ref("PROCESS_SELECT");
const saixuan = ref({operationCode:'QBSX-0001',operationName:'筛选'});
const onSelectedFinish = (row) => {
  if(!row||row.length==0){
    ElMessage.error("未选择任何工序!");
    return;
  }
  if(row.isSelect==="1"){
    ElMessage.error("该工序已被选过，不可再次选择!");
    return;
  }
  dataTable.value=row;
  queryFilter({targetId:targetId.value}).then(
      (data)=>{
        if(data.code==='200'){
          if(!data.data){
            dataTable.value.push(saixuan.value);
          }

        }
      }
  )
};
const openDialog = () =>{
  dialog.value.visible=true;
}

const closeDialog=()=>{
  dialog.value.visible = false
  dataTable.value=[];
}
const dataTable=ref([]);
const delRow = (index) => {
  dataTable.value.splice(index, 1);
};
const handleSubmit = () => {
   for(let i=0;i<dataTable.value.length;i++){
      if(!dataTable.value[i].target){
         ElMessage.error("第"+(i+1)+"行未填写目标值!");
         return;
      }
     dataTable.value[i].targetId=targetId.value
     dataTable.value[i].id=null
   }
  addBatch(dataTable.value).then(
      (res)=>{
        if(res.code==='200'){
          ElMessage.success("操作成功!");
          dialog.value.visible=false;
          dataList();
        }
      }
  )
}
</script>

<template>
  <div>
    <el-drawer size="60%" append-to-body v-model="visible">
      <avue-crud
        ref="crudRef"
        v-model:search="search"
        v-model="form"
        :data="data"
        :option="option"
        v-model:page="page"
        @row-save="createRow"
        @row-update="updateRow"
        @row-del="deleteRow"
        @search-change="searchChange"
        @search-reset="resetChange"
        @size-change="dataList"
        @current-change="dataList"
        @selection-change="selectionChange"
      >
        <template #menu-left="{ size }">
          <el-button
              type="primary"
              icon="el-icon-plus"
              :size="size"
              @click="openDialog"
          >新增</el-button
          >
        </template>
        <template #menu="{ row }">
          <el-button
              link
              type="primary"
              icon="el-icon-edit"
              @click="doEdit(row, index)"
          >编辑</el-button
          ></template>
      </avue-crud>
    </el-drawer>
    <CommonTable
      ref="commonTableRef"
      tableTitle="选择工序"
      :multipleRow="multiple"
      :tableType="commonTableType"
      @selected-sure="onSelectedFinish"
    />
    <el-dialog v-model="dialog.visible"
               :title="dialog.title"
               width="80%"
               @close="closeDialog"
               :destroy-on-close="true">
      <el-button
          type="primary"
          icon="el-icon-plus"
          @click="startToChooseProcess"
      >新增</el-button>
      <el-table :data="dataTable" :gutter="24">
        <el-table-column prop="operationCode" label="工序编码"  />
        <el-table-column prop="operationName" label="工序名称"  />
        <el-table-column prop="target" label="目标值(%)">
          <template #default="{ scope, row }">
            <el-input-number
                v-model="row.target"
                :precision="2"
                min="0.01"
                max="100"
                controls-position="right"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作">
          <template #default="{ scope, row }">
            <el-button
                link
                type="danger"
                size="small"
                v-if="row.operationCode!='QBSX-0001'"
                @click="delRow(scope.$index)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="dialog-footer" style="margin-top: 20px" align="center">
        <el-button
            type="primary"
            v-if="dataTable.length > 0"
            @click="handleSubmit"
        >保 存</el-button
        >
        <el-button @click="closeDialog">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss"></style>
