<template>
  <div>
    <el-card>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-divider content-position="left"><span style="font-weight: bold; font-size: larger;">工单信息</span>
        </el-divider>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="任务编号：">{{ form.orderCode }}</el-form-item>
            <el-form-item label="成品编码：">{{ form.materialCode }}</el-form-item>
            <el-form-item label="计划开始时间：">{{ form.planBeginTime }}</el-form-item>
            <el-form-item label="计划数量/已派工数量/完成数量：" label-width="220px">
              {{
                form.planAmount
              }}/{{
                form.dispatchAmount == null || form.dispatchAmount === undefined ? 0 : form.dispatchAmount
              }}/{{ form.completeAmount }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工艺路线：">{{ form.dispatchName }}</el-form-item>
            <el-form-item label="成品名称：">{{ form.materialName }}</el-form-item>
            <el-form-item label="计划结束时间：">{{ form.planEndTime }}</el-form-item>
            <el-form-item label="任务状态：">
              <template #default="scope">
              </template>
            </el-form-item>


          </el-col>
        </el-row>

        <el-divider content-position="left"><span style="font-weight: bold; font-size: larger;">派工信息</span>
        </el-divider>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button icon="el-icon-plus" size="small" type="primary" @click="handleAddMesProductPlan"
                       v-if="form.orderStatus!==ORDER_STATUS.FINISHED && form.orderStatus!=ORDER_STATUS.RECALLED && form.orderStatus!=ORDER_STATUS.DELETED">
              新增
            </el-button>
          </el-col>
        </el-row>
        <el-table ref="mesProductPlan" :data="mesProductPlanList"
                  :row-class-name="rowMesProductPlanIndex" @selection-change="handleMesProductPlanSelectionChange"
                  :tree-props="{children: 'children'}"
                  style="width: 100%;margin-bottom: 20px;"
                  row-key="id"
                  border
                  default-expand-all
        >
          <el-table-column label="序号" type="index" align="center">

          </el-table-column>

          <el-table-column
            width="80"
            label="删除"
            type=""
          >
            <template #default="scope">
              <el-button type="danger" icon="el-icon-delete" @click="handleDeleteMesProductPlan(scope)"
                         v-if="scope.row.firstFlag != null && scope.row.firstFlag === '1'
                         && form.orderStatus!==ORDER_STATUS.FINISHED && form.orderStatus!==ORDER_STATUS.RECALLED && form.orderStatus!==ORDER_STATUS.DELETED"></el-button>
            </template>
          </el-table-column>

<!--          <el-table-column-->
<!--            width="80"-->
<!--            type=""-->
<!--            label="添加"-->
<!--          >-->
<!--            <template #default="scope" v-if="">-->
<!--              <el-button type="primary" icon="el-icon-plus" @click="addProcessUser(scope)"-->
<!--                         v-if="(scope.row.children != null && scope.row.children !== undefined)-->
<!--                          && scope.row.processType!== PROCESS_TYPE.AUTO && scope.row.displayFlag !== DISPLAY_FLAG.NO"-->
<!--                         :disabled="scope.row.addFlag !=='1'-->
<!--                           || form.orderStatus===ORDER_STATUS.FINISHED || form.orderStatus===ORDER_STATUS.RECALLED || form.orderStatus===ORDER_STATUS.DELETED">-->

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

          <el-table-column
            width="50"
          >
            <!--        <template #default="scope">-->
            <!--          <el-button type="primary" icon="el-icon-plus" @click="add(scope)"></el-button>-->
            <!--        </template>-->
          </el-table-column>


          <el-table-column align="center" label="派工单号" prop="dispatchCode" width="230">
            <template #default="scope">
              <el-input v-model="scope.row.dispatchCode" :disabled="true"
                        v-if="scope.row.children != null && scope.row.children !== undefined"/>
            </template>
          </el-table-column>
          <el-table-column align="center" label="工序" prop="processName" width="140">
            <template #default="scope">
              <el-input v-model="scope.row.processName" :disabled="true"
                        v-if="scope.row.children != null && scope.row.children !== undefined"/>
            </template>
          </el-table-column>
          <el-table-column align="center" label="步骤" prop="processOrder">
            <template #default="scope">
              <el-input v-model="scope.row.processOrder" :disabled="true"
                        v-if="scope.row.children != null && scope.row.children !== undefined"/>
            </template>
          </el-table-column>
          <el-table-column align="center" label="派工数量" prop="dispatchAmount" width="100">
            <template #default="scope">
              <el-input v-model="scope.row.dispatchAmount" :disabled="scope.row.oldRowFlag"
                        v-if="scope.row.children != null && scope.row.children !== undefined
                        && scope.row.firstFlag != null && scope.row.firstFlag === '1'"
              />
            </template>
          </el-table-column>

<!--          <el-table-column align="center" label="用户" prop="userId" width="140">
            <template #default="scope">
              <el-select v-model="scope.row.userId" placeholder="请选择用户"
                         v-if="scope.row.children == null || scope.row.children === undefined"
                         :disabled="scope.row.planId != null && scope.row.planId !== undefined && scope.row.planId !== ''"
              >
                <el-option
                  v-for="item in processUsers[scope.row.processId]"
                  :key="item.userId"
                  :label="item.userName"
                  :value="item.userId"
                ></el-option>
              </el-select>

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

          <el-table-column align="center" label="工位" prop="releaseId" width="140">
            <template #default="scope">
              <el-select v-model="scope.row.releaseId" placeholder="请选择"
                         v-if="scope.row.children == null || scope.row.children === undefined"
                         :disabled="scope.row.planId != null && scope.row.planId !== undefined && scope.row.planId !== ''"
              >
                <el-option
                  v-for="item in processStations[scope.row.processId]"
                  :key="item.stationId"
                  :label="item.stationName"
                  :value="item.stationId"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>



          <el-table-column align="center" label="派工标准工时(小时)" prop="productionTime" width="180">
            <template #default="scope">
              <el-input-number style="width:150px;" :min="0" v-model="scope.row.productionTime"
                               :disabled="(scope.row.processType === PROCESS_TYPE.MANUAL && scope.row.children != null && scope.row.children !== undefined)
                                || scope.row.planStatus=== PLAN_STATUS.FINISHED || form.orderStatus===ORDER_STATUS.FINISHED || form.orderStatus===ORDER_STATUS.RECALLED || form.orderStatus===ORDER_STATUS.DELETED"/>
            </template>
          </el-table-column>
          <el-table-column align="center" label="计划开始时间" prop="planBeginTime" width="230">
            <template #default="scope">
              <el-date-picker v-model="scope.row.planBeginTime" style="width:200px;"
                              :disabled="(scope.row.processType === PROCESS_TYPE.MANUAL && scope.row.children != null && scope.row.children !== undefined)
                              || scope.row.planStatus=== PLAN_STATUS.FINISHED || form.orderStatus===ORDER_STATUS.FINISHED || form.orderStatus===ORDER_STATUS.RECALLED || form.orderStatus===ORDER_STATUS.DELETED"
                              clearable
                              placeholder="请选择计划开始时间"
                              type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
              />
            </template>
          </el-table-column>
          <el-table-column align="center" label="计划完成时间" prop="planEndTime" width="230">
            <template #default="scope">
              <el-date-picker v-model="scope.row.planEndTime" style="width:200px;"
                              :disabled="(scope.row.processType === PROCESS_TYPE.MANUAL && scope.row.children != null && scope.row.children !== undefined)
                              || scope.row.planStatus=== PLAN_STATUS.FINISHED || form.orderStatus===ORDER_STATUS.FINISHED || form.orderStatus===ORDER_STATUS.RECALLED || form.orderStatus===ORDER_STATUS.DELETED"
                              clearable
                              placeholder="请选择计划完成时间"
                              type="datetime" value-format="yyyy-MM-dd HH:mm:ss"/>
            </template>
          </el-table-column>

          <el-table-column align="center" label="状态" prop="planStatus" width="150">
            <template #default="scope">
              {{scope.row.planStatus}}

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


          <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="100">
            <template #default="scope">
              <el-button
                icon="el-icon-delete"
                size="small"
                type="danger"
                @click="handleDeleteDispatchUser(scope.row)"
                v-if="(scope.row.children == null || false)  "
                :disabled="(scope.row.planStatus !== PLAN_STATUS.TO_DISPATCH && scope.row.planStatus !== PLAN_STATUS.DISPATCHED) || form.orderStatus===ORDER_STATUS.FINISHED || form.orderStatus===ORDER_STATUS.RECALLED || form.orderStatus===ORDER_STATUS.DELETED"
              >删除
              </el-button>
            </template>
          </el-table-column>


        </el-table>
      </el-form>
      <el-form label-width="100px">
        <el-form-item style="text-align: center;margin-left:-100px;margin-top:10px;">
          <el-button type="primary" @click="submitForm()"
                     v-if="form.orderStatus!==ORDER_STATUS.FINISHED && form.orderStatus!==ORDER_STATUS.RECALLED && form.orderStatus!==ORDER_STATUS.DELETED">
            提交
          </el-button>
          <el-button @click="close()">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>

  </div>
</template>

<script>

import { getOrderInfo } from "@/api/mes/orderInfo";
import { getBaseRouteProcesses, getDispatchCode, selectProductPlans } from '@/api/mes/planInfo';
import { getProdBaseProcessUserList } from '@/api/mes/prodBaseProcessUser';
import { getStationInfoList } from '@/api/mes/baseStationInfo';
import { getProdLineList } from '@/api/mes/baseProdLineInfo';
import { getBaseRouteList } from '@/api/mes/baseRoute';
import { getProcessInfoList } from '@/api/mes/baseProcessInfo';

let id = 0


export default {
  name: "productPlanEdit",
  dicts: ['plan_status', 'product_status', 'mes_dispatch_flag'],
  props: {
    value: [String, Object, Array, Number],
    // sop文件数量限制
    sopLimit: {
      type: Number,
      default: 20,
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      blueprintModel: false,
      sopViewModel: false,
      pictureDetailModel: false,
      // 图片预览地址
      dialogImageUrl: '',
      // 非单个禁用
      single: true,
      checkedMesProductPlanList: [],
      // 选中选项卡的 name
      activeName: "columnInfo",
      // 表格的高度
      tableHeight: document.documentElement.scrollHeight - 245 + "px",
      // 表信息
      tables: [],
      // 表列信息
      columns: [],
      // 生产计划表格数据
      mesProductPlanList: [],
      //待删除的生产计划ID
      toDeletedPlanIds: [],
      productPlanData: {},
      // 表详细信息
      info: {},
      // 表单参数
      form: {},
      //自动化工序标识（2楼和3楼）
      autoProcessFlag: false,
      // 表单校验
      rules: {
        productOrderId: [
          {required: true, message: "生产工单ID不能为空", trigger: "blur"}
        ],
        planCode: [
          {required: true, message: "计划编号不能为空", trigger: "blur"}
        ],
        dispatchCode: [
          {required: true, message: "派工单号不能为空", trigger: "blur"}
        ],
        materialId: [
          {required: true, message: "物料ID不能为空", trigger: "blur"}
        ],
        materialBomId: [
          {required: true, message: "物料bomID不能为空", trigger: "blur"}
        ],
        stationId: [
          {required: true, message: "工位ID不能为空", trigger: "blur"}
        ],
        planStatus: [
          {required: true, message: "计划状态不能为空", trigger: "change"}
        ],
        isFlag: [
          {required: true, message: "是否标识不能为空", trigger: "change"}
        ],
      },
      // 文件列表
      fileList: [],
      // 根据工序和派工单号分组Sop文件
      groupSopFile: {},
      // 根据工序和派工单号分组Sop文件列表
      groupSopFileList: {},
      // 上传SOP文件回调列表
      uploadSopList: [],

      // 根据工序和派工单号分组图纸文件
      groupAttachFile: {},
      // 根据工序和派工单号分组图纸文件列表
      groupAttachFileList: {},
      // 上传图纸文件回调列表
      uploadAttachList: {},

      previewSopFlag: {},//是否预览过SOP
      previewDrawingFlag: {},//是否预览过图纸

      // SOP文件大小限制(MB)
      sopFileSize: 50,
      // SOP文件类型,
      sopFileType: ["png", "jpg", "jpeg"],

      // 图纸文件大小限制(MB)
      drawingFileSize: 50,
      // 图纸文件类型, 例如['png', 'jpg', 'jpeg']
      drawingFileType: ["dxf", "dwg"],

      //文件上传-生产派工对象
      addProductPlanObject: {},
      headers: {
        Authorization: "Bearer "  ,
      },
      PROCESS_ID: {
        BENDING_PROCESS_ID: 42
      },
      PROCESS_TYPE: {
        MANUAL: '1',
        AUTO: '3',
      },
      DISPLAY_FLAG: {
        YES: '1',
        NO: '0',
      },
      PLAN_STATUS: {
        TO_DISPATCH: '0',//待派工
        DISPATCHED: '1',//已派工
        STARTED: '2',//已开始
        FINISHED: '3' //已完成

      },
      ORDER_STATUS: {
        TO_PUBLISHED: '0',//待发布
        PUBLISHED: '1',//已发布
        FINISHED: '2',//已完成
        STARTED: '3',//已开始
        PAUSE: '4',//已暂停
        RECALLED: '8',//已撤回
        DELETED: '9',//已删除
      },
      SALE_TYPE: {
        INTERNAL: '2',//对内生产
      },
      id: 1,
      ATTACH_TYPE: {
        DRAWING: "1",//附件类别:加工图纸
        SOP: "2",//附件类别:SOP
      },
      processUsers: [],
      processStations:[],

      //物料BOMList
      attachInfoList: [],
      //选中的BOMList
      materialBomAttachIdList: [],
    };
  },
  created() {
    this.fetchOrderInfo();
  },
  methods: {
    async fetchOrderInfo() {
      const productOrderId = this.$route.params.productOrderId;
      console.log("productOrderId", productOrderId);
      if (productOrderId) {
        try {
          const response = await getOrderInfo(productOrderId);
          this.form = response.data;
          this.getProcessJoin(productOrderId);
        } catch (error) {
          console.error("Failed to fetch order info:", error);
        }
      }
    },

    async getProcessJoin(productOrderId) {
      const routeId = this.form.dispatchId;
      const processId = this.form.processId;
      try {
        const res = await getProdBaseProcessUserList({ routeId });
        res.data.forEach(processUser => {
          if (!this.processUsers[processUser.processId]) {
            this.processUsers[processUser.processId] = [];
          }
          this.processUsers[processUser.processId].push(processUser);
        });
        console.log("this.processUsers", this.processUsers);


        const station = await getStationInfoList({ processId });
        console.log("getStationInfoList", station);
        station.data.forEach(processStation => {
          if (!this.processStations[processStation.processId]){
            this.processStations[processStation.processId] = [];
          }
          this.processStations[processStation.processId].push(processStation);
        });

        const productPlansResponse = await selectProductPlans({ productOrderId: productOrderId });
        this.groupProductPlans(productPlansResponse.data);

      } catch (error) {
        console.error("Failed to fetch process users or product plans:", error);
      }
    },

    groupProductPlans(productPlans) {
      const groupedProductPlans = {};
      productPlans.forEach(productPlan => {
        const key = `${productPlan.dispatchCode}-${productPlan.processId}`;
        if (!groupedProductPlans[key]) {
          groupedProductPlans[key] = [];
        }
        groupedProductPlans[key].push(productPlan);
      });

      let firstDispatch = {};

      for (let dispatchCodeProcessId in groupedProductPlans) {
        let productPlansByDispatch = groupedProductPlans[dispatchCodeProcessId];

        // console.log(processId + ": " + JSON.stringify(groupedProductPlans[processId]));
        let obj = {};

        //每个派工单第一个工序才显示删除按钮
        let dispatchCode = dispatchCodeProcessId.split("-")[0];
        if (!firstDispatch[dispatchCode]) {
          firstDispatch[dispatchCode] = "1";
          obj.firstFlag = "1";
        }

        obj.id = this.id
        this.id = this.id + 1;
        obj.addFlag = "0";
        let i = 0;
        let processType;
        productPlansByDispatch.forEach(groupedProductPlan => {
          if (groupedProductPlan.planStatus !== this.PLAN_STATUS.FINISHED) {
            obj.addFlag = "1";
          }

          processType = groupedProductPlan.processType;
          groupedProductPlan.id = this.id;
          this.id = this.id + 1;
          groupedProductPlan.productionTime = parseFloat((groupedProductPlan.productionTime / 60 / 60).toFixed(1));
/*          obj.sopId = groupedProductPlan.sopId;*/
          obj.attachId = groupedProductPlan.attachId;
          obj.productionTime = parseFloat((groupedProductPlan.processProductionTime / 60 / 60).toFixed(1));

          if (i === 0 || groupedProductPlan.processType !== this.PROCESS_TYPE.MANUAL) {
            obj.dispatchCode = groupedProductPlan.dispatchCode;
            obj.planCode = groupedProductPlan.planCode;
            obj.dispatchAmount = groupedProductPlan.dispatchAmount;
            obj.processId = groupedProductPlan.processId;
            obj.processName = groupedProductPlan.processName;
            obj.lastProcessId = groupedProductPlan.lastProcessId;
            obj.processType = groupedProductPlan.processType;
            obj.processOrder = groupedProductPlan.processOrder;
/*            obj.displayFlag = groupedProductPlan.displayFlag;*/
            obj.finalProcessFlag = groupedProductPlan.finalProcessFlag;
            obj.attachId = groupedProductPlan.attachId;
/*            obj.sopId = groupedProductPlan.sopId;*/

            obj.planBeginTime = this.form.planBeginTime;
            obj.planEndTime = this.form.planEndTime;
            obj.planStatus = groupedProductPlan.planStatus;
            // obj.dispatchAmount = this.form.planAmount - this.form.dispatchAmount;

            obj.materialId = this.form.materialId;
            obj.materialBomId = this.form.materialBomId;
            obj.productOrderId = this.form.productOrderId;
            obj.saleOrderId = this.form.saleOrderId;
            obj.saleorderCode = this.form.saleorderCode;
            // 新添加列标识 false=新添加，true=历史行
            obj.oldRowFlag = true;

            if (groupedProductPlan.processType !== this.PROCESS_TYPE.MANUAL) {
              let cloneObj = deepClone(obj);
              cloneObj.id = this.id
              cloneObj.planId = groupedProductPlan.planId;
              cloneObj.productionTime = parseFloat((groupedProductPlan.productionTime / 60 / 60).toFixed(1));
              this.id = this.id + 1;
              cloneObj.children = [];
              this.mesProductPlanList.push(cloneObj);
            }
            i++;
          }
        });

        if (processType === this.PROCESS_TYPE.MANUAL) {
          obj.children = productPlansByDispatch;
          this.mesProductPlanList.push(obj);
        }
      }

      this.getId(this.mesProductPlanList);
      console.log(this.mesProductPlanList)

    },

    async getId(arr) {
      arr.forEach(element => {
        this.id = this.id + 1;
        if (Array.isArray(element.children)) {
          this.getId(element.children)
        }
      })
    },

    /** 提交按钮 */
    submitForm() {
      // let dataList = this.mesProductPlanList.filter(plan => !plan.oldRowFlag);
      if (this.mesProductPlanList.length === 0) {
        this.$modal.msgError("无派工信息提交");
        return;
      }

      let dataList = this.mesProductPlanList;
      let toUpdatedProductPlans = [];
      let undispathDesc;
      let currentDispatchAmount = 0;
      let planDispatchAmount = 0;
      for (let i = 0; i < dataList.length; i++) {
        let e = dataList[i];

        if (e.firstFlag && e.firstFlag === "1") {//第一个标识，校验派工数量
          let dispatchAmount = e.dispatchAmount;
          const numericAmount = parseInt(dispatchAmount, 10);
          if (!this.isPositiveInteger(numericAmount) || numericAmount <= 0) {
            this.$modal.msgError("派工数量须为大于等于0的正整数！");
            return;
          }

          planDispatchAmount = numericAmount;
          if (e.newFlag && e.newFlag === "1") {
            currentDispatchAmount += numericAmount;
          }
        }


        let dispatchFlag = false;
        undispathDesc = "派工单号为[" + e.dispatchCode + "]，工序为[" + e.processName + "],请选择用户派工";
        if (e.processType !== this.PROCESS_TYPE.AUTO) {
          if (!e.children || e.children.length <= 0) {//不是自动话产线需要派工到人
            this.$modal.msgError(undispathDesc);
            return;
          }

          for (let j = 0; j < e.children.length; j++) {
            let processUser = e.children[j];
            let toUpdatedProductPlan = deepClone(e);

            if (processUser.userId && processUser.userId !== '') {
              toUpdatedProductPlan.userId = processUser.userId;
              if (processUser.planBeginTime && processUser.planBeginTime !== '' &&
                (processUser.planBeginTime < this.form.planBeginTime || processUser.planBeginTime > this.form.planEndTime)){
                this.$modal.msgError("序号" + (parseInt(e.index) + 1) + "：计划开始时间不在生产工单时间范围内");
                return;
              }
              if (processUser.planEndTime && processUser.planEndTime !== '' &&
                (processUser.planEndTime < this.form.planBeginTime || processUser.planEndTime > this.form.planEndTime)) {
                this.$modal.msgError("序号" + (parseInt(e.index) + 1) + "：计划结束时间不在生产工单时间范围内");
                return;
              }

              if (processUser.planBeginTime && processUser.planBeginTime !== '' &&
                processUser.planEndTime && processUser.planEndTime !== '' &&
                processUser.planBeginTime >= processUser.planEndTime) {
                this.$modal.msgError("序号" + (parseInt(e.index) + 1) + "：计划开始时间须小于计划结束时间");
                return;
              }
              toUpdatedProductPlan.planBeginTime = processUser.planBeginTime;
              toUpdatedProductPlan.planEndTime = processUser.planEndTime;
              toUpdatedProductPlan.planId = processUser.planId;
              toUpdatedProductPlan.planStatus = processUser.planStatus;
              toUpdatedProductPlan.attachId = processUser.attachId;
              toUpdatedProductPlan.sopId = processUser.sopId;
              toUpdatedProductPlan.planAmount = planDispatchAmount;
              toUpdatedProductPlan.dispatchAmount = planDispatchAmount;
              toUpdatedProductPlan.children = null;
              let productionTimeHour = processUser.productionTime;

              let productionTimeSecond = productionTimeHour * 60 * 60;
              toUpdatedProductPlan.productionTime = productionTimeSecond;

              toUpdatedProductPlans.push(toUpdatedProductPlan);
              dispatchFlag = true;
            } else {
              this.$modal.msgError(undispathDesc);
              return;
            }
          }
        } else {
          toUpdatedProductPlans.push(e);
        }

        if (toUpdatedProductPlans.length <= 0) {
          this.$modal.msgError("无派工信息提交");
          return;
        }


      }

      //校验派工数量是否大于生产任务计划数量
      let dispatchedAmount = this.form.dispatchAmount + currentDispatchAmount;//加上此次派工的数量，总共的派工数量
      if (dispatchedAmount > this.form.planAmount) {
        this.$modal.msgError("派工数量之和需小于等于该生产任务计划数量！");
        return;
      }


      checkAddMesProductPlanList(
        {
          productOrderId: this.form.productOrderId,
          dispatchAmount: currentDispatchAmount,
          saleOrderId: this.form.saleOrderId,
          mesProductPlanList: toUpdatedProductPlans,
        })
        .then(res => {
          if (res?.msg && res.msg !== '') {
            this.$modal.confirm('有以下用户派工冲突，请确认是否继续派工?' + res.msg).then(function () {
              orderAddMesProductPlanList(currentDispatchAmount, toUpdatedProductPlans);
              return true;
            }).then(() => {
            }).catch(() => {
            });

          } else {
            this.orderAddMesProductPlanList(currentDispatchAmount, toUpdatedProductPlans);
          }

        });


    },

    orderAddMesProductPlanList(currentDispatchAmount, toUpdatedProductPlans) {
      orderAddMesProductPlanList(
        {
          productOrderId: this.form.productOrderId,
          dispatchAmount: currentDispatchAmount,
          mesProductPlanList: toUpdatedProductPlans,
          toDeletedPlanIds: this.toDeletedPlanIds
        })
        .then(res => {
          this.$modal.msgSuccess(res.msg);
          this.close();
        });
    },


    /** 删除按钮操作 */
    handleDeleteMesProductPlan(scope) {
      let dispatchCode = scope.row.dispatchCode;
      this.$modal.confirm('是否确认删除生产派工单号为"' + dispatchCode + '"的数据项？').then(function () {
        return true;
      }).then(() => {
        if (this.form.orderStatus === this.ORDER_STATUS.RECALLED) {
          this.$modal.msgError("此生产任务已经撤回，不能删除");
          return;
        }

        if (this.form.orderStatus === this.ORDER_STATUS.FINISHED) {
          this.$modal.msgError("此生产任务已经完成，不能删除");
          return;
        }

        if (this.form.orderStatus === this.ORDER_STATUS.DELETED) {
          this.$modal.msgError("此生产任务已经删除，不能删除");
          return;
        }


        if (scope.row.newFlag != null || scope.row.newFlag === '1') {
          //新增删除
          this.mesProductPlanList = this.mesProductPlanList.filter(function (item) {
            return scope.row.dispatchCode !== item.dispatchCode
          });
        } else {
          //历史删除
          let dispatchSum = 0; //需要减去的派工数量
          try {
            const planIds = this.mesProductPlanList.filter(function (item) {
              return scope.row.dispatchCode === item.dispatchCode
            }).map(item => {
              if (item.planStatus !== this.PLAN_STATUS.DISPATCHED && item.planStatus !== this.PLAN_STATUS.TO_DISPATCH) {
                throw Error("只能删除还未开始过状态的生产派工单！");
              }

              dispatchSum = item.dispatchAmount;//派工数量每一个工序都一样
              return item.planId;
            });

            deleteProductPlansByDispatchCode({
              productOrderId: this.form.productOrderId,
              dispatchCode: dispatchCode,
              dispatchAmount: dispatchSum
            }).then(res => {
              this.mesProductPlanList = this.mesProductPlanList.filter(function (item) {
                return dispatchCode !== item.dispatchCode
              });
              this.form.dispatchAmount = this.form.dispatchAmount - dispatchSum;
              this.$modal.msgSuccess("删除成功");

            });


          } catch (e) {
            this.$modal.msgError(e);
          }
        }
      }).catch(() => {
      });
    },

    /** 生产计划明细序号 */
    rowMesProductPlanIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },

    /** 复选框选中数据 */
    handleMesProductPlanSelectionChange(selection) {
      this.checkedMesProductPlanList = selection
      this.single = selection.length !== 1
    },

    /** 关闭按钮 */
    close() {
      const obj = {path: "/mes/prod/orderInfo", query: {t: Date.now(), queryParams: this.queryParams}};
      this.$tab.closeOpenPage(obj);
    },

    /** 生产计划添加按钮操作 */
    async handleAddMesProductPlan() {
      let dispatchCode = "";
      dispatchCode = await getDispatchCode().then(res => res.msg);
      console.log("dispatchCode", dispatchCode);

      const baseRouteProcesses = await getBaseRouteProcesses({ routeId: this.form.dispatchId });
      let lastProcessId = null;
      let i = 0;

      for (const e of baseRouteProcesses.data) {
        let obj = {};
        if (i === 0) {
          obj.firstFlag = "1"; // 设置第一条标识
          i++;
        }
        obj.id = this.id;
        this.id = this.id + 1;
        obj.dispatchCode = dispatchCode;
        obj.processId = e.processId;
        obj.processName = e.processName;
        obj.processType = e.processType;
        obj.processOrder = e.processOrder;
        obj.productionTime = e.productionTime ? parseFloat((e.productionTime / 60 / 60).toFixed(1)) : 0;

        obj.planBeginTime = this.form.planBeginTime;
        obj.planEndTime = this.form.planEndTime;
        obj.planStatus = '1';

        if (this.form.saleType === this.SALE_TYPE.INTERNAL) {
          obj.materialId = this.form.produceMaterialId;
        } else {
          obj.materialId = this.form.materialId;
        }

        obj.materialBomId = this.form.materialBomId;
        obj.productOrderId = this.form.productOrderId;
        obj.saleOrderId = this.form.saleOrderId;
        obj.saleorderCode = this.form.saleorderCode;

        obj.newFlag = "1"; // 代表新增
        obj.addFlag = "1";

        if (e.processType === this.PROCESS_TYPE.AUTO) {
          obj.children = [];
        } else {
          obj.children = [{
            id: this.id,
            dispatchCode: obj.dispatchCode,
            processId: obj.processId,
            materialBomId: obj.materialBomId,
            planStatus: this.PLAN_STATUS.DISPATCHED,
            productionTime: obj.productionTime,
            userId: null
          }]
        }

        this.id += 1;

        // 获取当前 processId 对应的工位信息
        const stationResponse = await getStationInfoList({ processId: e.processId });
        if (stationResponse.data && stationResponse.data.length > 0) {
          this.processStations[e.processId] = stationResponse.data.map(station => ({
            stationId: station.stationId,
            stationName: station.stationName
          }));
        }

        // 上一工序ID
        if (lastProcessId == null) {
          obj.lastProcessId = 0;
        } else if (lastProcessId === obj.processId) {
          obj.lastProcessId = this.mesProductPlanList[this.mesProductPlanList.length - 1].lastProcessId;
        } else {
          obj.lastProcessId = lastProcessId;
        }
        lastProcessId = e.processId;
        obj.oldRowFlag = false;
        this.mesProductPlanList.push(obj);
      }

      this.getId(this.mesProductPlanList);
      console.log(this.mesProductPlanList);
    },


    isPositiveInteger(value) {
      // 使用正则表达式匹配正整数
      return /^[0-9]\d*$/.test(value);
    },

    handleDeleteDispatchUser(row) {
      this.mesProductPlanList.forEach(mesProductPlan => {
        mesProductPlan.children = mesProductPlan.children.filter(item => item.id !== row.id);
      });
      if (row.planId != null && row.planId !== '') {
        this.toDeletedPlanIds.push(row.planId);
      }
    },


    isOptionDisabled(attachId) {
      // 根据业务逻辑，禁用某些选项的删除
      return this.materialBomAttachIdList.includes(attachId); // 例如可以禁用某些特定选项
    }

  },

  dispatchTypeList:[],
  async dispatchTypeFunction  () {

    const dispatchTypeRes = await proxy?.getConfigKey('sys.orderInfo.dispatchType');
    initFormData.dispatchType = dispatchTypeRes.data;
    if (dispatchTypeRes.data === '1'){
      dispatchTypeName.value = "产线";
      const res = await getProdLineList(null);
      dispatchTypeList.value = res.data.map(item => ({
        id: item.prodLineId,
        name: item.prodLineName
      }));
    } else if (dispatchTypeRes.data === '2'){
      dispatchTypeName.value = "工艺路线";
      const res = await getBaseRouteList(null);
      dispatchTypeList.value = res.data.map(item => ({
        id: item.routeId,
        name: item.routeName
      }));
    } else if (dispatchTypeRes.data === '3'){
      dispatchTypeName.value = "工序";
      const res = await getProcessInfoList(null);
      dispatchTypeList.value = res.data.map(item => ({
        id: item.processId,
        name: item.processName
      }));
    }
  },

}
;
onMounted(() => {
  dispatchTypeFunction();  //派工类型(1产线 2工艺路线 3工序)
});
</script>

<style scoped>
/deep/.el-icon-close{display:none}
/deep/.el-upload{
  display: none;
}
</style>
