<template>
  <div class="mainContentBox">
    <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"
      :before-open="beforeOpenDialog"
    >
      <template #menu-left="{ size }">
        <el-button
          :disabled="toDeleteIds.length < 1"
          type="danger"
          icon="el-icon-delete"
          :size="size"
          @click="multipleDelete"
          >删除</el-button
        >
      </template>

      <template #menu="{ size, row, index }">
        <el-button
          icon="el-icon-refresh"
          text
          @click="queryDiffList(row.id)"
          type="primary"
          :size="size"
          >同步</el-button
        >
      </template>

      <template #customFieldName-form="scope">
        <el-select
          v-model="customFieldNameValues"
          multiple
          filterable
          allow-create
          default-first-option
          :disabled="isDisabled"
          :reserve-keyword="false"
          placeholder="请输入名称，按回车创建"
          @change="customFieldChange"
        >
          <el-option
            v-for="item in customFieldOptions"
            :key="item.value"
            :label="item.value"
            :value="item.value"
          />
        </el-select>
      </template>

      <template #menu-right="{}">
        <el-dropdown split-button
          >导入
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                @click="downloadTemplate('/api/v1/op/baseOperation/template')"
              >
                <i-ep-download />下载模板
              </el-dropdown-item>
              <el-dropdown-item @click="importExcelData">
                <i-ep-top />导入数据
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <!-- <el-button
          class="ml-3"
          @click="exportData('/api/v1/plan/order/export')"
        >
          <template #icon> <i-ep-download /> </template>导出
        </el-button> -->
      </template>
    </avue-crud>
    <ExcelUpload ref="uploadRef" @finished="uploadFinished" />
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="950px"
      @close="dialog.visible = false"
    >
      <div style="width: 100%; height: 10px; color: #fa0303">
        已经开始生产的工艺路线,请到工艺路线中进行单个更改!!!
      </div>
      <difference :diffList="diffList" @syncList="clickSyncList" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">同 步</el-button>
          <el-button @click="dialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, getCurrentInstance } from "vue";
import { useCrud } from "@/hooks/userCrud";
import { useCommonStoreHook, useDictionaryStore } from "@/store";
import { syncOperation, checkSyncList } from "@/api/craft/process";
import difference from "./component/difference.vue";
// 数据字典相关
const { dicts } = useDictionaryStore();
const dialog = reactive({
  title: "差异列表",
  visible: false,
});
const isDisabled = ref(false);
// 传入一个url，后面不带/
const { form, data, option, search, page, toDeleteIds, Methords, Utils } =
  useCrud({
    src: "/api/v1/op/baseOperation",
  });
const { dataList, createRow, updateRow, deleteRow, searchChange, resetChange } =
  Methords; //增删改查
const { selectionChange, multipleDelete } = Methords; //选中和批量删除事件
const { checkBtnPerm, downloadTemplate, exportData } = Utils; //按钮权限等工具

const crudRef = ref(null); //crudRef.value 获取avue-crud对象

const clickObjId = ref(null);

const clickSyncRouteList = ref([]);
onMounted(() => {
  // console.log("crudRef", crudRef)
  dataList();
});
const clickSyncList = (list) => {
  clickSyncRouteList.value = list;
};
const handleSubmit = () => {
  if (clickSyncRouteList.value.length > 0) {
    syncOperation({
      baseId: clickObjId.value,
      routeIds: clickSyncRouteList.value,
    }).then((data) => {
      if (data.code === "200") {
        clickSyncRouteList.value = [];
        dialog.visible = false;
        ElMessage.success(data.msg);
      } else {
        ElMessage.error(data.msg);
      }
    });
  } else {
    ElMessage.error("请选择需要同步的数据");
  }
};
const diffList = ref([]);

/**
 * 上传excel相关
 */
const uploadRef = ref(null);
const uploadFinished = () => {
  // 上传完成后的刷新操作
  page.currentPage = 1;
  dataList();
};
const importExcelData = () => {
  if (uploadRef.value) {
    uploadRef.value.show("/api/v1/op/baseOperation/import");
  }
};

// 设置表格列或者其他自定义的option
const switchOp = [
  {
    label: "否",
    value: 0,
  },
  {
    label: "是",
    value: 1,
  },
];

// 自定义工序项目字段名称相关方法
const customFieldNameValues = ref([]);
const customFieldOptions = [];
const customFieldChange = (val) => {
  let result = Array.from(val);
  result = result.map((item) => {
    return {
      value: item,
      isSelected: true,
    };
  });

  form.value.customFieldName = JSON.stringify(result);
};

const queryDiffList = (id) => {
  clickObjId.value = id;
  checkSyncList(id).then((data) => {
    if (data.data) {
      diffList.value = [];
      dialog.visible = true;
      data.data.forEach((item) => {
        diffList.value.push(item);
      });
    }
  });
};
const beforeOpenDialog = (done, type, loading) => {
  if (
    form.value.customFieldName &&
    JSON.parse(form.value.customFieldName)?.length > 0
  ) {
    customFieldOptions.value = JSON.parse(form.value.customFieldName);
    customFieldNameValues.value = customFieldOptions.value.map(
      (item) => item.value
    );
  }
  if (type == "view") {
    isDisabled.value = true;
  } else {
    isDisabled.value = false;
  }
  if (
    !form.value.customFieldName ||
    JSON.parse(form.value.customFieldName)?.length == 0
  ) {
    customFieldNameValues.value = [];
  }
  done();
};

option.value = Object.assign(option.value, {
  searchEnter: true,
  selection: true,
  labelWidth: 120,
  column: [
    {
      label: "工序名称",
      prop: "operationName",
      span: 12,
      search: true,
      rules: [
        {
          required: true,
          message: "工序名称不能为空",
          trigger: "blur",
        },
      ],
    },
    {
      label: "工序编码",
      prop: "operationCode",
      span: 12,
      search: true,
      display: false,
    },
    {
      label: "工段",
      prop: "workSection",
      type: "select",
      search: true,
      dicData: dicts.workshop_section,
      props: {
        label: "dictLabel",
        value: "dictValue",
      },
      span: 12,
      rules: [
        {
          required: true,
          message: "请选择工段",
          trigger: "change",
        },
      ],
    },
    {
      label: "工序类型",
      prop: "operationType",
      type: "select",
      search: true,
      dicData: dicts.process_type,
      props: {
        label: "dictLabel",
        value: "dictValue",
      },
      span: 12,
      rules: [
        {
          required: true,
          message: "请选择工序类型",
          trigger: "change",
        },
      ],
    },
    {
      label: "工艺条件",
      prop: "processAsk",
      span: 12,
      minWidth: 300,
      rules: [
        {
          required: true,
          message: "工艺条件不能为空",
          trigger: "blur",
        },
      ],
    },
    {
      label: "技能要求",
      prop: "skillAsk",
      span: 12,
      type: "select",
      search: true,
      filterable: true,
      dicData: dicts.skill_requirements,
      props: {
        label: "dictLabel",
        value: "dictValue",
      },
      rules: [
        {
          required: true,
          message: "请选择技能要求",
          trigger: "change",
        },
      ],
    },
    /*{
      label: "后置时间(分)",
      prop: "forceTime",
      type: "number",
      span: 12,
      rules: [
        {
          required: true,
          message: "后置时间不能为空",
          trigger: "blur",
        },
      ],
    },*/
    /*{
      label: "标准机时",
      prop: "timeingNum",
      type: "number",
      span: 12,
      rules: [
        {
          required: true,
          message: "标准机时不能为空",
          trigger: "blur",
        },
      ],
    },*/
    {
      label: "标准工时(分)",
      prop: "standardWorktime",
      type: "number",
      span: 12,
      rules: [
        {
          required: true,
          message: "标准工时不能为空",
          trigger: "blur",
        },
      ],
    },

    {
      label: "目标值(%)",
      prop: "targetRate",
      type: "number",
      max: 100,
      min: 0,
      span: 12,
      rules: [
        {
          required: true,
          message: "目标值不能为空",
          trigger: "blur",
        },
      ],
    },
    // {
    //   label: '岗位',
    //   prop: 'type',
    //   type: 'select',
    //   dicData: [
    //     {
    //       label: '岗位1',
    //       value: 'position1',
    //     },
    //   ],
    //   props: {
    //     label: 'label',
    //     value: 'value',
    //   },
    //   span: 12,
    // },
    {
      label: "工位类型",
      prop: "stanType",
      search: true,
      type: "select",
      dicData: dicts.station_type,
      props: {
        label: "dictLabel",
        value: "dictValue",
      },
      span: 12,
      rules: [
        {
          required: true,
          message: "请选择工位类型",
          trigger: "blur",
        },
      ],
    },
    {
      label: "工序标注",
      prop: "operationLabel",
      span: 12,
      rules: [
        {
          max: 16,
          message: "工序标注不能超过16个字符",
          trigger: "blur",
        },
      ],
    },
    {
      label: "方法",
      prop: "method",
      span: 12,
    },
    {
      label: "试验规程编号",
      prop: "testPlanCode",
      span: 12,
    },
    {
      label: "是否可跳过",
      prop: "skipped",
      span: 8,
      hide: true,
      type: "switch",
      dicData: switchOp,
      value: 0,
    },
    {
      label: "是否关键工序",
      prop: "keyProcesses",
      span: 8,
      type: "switch",
      dicData: switchOp,
      value: 0,
    },
    {
      label: "是否特殊工序",
      prop: "isSpecial",
      span: 8,
      type: "switch",
      dicData: switchOp,
      value: 0,
    },
    {
      label: "是否禁用",
      prop: "enabled",
      hide: true,
      span: 8,
      type: "switch",
      dicData: switchOp,
      value: 0,
    },
    //  {
    //    label: "是否外协",
    //    prop: "externalCooperation",
    //    span: 8,
    // hide: true,
    //    type: "switch",
    //    dicData: switchOp,
    //    value: 0,
    //  },
    /*{
      label: "是否首检",
      prop: "firstCheck",
      span: 8,
      hide: true,
      type: "switch",
      dicData: switchOp,
      value: 0,
    },*/
    /*{
      label: "是否巡检",
      prop: "inspection",
      span: 8,
      hide: true,
      type: "switch",
      dicData: switchOp,
      value: 0,
    },
    {
      label: "是否自检",
      prop: "selfCheck",
      span: 8,
      hide: true,
      type: "switch",
      dicData: switchOp,
      value: 0,
    },*/
    {
      label: "批量报工",
      prop: "batchReport",
      span: 8,
      hide: true,
      type: "switch",
      dicData: switchOp,
      value: 1,
    },
    //  {
    //    label: "是否工艺数量",
    //    prop: "common",
    //    span: 8,
    // hide: true,
    //    type: "switch",
    //    dicData: switchOp,
    //    value: 0,
    //  },
    //  {
    //    label: "是否分批",
    //    prop: "batch",
    //    span: 8,
    // hide: true,
    //    type: "switch",
    //    dicData: switchOp,
    //    value: 0,
    //  },
    {
      label: "是否合批",
      prop: "merge",
      span: 8,
      hide: true,
      type: "switch",
      dicData: switchOp,
      value: 0,
      //联动隐藏
      control: (val, form) => {
        return {
          mergeNum: {
            display: val == 1 ? true : false,
          },
        };
      },
    },
    {
      label: "是否自定义名称",
      prop: "customEnable",
      span: 8,
      hide: true,
      type: "switch",
      dicData: switchOp,
      value: 0,
      //联动隐藏
      control: (val, form) => {
        return {
          customFieldName: {
            display: val == 1 ? true : false,
          },
        };
      },
    },
    {
      label: "自定义工序项目字段名称",
      prop: "customFieldName",
      hide: true,
      span: 24,
    },

    /*{
      label: "是否委外",
      prop: "outsourcing",
      span: 8,
      hide: true,
      type: "switch",
      dicData: switchOp,
      // click: ({ column,value }) => {
      //  if(value == 0){
      // console.log('column',column)
      //  }
      // },
      //联动隐藏
      control: (val, form) => {
        return {
          outTime: {
            display: val == 1 ? true : false,
          },
        };
      },
      value: 0,
    },*/
    {
      label: "合批数量",
      prop: "mergeNum",
      span: 5,
      hide: true,
      display: false,
      value: 0,
    },
    {
      label: "分批数量",
      prop: "batchNum",
      span: 5,
      display: false,
      hide: true,
      value: 0,
      // slot:true, // 自定义列
    },
    {
      label: "委外时间",
      prop: "outTime",
      span: 5,
      display: false,
      hide: true,
      value: 0,
      // slot:true, // 自定义列
    },
    {
      label: "工序描述",
      prop: "operationDesc",
      hide: true,
      span: 24,
      type: "textarea",
    },
    /*{
      label: "备注",
      prop: "remark",
      hide: true,
      span: 24,
      type: "textarea",
    },*/
  ],
});
</script>
