<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-style="tableRowClassName"
      @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
          :disabled="toDeleteIds.length < 1"
          type="danger"
          icon="el-icon-delete"
          :size="size"
          @click="multipleDelete"
          >删除</el-button
        >
        <el-button
          :disabled="toDeleteIds.length < 1"
          type="primary"
          :size="size"
          @click="aps1"
          >批量排程
          <template #icon>
            <svg-icon icon-class="paicheng" />
          </template>
        </el-button>
        <el-button
            :disabled="toDeleteIds.length < 1"
            type="refresh"
            icon="el-icon-refresh"
            :size="size"
            @click="apsSync"
        >APS同步</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,row.workOrderState)"
          text
          v-hasPerm="[buttonPermission.PLAN.BTNS.work_order_aps]"
          v-if="
            row.workOrderState !== '6'
          "
          type="primary"
          :size="size"
          >排程
          <template #icon>
            <svg-icon icon-class="paicheng" />
          </template>
        </el-button>

        <el-button
          text
          v-hasPerm="[buttonPermission.PLAN.BTNS.work_order_lock]"
          v-if="row.workOrderState === '4'"
          @click="lockOrUnLockWorkOrder(row.id, 5)"
          type="primary"
          :size="size"
          >冻结
          <template #icon>
            <svg-icon icon-class="dongjie" />
          </template>
        </el-button>
        <el-button
          text
          v-if="row.workOrderState === '5'"
          v-hasPerm="[buttonPermission.PLAN.BTNS.work_order_lock]"
          @click="lockOrUnLockWorkOrder(row.id, 4)"
          type="primary"
          :size="size"
          >解冻
          <template #icon>
            <svg-icon icon-class="jiedong" />
          </template>
        </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 text @click="showSeqPage(row)" type="primary" :size="size"
          >流转卡号
          <template #icon>
            <svg-icon icon-class="luozhuankahao" />
          </template>
        </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
          text
          @click="jumpPage(row.workOrderCode, 1)"
          type="primary"
          :size="size"
          >领用申请
          <template #icon>
            <svg-icon icon-class="lingyongshenqing" />
          </template>
        </el-button>
        <el-button
          text
          @click="jumpPage(row.workOrderCode, 2)"
          type="primary"
          :size="size"
          >生产准备
          <template #icon>
            <svg-icon icon-class="shengchanzhunbei" />
          </template>
        </el-button>
        <el-button
          icon="el-icon-notebook"
          text
          v-if="row.workOrderState === '6' && row.packageUrl === '0'"
          @click="zipData(row.workOrderCode)"
          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="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"
              :disabled="apsDisabled.includes(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>
  </div>
</template>
<script setup>
import { ref, getCurrentInstance } from "vue";
import { useCrud } from "@/hooks/userCrud";
import buttonPermission from "@/common/configs/buttonPermission";
import {
  apsWorkOrder,
  distributeWorkOrder,
  revokeWorkOrder,
  lockWorkOrder,
  zipWorkOrder,
} from "@/api/order";
import {syncAps} from "@/api/aps";
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 { checkPerm } from "@/directive/permission";
import { queryDictDataByType } from "@/api/system/dict";
import {ElMessage, ElMessageBox} from "element-plus";
const { isShowTable, tableType } = toRefs(useCommonStoreHook());

const tableRowClassName = ({ row, rowIndex }) => {
  if(row.planStartEnd){
    const currentDate = new Date(); // 获取当前日期
    const compareDate = new Date(row.planStartEnd); // 设置要比较的日期
    if (currentDate > compareDate && row.workOrderState !== '6') {
      return { backgroundColor: '#F1BFBFFF'};
    }
  }
  return '';
};
const router = useRouter();
const test = () => {
  isShowTable.value = true;
  tableType.value = tableType.value == 1 ? 2 : 1;
};
const processRouteType = ref("");
const permission = reactive({
  delBtn: checkPerm(buttonPermission.PLAN.BTNS.work_order_del),
  addBtn: checkPerm(buttonPermission.PLAN.BTNS.work_order_add),
  editBtn: checkPerm(buttonPermission.PLAN.BTNS.work_order_edit),
  menu: true,
});
const disabledDate = (time) => {
  return time.getTime() < Date.now(); // 8.64e7 毫秒数代表一天
};
const apsSync = () =>{
  ElMessageBox.confirm("是否同步所选中数据？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    let param = {type: 3,codes: toDeleteIds.value}
    syncAps(param).then((data)=>{
      if (data.code === "200") {
        ElMessage.success(data.msg);
      } else {
        ElMessage.error(data.msg);
      }
    })
  });
}
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 apsType = ref(0);
const aps = (id,state) => {
  apsType.value = 0;
  formData.workOrderIds = [id];
  dialog5.visible = true;
  formData.apsModel = null
  apsDisabled.value = []
  if(state === '0' || state === '1' || state === '2' || state === '3'){
    apsDisabled.value = ['2']
  }
  if(state === '4' || state === '5'){
    apsDisabled.value = ['0','1']
  }
};
const apsDisabled = ref([])
const showSeqPage = (workOrderCode) => {
  form.value = workOrderCode;
  dialog4.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 zipWork = ref({});
const zipData = (workOrderCode) => {
  loading.value = true;
  zipWork.value.workOrderCode = workOrderCode;
  zipWorkOrder(zipWork.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 handleEdit = (row, index) => {
  crudRef.value && crudRef.value.rowEdit(row, index);
};
const aps1 = () => {
  apsType.value = 1;
  apsDisabled.value = []
  formData.workOrderIds = toDeleteIds;
  dialog5.visible = true;
};
const dataFormRef = ref(ElForm);
const schedulingTypes = ref([]);
const apsPriority = ref([]);
const formData = reactive({
  apsTime: null,
  priority: "1",
  apsModel: null,
  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 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;
  dialog1.visible = false;
};
// 传入一个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 crudRef = ref(null); //crudRef.value 获取avue-crud对象

// 设置表格列或者其他自定义的option
option.value = Object.assign(option.value, {
  delBtn: false,
  selection: true,
  viewBtn: false,
  editBtn: false,
  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;
        }
      },
    },
    {
      label: "订单名称",
      prop: "orderName",
      search: true,
      disabled: true,
      width: 125,
      overHidden: true,
    },
    {
      label: "订单类型",
      prop: "orderType",
      type: "select", //类型为下拉选择框
      width: 100,
      disabled: true,
      overHidden: true,
      dicUrl: dictDataUtil.request_url + dictDataUtil.TYPE_CODE.plan_order_type,
      props: {
        label: "dictLabel",
        value: "dictValue",
      },
    },
    {
      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: "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",
      width: "80",
      display: false,
      search: true,
      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 === "1" ? "ZC" : "FG";
          dialog1.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 = "";
        }
      },
    },
    {
      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;
        }
      },
    },
    {
      label: "开始时间",
      prop: "planStartWhen",
      width: 180,
      overHidden: true,
      display: false,
    },
    {
      label: "结束时间",
      prop: "planStartEnd",
      width: 180,
      display: false,
      overHidden: true,
    },
    {
      label: "工单数量",
      prop: "planNum",
      width: 85,
      type: "number",
      min: 1,
      max: 99999,
      rules: [
        {
          required: true,
          message: "工单数量不能为空",
          trigger: "trigger",
        },
      ],
    },
    {
      label: "自动拆单",
      hide: true,
      type: "switch",
      dicData: [
        {
          label: "否",
          value: 0,
        },
        {
          label: "是",
          value: 1,
        },
      ],
      value: 0,
      editDisplay: false,
      prop: "autoGenerate",
    },
    {
      label: "完成数量",
      width: 85,
      display: false,
      prop: "completeNum",
    },
    {
      label: "下线数量",
      width: 85,
      display: false,
      prop: "beforeNum",
    },
    {
      label: "报废数量",
      width: 85,
      display: false,
      prop: "scrapNum",
    },
    {
      label: "创建时间",
      width: 180,
      display: false,
      prop: "created",
    },
    {
      label: "创建人",
      width: 90,
      display: false,
      prop: "creator",
    },
    {
      label: "数据包地址",
      width: 90,
      display: false,
      prop: "packageUrl",
      hide: true,
    },
  ],
});

onMounted(() => {
  // console.log("crudRef", crudRef)
  dataList();
  queryDictDataByType("order_scheduling_type").then((data) => {
    schedulingTypes.value = data.data;
  });
  queryDictDataByType("aps_priority").then((data) => {
    apsPriority.value = data.data;
  });
});
</script>
