<template>
  <div class="mainContentBox">
    <avue-crud
      ref="crudRef"
      v-model:search="search"
      v-loading="loading"
      v-model="form"
      :data="data"
      :option="option"
      v-model:page="page"
      :permission="permission"
      @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 #isImportant="scope">
        <el-switch
          :active-value="1"
          :inactive-value="0"
          inline-prompt
          active-text="是"
          inactive-text="否"
          v-model="scope.row.isImportant"
          @click="changeItem(scope.row)"
          class="ml-2"
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
        />
      </template>
      <template #menu-left="{ size }">
        <el-button
          :disabled="toDeleteIds.length < 1"
          type="danger"
          icon="el-icon-delete"
          :size="size"
          @click="multipleDelete"
          >删除</el-button
        >
        <el-button
          :disabled="toDeleteIds.length < 1"
          type="primary"
          icon="el-icon-primary"
          :size="size"
          @click="aps1"
          >批量排程</el-button
        >
      </template>
      <template #menu="{ size, row, index }">
        <el-button
          v-hasPerm="[buttonPermission.PLAN.BTNS.work_order_edit]"
          v-if="
            row.workOrderState === '0' ||
            row.workOrderState === '1' ||
            row.workOrderState === '2'
          "
          type="primary"
          link
          size="small"
          @click="handleEdit(row, 0)"
          ><i-ep-edit />编辑
        </el-button>
        <el-button
          @click="aps(row.id)"
          icon="el-icon-setting"
          text
          v-hasPerm="[buttonPermission.PLAN.BTNS.work_order_aps]"
          v-if="
            row.workOrderState === '0' ||
            row.workOrderState === '1' ||
            row.workOrderState === '2'
          "
          type="primary"
          :size="size"
          >排程</el-button
        >
        <el-button
          icon="el-icon-setting"
          text
          v-hasPerm="[buttonPermission.PLAN.BTNS.work_order_lock]"
          v-if="row.workOrderState === '4'"
          @click="lockOrUnLockWorkOrder(row.id, 5)"
          type="primary"
          :size="size"
          >冻结</el-button
        >
        <el-button
          icon="el-icon-setting"
          text
          v-if="row.workOrderState === '5'"
          v-hasPerm="[buttonPermission.PLAN.BTNS.work_order_lock]"
          @click="lockOrUnLockWorkOrder(row.id, 4)"
          type="primary"
          :size="size"
          >解冻</el-button
        >
        <el-button
          icon="el-icon-setting"
          text
          v-if="row.workOrderState === '2'"
          @click="distribute(row.id)"
          type="primary"
          v-hasPerm="[buttonPermission.PLAN.BTNS.work_order_aps]"
          :size="size"
          >下发</el-button
        >
        <el-button
          icon="el-icon-setting"
          text
          @click="showSeqPage(row)"
          type="primary"
          :size="size"
          >产品管号</el-button
        >
        <el-button
          icon="el-icon-delete"
          text
          v-if="row.workOrderState === '3'"
          @click="revoke(row.id)"
          type="primary"
          :size="size"
          >撤销</el-button
        >
        <!-- <el-button
          icon="el-icon-setting"
          text
          @click="showCheckTask(row)"
          type="primary"
          :size="size"
          >检验任务</el-button
        > -->
        <el-button
          icon="el-icon-setting"
          text
          @click="jumpPage(row.workOrderCode, 2)"
          type="primary"
          :size="size"
          >生产准备</el-button
        >

        <el-button
          icon="el-icon-setting"
          text
          @click="showProExcel(row.id)"
          type="primary"
          v-if="row.workOrderState > 3"
          :size="size"
          >生产随工单</el-button
        >

        <el-button
          icon="el-icon-setting"
          text
          @click="exportDataZip(row.id)"
          type="primary"
          v-if="row.workOrderState === '6'"
          :size="size"
          >生产数据包</el-button
        >

          <el-button
                  icon="el-icon-setting"
                  text
                  @click="scrap(row.id)"
                  type="primary"
                  v-if="row.workOrderState === '4'"
                  :size="size"
                  v-hasPerm="[buttonPermission.PLAN.BTNS.work_order_scrap]"
          >报废</el-button
          >

        <!--        <el-button
          icon="el-icon-notebook"
          text
          v-if="row.workOrderState === '6'"
          @click="workOrderData(row.id)"
          type="primary"
          v-hasPerm="[buttonPermission.PLAN.BTNS.work_order_data]"
          :size="size"
          >生成生产随工单</el-button
        >-->
        <!--        <el-button
          icon="el-icon-download"
          text
          v-if="row.workOrderState === '6'&&row.packageUrl!=='0'"
          @click="downloadTemplate('/api/v1/plan/workOrder/zip/'+row.id)"
          type="primary"
          v-hasPerm="[buttonPermission.PLAN.BTNS.work_order_downLoad]"
          :size="size">下载数据包</el-button>-->
      </template>
    </avue-crud>
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="80%"
      @close="dialog.visible = false"
    >
      <order-page queryType="1" @order-info="orderInfo" />
    </el-dialog>

    <el-dialog
      v-model="dialog1.visible"
      :title="dialog1.title"
      width="80%"
      @close="dialog1.visible = false"
    >
      <choice-route-page
        :processRouteType="processRouteType"
        :material-code="form.materialCode"
        @route-info="routeInfo"
      />
    </el-dialog>

    <el-dialog
      v-model="dialog2.visible"
      :title="dialog2.title"
      width="80%"
      @close="dialog2.visible = false"
    >
      <choice-workshop-page @work-shop-info="workShopInfo" />
    </el-dialog>

    <el-dialog
      v-model="dialog3.visible"
      :title="dialog3.title"
      width="80%"
      @close="dialog3.visible = false"
    >
      <choice-line-page
        :parentCode="form.workshopCode"
        :materialCode="form.materialCode"
        @line-info="lineInfo"
      />
    </el-dialog>

    <el-dialog
      v-model="dialog4.visible"
      :title="dialog4.title"
      width="950px"
      @close="dialog4.visible = false"
    >
      <work-order-seq :workOrderInfo="form" />
    </el-dialog>
    <el-dialog
      v-model="dialog6.visible"
      :append-to-body="true"
      :title="dialog6.title"
      width="1100px"
      @close="dialog6.visible = false"
    >
      <check-task :workOrderInfo="form" />
    </el-dialog>
    <el-dialog
      v-model="dialog5.visible"
      :title="dialog5.title"
      width="450px"
      @close="dialog5.visible = false"
    >
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="rules"
        label-width="150px"
      >
        <el-form-item label="排程时间" prop="apsTime">
          <el-date-picker
            v-model="formData.apsTime"
            type="date"
            style="width: 200px"
            :disabled-date="disabledDate"
            placeholder="请选择时间"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
          />

          <!--        <el-input width="250px" v-model="formData.apsTime" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD"/>-->
        </el-form-item>
        <el-form-item label="优先级" prop="priority" v-if="apsType === 1">
          <el-select
            v-model="formData.priority"
            placeholder="排程类型"
            style="width: 200px"
          >
            <el-option
              v-for="item in apsPriority"
              :label="item.dictLabel"
              :value="item.dictValue"
              :key="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排程类型" prop="apsModel">
          <el-select
            v-model="formData.apsModel"
            placeholder="排程类型"
            style="width: 200px"
          >
            <el-option
              v-for="item in schedulingTypes"
              :label="item.dictLabel"
              :value="item.dictValue"
              :key="item.dictValue"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="dialog5.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 生产随工单 -->
    <el-dialog
      v-model="workOderShow"
      :title="updateTitle"
      @close="workOderShow = false"
      append-to-body
      fullscreen
    >
      <ExcelShowingSGD :data="ExDataObj" @close="closeShow" />
    </el-dialog>

    <el-dialog
      v-model="dialog7.visible"
      :title="dialog7.title"
      width="950px"
      @close="dialog7.visible = false"
    >
      <work-order-page
        queryType="2"
        @order-info="workOrderInfoClick"
        multipleKey="workOrderCode"
      />
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, getCurrentInstance } from "vue";
import { useCrud } from "@/hooks/userCrud";
import buttonPermission from "@/common/configs/buttonPermission";
import ExcelShowingSGD from "./components/ExcelShowingSGD.vue";
import {
    apsWorkOrder,
    distributeWorkOrder,
    revokeWorkOrder,
    lockWorkOrder,
    exportOrder,
    excelWorkOrder,
    workOrderGroupStr, scrapWorkOrder,
} from "@/api/order";
import { useCommonStoreHook } from "@/store";
import dictDataUtil from "@/common/configs/dictDataUtil";
import ChoiceRoutePage from "./components/choice-route-page.vue";
import ChoiceWorkshopPage from "./components/choice-workshop-page.vue";
import WorkOrderSeq from "./components/work-order-seq.vue";
import CheckTask from "./components/check-task.vue";
import { checkPerm } from "@/directive/permission";
import { queryDictDataByType } from "@/api/system/dict";
import { getProExcel } from "@/api/excel";
import { exportDataInfo } from "@/api/order";
import { getJobInfo, getWorkshopData } from "@/api/report";
import ButtonPermKeys from "@/common/configs/buttonPermission";
import { updateWorkOrderInfo } from "@/api/plan";
import {ElMessageBox} from "element-plus";
const { isShowTable, tableType } = toRefs(useCommonStoreHook());
const updateTitle = ref("生产随工单");
const workshopName = ref("");
const router = useRouter();
const workOderShow = ref(false);
const ExDataObj = ref({});
const excelData = ref([]);
const showProExcel = async (id) => {
  const { data, code } = await getProExcel(id);
  if (code == "200") {
    ExDataObj.value = data;
    workOderShow.value = true;
  } else {
    ExDataObj.value = {};
    workOderShow.value = false;
  }
};

const scrap =(val)=>{
  ElMessageBox.confirm("报废后所有操作不可回退, 是否确认报废？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    scrapWorkOrder({workOrderId:val}).then(
        (res)=>{
            if(res.code==='200'){
                ElMessage.success("操作成功");
                dataList();
            }
        }
    )
  });
}
const exportDataZip = async (id) => {
  exportDataInfo(1, id).then((response) => {
    console.log(response);
    try {
      const decoder = new TextDecoder("utf-8");
      const jsonString = decoder.decode(response.data);
      const jsonObject = JSON.parse(jsonString);
      const { code, msg } = jsonObject;
      if (code != "200") {
        ElMessage.error(msg);
      }
    } catch (e) {
      downFile(response);
    }
  });
};

const downFile = (response) => {
  const fileData = response.data;
  const fileName = decodeURI(
    response.headers["content-disposition"].split(";")[1].split("=")[1]
  );
  const fileType =
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";
  const blob = new Blob([fileData], { type: fileType });
  const downloadUrl = window.URL.createObjectURL(blob);
  const downloadLink = document.createElement("a");
  downloadLink.href = downloadUrl;
  downloadLink.download = fileName;
  document.body.appendChild(downloadLink);
  downloadLink.click();
  document.body.removeChild(downloadLink);
  window.URL.revokeObjectURL(downloadUrl);
};
const toShowExcel = (item) => {
  ExDataObj.value = item;
  workOderShow.value = true;
};
const closeShow = () => {
  workOderShow.value = false;
};
const test = () => {
  isShowTable.value = true;
  tableType.value = tableType.value == 1 ? 2 : 1;
};
const processRouteType = ref("");
const permission = ref({});
const disabledDate = (time) => {
  return time.getTime() < Date.now(); // 8.64e7 毫秒数代表一天
};

const jumpPage = (workOrderCode, type) => {
  if (type === 1) {
    router.push("/requisition?workOrderCode=" + workOrderCode);
  } else {
    router.push("/plan/prepare?workOrderCode=" + workOrderCode);
  }
};
const dialog = reactive({
  title: "订单选择",
  visible: false,
});
const dialog1 = reactive({
  title: "工艺选择",
  visible: false,
});
const dialog2 = reactive({
  title: "车间选择",
  visible: false,
});
const dialog3 = reactive({
  title: "产线选择",
  visible: false,
});
const dialog4 = reactive({
  title: "产品管号",
  visible: false,
});
const dialog5 = reactive({
  title: "排程确认",
  visible: false,
});
const dialog6 = reactive({
  title: "检验任务",
  visible: false,
});
const dialog7 = reactive({
  title: "前置工单选择",
  visible: false,
});
const dialog8 = reactive({
  title: "生产随工单列表",
  visible: false,
});
const apsType = ref(0);
const aps = (id) => {
  apsType.value = 0;
  formData.workOrderIds = [id];
  dialog5.visible = true;
};
const showSeqPage = (workOrderCode) => {
  form.value = workOrderCode;
  dialog4.visible = true;
};
const showCheckTask = (workOrderCode) => {
  form.value = workOrderCode;
  dialog6.visible = true;
};
const distribute = (id) => {
  ElMessageBox.confirm("当前操作不可逆,确定下发工单吗?")
    .then(() => {
      distributeWorkOrder(id).then((data) => {
        ElMessage.success(data.msg);
        dataList();
      });
    })
    .catch(() => {
      // catch error
    });
};
const lockOrUnLockWorkOrder = (id, status) => {
  let message = status === "4" ? "解冻" : "冻结";
  ElMessageBox.confirm("当前操作不可逆,确定" + message + "工单吗?")
    .then(() => {
      loading.value = true;
      lockWorkOrder({ id: id, workOrderState: status }).then((data) => {
        loading.value = false;
        ElMessage.success(data.msg);
        dataList();
      });
    })
    .catch(() => {
      // catch error
    });
};
const loading = ref(false);
const excelWork = ref({});
const workOrderData = (id) => {
  loading.value = true;
  excelWork.value.workOrderId = id;
  excelWorkOrder(excelWork.value).then((data) => {
    if (data.code === "200") {
      loading.value = false;
      ElMessage.success(data.msg);
      dataList();
    } else {
      loading.value = false;
      ElMessage.error(data.msg);
    }
  });
};
const revoke = (id) => {
  ElMessageBox.confirm("当前操作不可逆,确定撤销工单吗?")
    .then(() => {
      loading.value = true;
      revokeWorkOrder(id).then((data) => {
        if (data.code === "200") {
          loading.value = false;
          ElMessage.success(data.msg);
          dataList();
        } else {
          loading.value = false;
          ElMessage.error(data.msg);
        }
      });
    })
    .catch(() => {
      // catch error
    });
};
const allData = ref([]);
const getAllData = async () => {
  const { data, code } = await getWorkshopData({
    pageNo: 1,
    pageSize: 999999,
  });
  allData.value = data.records;
};
const setWorkShop = () => {
  allData.value.forEach((item) => {
    if (item.name == workshopName.value) {
      workShopInfo(item);
    }
  });
};
const handleEdit = (row, index) => {
  workshopName.value = row.workshopName;
  crudRef.value && crudRef.value.rowEdit(row, index);
  setWorkShop();
};
const aps1 = () => {
  apsType.value = 1;
  formData.workOrderIds = toDeleteIds;
  dialog5.visible = true;
};
const dataFormRef = ref(ElForm);
const schedulingTypes = ref([]);
const apsPriority = ref([]);
const formData = reactive({
  apsTime: null,
  priority: "1",
  apsModel: "0",
  workOrderId: 0,
});

const rules = reactive({
  priority: [{ required: true, message: "请选择优先级", trigger: "blur" }],
  apsTime: [{ required: true, message: "排程时间不能为空", trigger: "blur" }],
  apsModel: [{ required: true, message: "排程类型不能为空", trigger: "blur" }],
});
const handleSubmit = () => {
  dataFormRef.value.validate((isValid) => {
    if (isValid) {
      apsWorkOrder(formData).then((data) => {
        if (data.code === "200") {
          ElMessage.success(data.msg);
          dialog5.visible = false;
          dataList();
        } else {
          ElMessage.error(data.msg);
        }
      });
    }
  });
};
const workOrderInfoClick = (value) => {
  if (value) {
    form.value.frontWorkOrderCode = value.join(",");
  }
  dialog7.visible = false;
};
const orderInfo = (value) => {
  form.value.orderCode = value.orderCode;
  form.value.orderName = value.orderName;
  form.value.materialCode = value.materialCode;
  form.value.materialName = value.materialName;
  form.value.materialModel = value.materialModel;
  form.value.priority = value.priority;
  form.value.orderType = value.orderType;
  form.value.processRouteId = "";
  form.value.processRouteCode = "";
  form.value.processRouteName = "";
  form.value.processRouteVersion = "";
  form.value.productLineId = "";
  form.value.productLineName = "";
  form.value.workshopName = "";
  form.value.workshopCode = "";
  form.value.workshopName = "";
  dialog.visible = false;
};
const lineInfo = (value) => {
  form.value.productLineId = value.id;
  form.value.productLineName = value.name;
  dialog3.visible = false;
};
const workShopInfo = (value) => {
  if (
    form.value.workshopCode &&
    value.code &&
    form.value.workshopCode !== value.code
  ) {
    form.value.productLineId = "";
    form.value.productLineName = "";
  }
  form.value.workshopName = value.id;
  form.value.workshopCode = value.code;
  form.value.workshopName = value.name;
  dialog2.visible = false;
};
const routeInfo = (value) => {
  form.value.processRouteId = value.id;
  form.value.processRouteCode = value.processRouteCode;
  form.value.processRouteName = value.processRouteName;
  form.value.processRouteVersion = value.processRouteVersion;
  console.log("ddddd", value.opGroups);
  option.value.column.forEach((item) => {
    if (item.prop === "opGroup") {
      item.dicData = value.opGroups;
      item.disabled = false;
    }
    if (item.prop === "opType") {
      item.disabled = false;
    }
  });
  dialog1.visible = false;
};
const opGroupList = ref([]);
// 传入一个url，后面不带/
const { form, data, option, search, page, toDeleteIds, Methords, Utils } =
  useCrud({
    src: "/api/v1/plan/workOrder",
  });
const { dataList, createRow, updateRow, deleteRow, searchChange, resetChange } =
  Methords; //增删改查
const { selectionChange, multipleDelete } = Methords; //选中和批量删除事件
const { checkBtnPerm, downloadTemplate, exportData } = Utils; //按钮权限等工具
const opGroupShow = ref(true);
const crudRef = ref(null); //crudRef.value 获取avue-crud对象
const groupStri = ref({});
const switchOp = [
  {
    label: "否",
    value: 0,
  },
  {
    label: "是",
    value: 1,
  },
];
// 设置表格列或者其他自定义的option
option.value = Object.assign(option.value, {
  searchEnter: true,
  delBtn: false,
  selection: true,
  viewBtn: false,
  editBtn: false,
  labelWidth: 120,
  column: [
    {
      label: "生产批号",
      prop: "workOrderCode",
      search: true,
      display: false,
      width: 125,
      overHidden: true,
    },
    {
      label: "订单编号",
      prop: "orderCode",
      search: true,
      width: 125,
      overHidden: true,
      rules: [
        {
          required: true,
          message: "订单编号不能为空",
          trigger: "trigger",
        },
      ],
      click: ({ value, column }) => {
        if (column.boxType) {
          dialog.visible = true;
        }
      },
      change: ({ value, column }) => {
        if (column.boxType) {
          if (value != form.value.orderCode) {
            dialog.visible = true;
          }
        }
      },
    },
    {
      label: "订单名称",
      prop: "orderName",
      search: true,
      disabled: true,
      width: 125,
      overHidden: true,
    },
    {
      label: "订单类型",
      prop: "orderType",
      type: "select", //类型为下拉选择框
      width: 100,
      rules: [
        {
          required: true,
          message: "订单类型不能为空",
          trigger: "trigger",
        },
      ],
      overHidden: true,
      dicUrl: dictDataUtil.request_url + dictDataUtil.TYPE_CODE.plan_order_type,
      props: {
        label: "dictLabel",
        value: "dictValue",
      },
      change: ({ value, column }) => {
        if (
          form.value.opType &&
          form.value.workOrderCode &&
          form.value.orderCode
        ) {
          // 只有新增的时候需要调用，编辑的时候可能只限编辑先工序
          if (column.boxType && column.boxType === "add") {
            getOrderType(value);
          }
        }
      },
    },
    {
      label: "产品编号",
      width: 125,
      overHidden: true,
      search: true,
      disabled: true,
      prop: "materialCode",
    },
    {
      label: "产品名称",
      width: 125,
      overHidden: true,
      search: true,
      disabled: true,
      prop: "materialName",
    },
    {
      label: "产品规格",
      width: 125,
      search: true,
      overHidden: true,
      disabled: true,
      prop: "materialModel",
    },
    {
      label: "质量等级",
      prop: "hOrder",
      type: "select", //类型为下拉选择框
      width: 100,
      overHidden: true,
      dicUrl: dictDataUtil.request_url + dictDataUtil.TYPE_CODE.quality_grade,
      props: {
        label: "dictLabel",
        value: "dictValue",
      },
      rules: [
        {
          required: true,
          message: "质量等级不能为空",
          trigger: "trigger",
        },
      ],
    },
    {
      label: "优先级",
      prop: "priority",
      display: false,
      width: "80",
      type: "select", //类型为下拉选择框
      dicUrl:
        dictDataUtil.request_url + dictDataUtil.TYPE_CODE.plan_order_priority,
      props: {
        label: "dictLabel",
        value: "dictValue",
      },
    },
    {
      label: "状态",
      prop: "workOrderState",
      search: true,
      width: "80",
      display: false,
      type: "select", //类型为下拉选择框
      dicUrl:
        dictDataUtil.request_url + dictDataUtil.TYPE_CODE.plan_work_order_state,
      props: {
        label: "dictLabel",
        value: "dictValue",
      },
    },
    {
      label: "工艺路线",
      prop: "processRouteName",
      width: 125,
      overHidden: true,
      rules: [
        {
          required: true,
          message: "工艺路线不能为空",
          trigger: "trigger",
        },
      ],
      click: ({ value, column }) => {
        if (column.boxType) {
          if (!form.value.materialCode) {
            ElMessage({
              message: "请先选择订单",
              type: "warning",
            });
            return;
          }
          processRouteType.value = form.value.orderType === "2" ? "FG" : "ZC";
          dialog1.visible = true;
        }
      },
      change: ({ value, column }) => {
        //form.value.opType = ''
        if (column.boxType) {
          if (value != form.value.processRouteName) {
            dialog1.visible = true;
          }
        }
      },
    },
    {
      label: "工序分组",
      prop: "opType",
      width: "100",
      disabled: true,
      type: "select", //类型为下拉选择框
      dicUrl: dictDataUtil.request_url + dictDataUtil.TYPE_CODE.op_group,
      props: {
        label: "dictLabel",
        value: "dictValue",
      },
      click: ({ value, column }) => {
        if (column.boxType) {
          if (!form.value.orderType) {
            ElMessage({
              message: "请先选择订单类型",
              type: "warning",
            });
            return;
          }
        }
      },
      change: ({ value, column }) => {
        option.value.column.forEach((item) => {
          if (value) {
            if (column.boxType === "edit") {
              if (item.prop === "opType") {
                item.disabled = false;
              }
            }
            if (item.prop === "frontWorkOrderCode" || item.prop === "opGroup") {
              if (value === "2") {
                item.display = false;
              }
              if (item.prop === "opGroup") {
                if (value === "1") {
                  item.display = true;
                  item.disabled = false;
                  groupStri.value.workSection = "HGX";
                  groupStri.value.procecssRouteId = form.value.processRouteId;
                  workOrderGroupStr(groupStri.value).then((data) => {
                    opGroupList.value = data.data;

                    if (item.prop === "opGroup") {
                      item.dicData = data.data;
                    }
                  });
                }
                if (value === "0") {
                  item.display = true;
                  item.disabled = false;
                  groupStri.value.workSection = "QGX";
                  groupStri.value.procecssRouteId = form.value.processRouteId;
                  workOrderGroupStr(groupStri.value).then((data) => {
                    opGroupList.value = data.data;

                    if (item.prop === "opGroup") {
                      item.dicData = data.data;
                    }
                  });
                }
              }
              if (item.prop === "frontWorkOrderCode") {
                if (value === "1") {
                  item.display = true;
                  item.disabled = false;
                }
                if (value === "0") {
                  item.display = false;
                  item.disabled = false;
                }
              }
            }
          }
        });

        // 只有新增的时候需要调用，编辑的时候可能只限编辑先工序
        if (column.boxType && column.boxType === "add") {
          getOpGroup(value);
        }
      },
      rules: [
        {
          required: true,
          message: "工序分组不能为空",
          trigger: "trigger",
        },
      ],
    },
    {
      label: "是否重要订单",
      slot: true,
      headerAlign: "center",
      prop: "isImportant",
      width: 100,
      addDisplay: false,
      editDisplay: false,
    },
    {
      label: "工单编号",
      prop: "workOrderCode",
      rules: [
        {
          required: true,
          message: "工单编号不能为空",
          trigger: "trigger",
        },
      ],
    },
    {
      label: "分组标识",
      prop: "opGroup",
      width: "100",
      display: false,
      disabled: true,
      type: "select", //类型为下拉选择框
      dicData: opGroupList.value,
      props: {
        label: "name",
        value: "name",
      },
      rules: [
        {
          required: true,
          message: "分组标识不能为空",
          trigger: "trigger",
        },
      ],
    },
    {
      label: "前置工单",
      prop: "frontWorkOrderCode",
      width: "100",
      display: false,
      overHidden: true,
      rules: [
        {
          required: true,
          message: "前置工单不能为空",
          trigger: "trigger",
        },
      ],
      click: ({ value, column }) => {
        if (column.boxType) {
          dialog7.visible = true;
        }
      },
    },
    {
      label: "工艺版本",
      width: 100,
      overHidden: true,
      prop: "processRouteVersion",
      display: false,
      html: true,
      formatter: (val) => {
        return (
          '<b class="el-tag el-tag--success el-tag--light">' +
          val.processRouteVersion +
          "</b>"
        );
      },
    },
    {
      label: "生产车间",
      prop: "workshopName",
      width: 120,
      overHidden: true,
      rules: [
        {
          required: true,
          message: "生产车间不能为空",
          trigger: "trigger",
        },
      ],
      click: ({ value, column }) => {
        if (column.boxType) {
          dialog2.visible = true;
        }
        if (column.boxType == "edit") {
          form.value.productLineName = "";
        }
      },
      change: ({ value, column }) => {
        if (column.boxType) {
          if (value != form.value.workshopName) {
            dialog2.visible = true;
          }
        }
      },
    },
    {
      label: "产线名称",
      prop: "productLineName",
      width: 120,
      overHidden: true,
      rules: [
        {
          required: true,
          message: "产线名称不能为空",
          trigger: "trigger",
        },
      ],
      click: ({ value, column }) => {
        if (column.boxType) {
          if (!form.value.workshopName) {
            ElMessage({
              message: "请先选择生产车间",
              type: "warning",
            });
            return;
          }
          dialog3.visible = true;
        }
      },
      change: ({ value, column }) => {
        if (column.boxType) {
          if (value != form.value.productLineName) {
            dialog3.visible = true;
          }
        }
      },
    },
    /* {
      label: "检验批号",
      prop: "produceCode",
      width: "100",
    },*/
    {
      label: "开始时间",
      prop: "planStartWhen",
      width: 180,
      overHidden: true,
      display: false,
    },
    {
      label: "结束时间",
      prop: "planStartEnd",
      width: 180,
      display: false,
      overHidden: true,
    },
    {
      label: "管号最小值",
      prop: "seqMin",
      type: "number",
      min: 1,
      max: 99999,
      blur: () => {
        countPlanNum();
      },
      rules: [
        {
          required: true,
          message: "管号最小值不能为空",
          trigger: "trigger",
        },
      ],
    },
    {
      label: "管号最大值",
      prop: "seqMax",
      type: "number",
      min: 1,
      max: 99999,
      blur: () => {
        countPlanNum();
      },
      rules: [
        {
          required: true,
          message: "管号最大值不能为空",
          trigger: "trigger",
        },
      ],
    },
    {
      label: "工单数量",
      prop: "planNum",
      width: 85,
      disabled: true,
    },
    {
      label: "检验批号",
      width: 85,
      display: false,
      prop: "checkCode",
    },
    {
      label: "完成数量",
      width: 85,
      display: false,
      prop: "completeNum",
    },
    {
      label: "下线数量",
      width: 85,
      display: false,
      prop: "beforeNum",
    },
    {
      label: "报废数量",
      width: 85,
      display: false,
      prop: "scrapNum",
    },
    // {
    //   label: "首检数量",
    //   width: 85,
    //   prop: "firstCheckNum",
    //   value: 0,
    // },
    {
      label: "已检数量",
      width: 85,
      display: false,
      prop: "firstCheckAlreadyNum",
    },

    {
      label: "创建时间",
      width: 180,
      display: false,
      prop: "created",
    },
    {
      label: "创建人",
      width: 90,
      display: false,
      prop: "creator",
    },
    {
      label: "数据包地址",
      width: 90,
      display: false,
      prop: "packageUrl",
      hide: true,
    },
    {
      label: "水汽",
      prop: "waterVapor",
      span: 12,
      type: "switch",
      dicData: switchOp,
      value: 0,
    },
    {
      label: "DPA",
      prop: "dpa",
      span: 12,
      type: "switch",
      dicData: switchOp,
      value: 0,
    },
    {
      label: "备注",
      prop: "remark",
      width: 100,
      overHidden: true,
      minRows: 2, //最小行/最小值
      type: "textarea", //类型为多行文本域框
      maxlength: 20, //最大输入长度
    },
  ],
});

onMounted(() => {
  getAllData();
  dataList();
  queryDictDataByType("order_scheduling_type").then((data) => {
    schedulingTypes.value = data.data;
  });
  queryDictDataByType("aps_priority").then((data) => {
    apsPriority.value = data.data;
  });

  permission.value = {
    delBtn: checkPerm(ButtonPermKeys.PLAN.BTNS.work_order_del),
    addBtn: checkPerm(ButtonPermKeys.PLAN.BTNS.work_order_add),
    editBtn: checkPerm(buttonPermission.PLAN.BTNS.work_order_edit),
  };
});

// 选择完前工序或者后工序后获取这个
const getOpGroup = (value) => {
  getJobInfo(form.value.orderCode, value + "", form.value.orderType).then(
    (res) => {
      form.value.workOrderCode = res.data;
    }
  );
};

const getOrderType = (value) => {
  getJobInfo(form.value.orderCode, form.value.opType, value + "").then(
    (res) => {
      form.value.workOrderCode = res.data;
    }
  );
};

// 输入完最大值和最小值计算工单数量
const countPlanNum = () => {
  if (form.value.seqMax && form.value.seqMin) {
    form.value.planNum = form.value.seqMax - form.value.seqMin + 1;
  }
};

const changeItem = (row) => {
  updateWorkOrderInfo(row).then(() => {
    ElMessage.success("操作成功");
    dataList();
  });
};
</script>
