<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 slot-scope="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="mini" 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 slot-scope="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 slot-scope="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 slot-scope="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 slot-scope="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 slot-scope="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 slot-scope="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 slot-scope="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 slot-scope="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="productionTime" width="180">
            <template slot-scope="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 slot-scope="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 slot-scope="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 slot-scope="scope">
              {{scope.row.planStatus}}

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


          <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="100">
            <template slot-scope="scope">
              <el-button
                icon="el-icon-search"
                size="mini"
                type="primary"
                @click="handleDrawing(scope.row)"
                v-if=" scope.row.userId != null"
              >图纸
              </el-button>
              <el-button
                icon="el-icon-search"
                size="mini"
                type="success"
                @click="handleSop(scope.row)"
                v-if=" scope.row.userId != null"
              >SOP
              </el-button>

              <el-button
                icon="el-icon-lock"
                size="mini"
                type="primary"
                @click="handleApplyRawOutstock(scope.row)"
                v-if="scope.row.processType === PROCESS_TYPE.AUTO && scope.row.planId!=null && scope.row.planId!==''
                      && scope.row.planStatus !== PLAN_STATUS.FINISHED
                      && form.orderStatus!==ORDER_STATUS.FINISHED && form.orderStatus!==ORDER_STATUS.RECALLED && form.orderStatus!==ORDER_STATUS.DELETED"
              >投料
              </el-button>


              <el-button
                icon="el-icon-delete"
                size="mini"
                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>
    <el-dialog
      :visible.sync="blueprintModel"
      title="上传图纸"
      width="30%"
      @before-close="blueprintModel = false">
      <el-form ref="form">
        <el-form-item label="选择BOM图纸">
          <el-select v-model="materialBomAttachIdList"  placeholder="请选择选择BOM图纸" multiple filterable :clearable="false"
                     :disabled="(addProductPlanObject.planStatus !== PLAN_STATUS.DISPATCHED)">
            <el-option
              v-for="item in attachInfoList"
              :key="item.attachId"
              :label="item.attachName"
              :value="item.attachId"
              :disabled="isOptionDisabled(item.attachId)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-upload
        single
        ref="drawingUpload"
        list-type="picture-card"
        action="uploadDrawingUrl"
        :auto-upload="true"
        :limit="drawingLimit"
        :headers="headers"
        :before-upload="handleBeforeUpload"
        :http-request="httpRequest"
        :on-exceed="handleExceed"
        :file-list="fileList"
      >
        <i slot="default" class="el-icon-plus"></i>
        <div slot="file" slot-scope="{file}">
          <img
            v-if="isAssetTypeAnImage(file.name)"
            :alt="file.name"
            :src="file.url" class="el-upload-list__item-thumbnail"
          >
          <span v-else>{{ file.name }}</span>
          <span class="el-upload-list__item-actions">
        <span
          v-if="isAssetTypeAnImage(file.name)"
          class="el-upload-list__item-preview"
          @click="handlePictureCardPreview(file)"
        >
          <i class="el-icon-zoom-in"></i>
        </span>
        <span
          class="el-upload-list__item-delete"
          @click="handleDownload(file)"
        >
          <i class="el-icon-download"></i>
        </span>
        <span
          class="el-upload-list__item-delete"
          @click="handleRemoveDrawing(file)"
          v-if="addProductPlanObject.planStatus === PLAN_STATUS.DISPATCHED"
        >
          <i class="el-icon-delete"></i>
        </span>
      </span>
        </div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <!-- 上传提示 -->
    <el-button type="primary" @click="drawingFileUploadSubmit">确 定</el-button>
    <el-button @click="blueprintModel = false">取 消</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :visible.sync="sopViewModel"
      title="上传SOP附件"
      width="30%"
      @before-close="sopViewModel = false">
      <el-form ref="form">
        <el-form-item label="选择BOM的SOP">
          <el-select v-model="materialBomAttachIdList"  placeholder="请选择选择BOM的SOP" multiple filterable :clearable="false"
                     :disabled="(addProductPlanObject.planStatus !== PLAN_STATUS.DISPATCHED)">
            <el-option
              v-for="item in attachInfoList"
              :key="item.attachId"
              :label="item.attachName"
              :value="item.attachId"
              :disabled="isOptionDisabled(item.attachId)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-upload
        single
        ref="drawingUpload"
        list-type="picture-card"
        action="uploadImgUrl"
        :auto-upload="true"
        :limit="sopLimit"
        :headers="headers"
        :before-upload="handleBeforeUpload"
        :http-request="httpSopRequest"
        :on-exceed="handleExceed"
        :file-list="fileList"
      >
        <i slot="default" class="el-icon-plus"></i>
        <div slot="file" slot-scope="{file}">
          <img
            v-if="isAssetTypeAnImage(file.name)"
            :alt="file.name"
            :src="file.url" class="el-upload-list__item-thumbnail"
          >
          <span v-else>{{ file.name }}</span>
          <span class="el-upload-list__item-actions">
        <span
          v-if="isAssetTypeAnImage(file.name)"
          class="el-upload-list__item-preview"
          @click="handlePictureCardPreview(file)"
        >
          <i class="el-icon-zoom-in"></i>
        </span>
        <span
          class="el-upload-list__item-delete"
          @click="handleDownload(file)"
        >
          <i class="el-icon-download"></i>
        </span>
        <span
          class="el-upload-list__item-delete"
          @click="handleRemoveSop(file)"
          v-if="addProductPlanObject.planStatus === PLAN_STATUS.DISPATCHED"
        >
          <i class="el-icon-delete"></i>
        </span>
      </span>
        </div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <!-- 上传提示 -->
<!--    <div class="el-upload__tip" slot="tip" v-if="isShowTip">-->
<!--      请上传-->
<!--      <template v-if="sopFileSize"> 大小不超过 <b style="color: #f56c6c">{{ sopFileSize }}MB</b></template>-->
<!--      <template v-if="sopFileType"> 格式为 <b style="color: #f56c6c">{{ sopFileType.join("/") }}</b></template>-->
<!--      的文件-->
<!--    </div>-->
    <el-button type="primary" @click="sopFileUploadSubmit">确 定</el-button>
    <el-button @click="sopViewModel = false">取 消</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :visible.sync="pictureDetailModel"
      title="图纸预览"
      width="800"
      append-to-body
    >
      <img
        :src="dialogImageUrl"
        style="display: block; max-width: 100%; margin: 0 auto"
      />
    </el-dialog>


    <!-- 投料信息对话框 -->
    <el-dialog title="投料" :visible.sync="applyRawOutstockOpen" append-to-body>
      <apply-raw-outstock ref="applyRawOutstockRef" :defineData="productPlanData"
                          v-if="applyRawOutstockOpen"></apply-raw-outstock>
    </el-dialog>
  </div>
</template>

<script>
// import {getProductOrder} from "@//api/mes/productOrder";
// import {
//   deleteProductPlansByDispatchCode,
//   getDispatchCode,
//   selectProductPlans,
//   checkAddMesProductPlanList,
//   orderAddMesProductPlanList,
//   getBaseRouteProcesses,
//   getProcessUsers,
//   uploadFile, getAttachInfoList
// } from "@//api/mes/productplan";
// import {getConfigKey} from "@//api/system/config"
// import {deepClone} from "@//utils/index";
// import {getToken} from "@//utils/auth";
// import {getBomAttachInfo, listMaterialBom} from "@/api/mes/materialBom";
// import {listMaterialinfo} from "@/api/mes/materialinfo";

let id = 0
let deepSearch = (arr, target) => {
  let results = []
  arr.forEach(element => {
    console.log(element)
    id = Math.max(id, element.id)
    if (element.id === target) {
      results.push(element)
    } else if (Array.isArray(element.children)) {
      results = results.concat(deepSearch(element.children, target))
    }
    // if (Array.isArray(element.children)) {
    //   results = results.concat(deepSearch(element.children, target))
    // } else if (element.id === target) {
    //   results.push(element)
    // }
  })
  return results
}


export default {
  name: "productPlanEdit",
  dicts: ['plan_status', 'product_status', 'mes_dispatch_flag'],
  provide() {
    return {
      closeRawOutstockDialog: this.closeRawOutstockDialog,
    }
  },
  props: {
    value: [String, Object, Array, Number],
    // sop文件数量限制
    sopLimit: {
      type: Number,
      default: 20,
    },
    // 图纸数量限制
    drawingLimit: {
      type: Number,
      default: 20,
    },

    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      blueprintModel: false,
      sopViewModel: false,
      pictureDetailModel: false,
      // 图片预览地址
      dialogImageUrl: '',
      // 非单个禁用
      single: true,
      checkedMesProductPlanList: [],
      // 上传的文件服务器地址
      uploadImgUrl: import.meta.env.VUE_APP_BASE_API,
      uploadDrawingUrl: import.meta.env.VUE_APP_BASE_API + "/file/upload2SharePath",
      // 选中选项卡的 name
      activeName: "columnInfo",
      // 表格的高度
      tableHeight: document.documentElement.scrollHeight - 245 + "px",
      // 表信息
      tables: [],
      // 表列信息
      columns: [],
      // 生产计划表格数据
      mesProductPlanList: [],
      //待删除的生产计划ID
      toDeletedPlanIds: [],

      applyRawOutstockOpen: false,
      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: [],
      //物料BOMList
      attachInfoList: [],
      //选中的BOMList
      materialBomAttachIdList: [],
    };
  },
  watch: {
    'materialBomAttachIdList': {
      handler(newVal, oldVal)  {
        this.updateAttachInfoByBom(newVal, oldVal);
      },
    }
  },
  created() {
    // const productOrderId = this.$route.params && this.$route.params.productOrderId;
    // if (productOrderId) {
    //   // 获取表详细信息
    //   getProductOrder(productOrderId).then(res => {
    //     this.form = res.data;
    //     this.getProcessUsers(productOrderId);
    //   });
    // }
    //
    //
    // this.getConfigValues();
  },
  methods: {
    getConfigValues(){
      //图纸支持格式
      getConfigKey("mes.drawing.allowedExtension").then(res => {
        if(res.msg){
          this.drawingFileType = res.msg.split(",");
        }
      });

      getConfigKey("mes.drawing.maxSize").then(res => {
        if(res.msg){
          this.drawingFileSize = res.msg;
        }
      });

      getConfigKey("mes.sop.allowedExtension").then(res => {
        if(res.msg){
          this.sopFileType = res.msg.split(",");
        }
      });

      getConfigKey("mes.sop.maxSize").then(res => {
        if (res.msg) {
          this.sopFileSize = res.msg;
        }
      });

    },

    getProcessUsers(productOrderId) {
      getProcessUsers(this.form.dispatchId).then(res => {
        res.data.forEach(processUser => {
          if (!this.processUsers[processUser.processId]) {
            this.processUsers[processUser.processId] = [];
          }
          this.processUsers[processUser.processId].push(processUser);
        });

        selectProductPlans({productOrderId: productOrderId}).then(res => {
          this.groupProductPlans(res.data)
          // res.data.forEach(e => {
          //   // 新添加列标识 false=新添加，true=历史行
          //   e.oldRowFlag = true;
          //   this.mesProductPlanList.push(e);
          // })
        })
      });
    },

    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)

    },

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

    addProcessUser(scope) {
      let finishStatus = this.PLAN_STATUS.FINISHED
      const filterPlanList = this.mesProductPlanList.filter(function (item) {
        return scope.row.dispatchCode + "-" + scope.row.processId === item.dispatchCode + "-" + item.processId
          && item.planStatus !== finishStatus;
      })

      if (filterPlanList.length <= 0) {
        this.$modal.msgError("此工序已经完成，不能添加");
        return;
      }

      let data = deepSearch(this.mesProductPlanList, scope.row.id)?.[0]
      let id = this.id + 1
      this.id += 1;
      if (Array.isArray(data.children)) {

        this.$set(data.children, data.children.length, {
          id: id,
          dispatchCode: scope.row.dispatchCode,
          processId: scope.row.processId,
          productionTime: scope.row.productionTime,
          materialBomId: scope.row.materialBomId,
          planStatus: this.PLAN_STATUS.DISPATCHED,
          userId: null
        })
      } else {
        this.$set(data, 'children', [
          {
            id: id,
            dispatchCode: scope.row.dispatchCode,
            processId: scope.row.processId,
            productionTime: scope.row.productionTime,
            materialBomId: scope.row.materialBomId,
            planStatus: this.PLAN_STATUS.DISPATCHED,
            userId: null,
          }
        ])
      }


      this.id += 1
      // this.show = false
      // this.show = true
    },


    isAssetTypeAnImage(ext) {
      let suffix = ext.lastIndexOf(".");
      let name = ext.substr(suffix + 1);
      return ['png', 'jpg', 'jpeg'].includes(name.toLowerCase())
    },
    /** 提交按钮 */
    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/plan/productOrder", query: {t: Date.now(), queryParams: this.$route.query.queryParams}};
      this.$tab.closeOpenPage(obj);
    },


    /** 生产计划添加按钮操作 */
    handleAddMesProductPlan() {
      let dispatchCode = "";
      getDispatchCode().then(res => {
        dispatchCode = res.msg;
        getBaseRouteProcesses({routeId: this.form.dispatchId}).then(res => {
          // if (res.data.length === 0) {
          //   this.$modal.msgError("工艺路线未维护工位信息！");
          // }
          let lastProcessId = null;
          let i = 0;
          res.data.forEach((e, index) => {
            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.finalProcessFlag = e.finalProcessFlag;
            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';
            // obj.dispatchAmount = this.form.planAmount - this.form.dispatchAmount;
            obj.dispatchFlag = null;

            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";

            // e.mesBaseProcessUserList.forEach((mesBaseProcessUser, index) => {
            //   mesBaseProcessUser.id = this.id + 1;
            //   mesBaseProcessUser.dispatchFlag = null;
            //   mesBaseProcessUser.planBeginTime = null;
            //   mesBaseProcessUser.planEndTime = null;
            //   this.id = this.id + 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;

            // 上一工序ID
            if (lastProcessId == null) {
              obj.lastProcessId = 0;
            } else if (lastProcessId === obj.processId) {
              obj.lastProcessId = this.mesProductPlanList[index - 1].lastProcessId;
            } else {
              obj.lastProcessId = lastProcessId;
            }
            lastProcessId = e.processId;
            // 新添加列标识 false=新添加，true=历史行
            obj.oldRowFlag = false;
            this.mesProductPlanList.push(obj);
          })

          this.getId(this.mesProductPlanList)
        })
      })
    },


    isPositiveInteger(value) {
      // 使用正则表达式匹配正整数
      return /^[0-9]\d*$/.test(value);
    },
    //查看图纸预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.pictureDetailModel = true;
    },
    //图纸下载
    handleDownload(file) {
      window.open(file.url);
    },


    /** 查看图纸 */
    handleDrawing(row) {
      this.fileList = [];
      if (row.planId != null && (!this.previewDrawingFlag[row.dispatchCode + "-" + row.processId + "-" + row.userId]
        || this.previewDrawingFlag[row.dispatchCode + "-" + row.processId + "-" + row.userId] !== "1")) {
        this.previewDrawingFlag[row.dispatchCode + "-" + row.processId + "-" + row.userId] = "1";
        getAttachInfoList(this.ATTACH_TYPE.DRAWING, row.dispatchCode, row.processId, row.userId).then(res => {
          let attachList = res.data;
          attachList.forEach(e => {
            let previewFile = {};
            previewFile.url = e.attachPath;
            previewFile.name = e.attachName;
            this.fileList.push(previewFile);

            let groupAttachFile = {};
            groupAttachFile.dispatchCode = row.dispatchCode;
            groupAttachFile.processId = row.processId;
            groupAttachFile.attachId = e.attachId;
            groupAttachFile.attachPath = e.attachPath;
            groupAttachFile.attachName = e.attachName;
            let groupAttachFileList = this.groupAttachFileList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId];
            this.groupAttachFileList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId] = groupAttachFileList ? this.groupAttachFileList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId] : [];
            this.groupAttachFileList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId].push(groupAttachFile);

            let uploadAttachList = this.uploadAttachList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId];
            this.uploadAttachList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId] = uploadAttachList ? this.uploadAttachList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId] : [];
            this.uploadAttachList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId].push(e.attachId);

          })
        })
      } else {
        if (this.groupAttachFileList[row.dispatchCode + "-" + row.processId + "-" + row.userId]) {
          this.groupAttachFileList[row.dispatchCode + "-" + row.processId + "-" + row.userId].forEach(e => {
            let previewFile = {};
            previewFile.url = e.attachPath;
            previewFile.name = e.attachName;
            this.fileList.push(previewFile);
          })
        }
      }

      this.addProductPlanObject = row;
      this.materialBomAttachIdList = [];
      getBomAttachInfo(this.ATTACH_TYPE.DRAWING, this.addProductPlanObject.materialBomId).then(response => {
        this.attachInfoList = response.data;
        for (let e of this.fileList) {
          let attachInfo = this.attachInfoList.find(item => item.attachPath === e.url);
          if (attachInfo != null){
            this.materialBomAttachIdList.push(attachInfo.attachId);
          }
        }
        this.blueprintModel = true;
      });
    },

    //添加图纸提交
    drawingFileUploadSubmit() {
      for (let i = 0; i < this.mesProductPlanList.length; i++) {
        let mesProductPlan = this.mesProductPlanList[i];
        for (let child of mesProductPlan.children) {
          if (mesProductPlan.dispatchCode === this.addProductPlanObject.dispatchCode
            && mesProductPlan.processId === this.addProductPlanObject.processId
            && child.userId === this.addProductPlanObject.userId) {
            child.attachId = this.uploadAttachList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId].join(",");
          }
        }
      }
      // this.uploadAttachList = [];
      this.addProductPlanObject = {};
      this.blueprintModel = false;
    },


    //图纸图片上传
    httpRequest(file) {
      // 文件信息
      const fileData = file.file;
      const formData = new FormData();
      formData.append("file", fileData);
      formData.append("processId", this.addProductPlanObject.processId);
      formData.append("attachType", this.ATTACH_TYPE.DRAWING);
      uploadFile(formData).then(
        (res) => {
          let uploadAttachList = this.uploadAttachList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId];
          this.uploadAttachList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId] = uploadAttachList ? this.uploadAttachList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId] : [];
          this.uploadAttachList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId].push(res.attachId);

          // 存储附件信息主键
          let groupAttachFile = {};
          groupAttachFile.dispatchCode = this.addProductPlanObject.dispatchCode;
          groupAttachFile.processId = this.addProductPlanObject.processId;
          groupAttachFile.attachId = res.attachId;
          groupAttachFile.attachPath = res.imgUrl;
          groupAttachFile.attachName = res.fileName;
          let groupAttachFileList = this.groupAttachFileList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId];
          this.groupAttachFileList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId] = groupAttachFileList ? this.groupAttachFileList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId] : [];
          this.groupAttachFileList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId].push(groupAttachFile);
          this.$modal.closeLoading();
        }, (err) => {
          this.$refs.drawingUpload.clearFiles();  //上传失败后清除当前上传的图片
          this.$modal.closeLoading();
        }
      );
    },

    //删除上传的图片
    handleRemoveDrawing(file) {
      let arrPic = this.$refs.drawingUpload.uploadFiles;
      let index = arrPic.indexOf(file);
      this.uploadAttachList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId].splice(index, 1);
      // this.uploadAttachList.splice(index, 1);
      this.fileList.splice(index, 1);
      this.groupAttachFileList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId].splice(index, 1);
      let num = 0;
      arrPic.map((item) => {
        if (item.uid === file.uid) {
          arrPic.splice(num, 1);
        }
        num++;
      });
      let attachInfo = this.attachInfoList.find(item => item.attachPath === file.url);
      if (attachInfo != null){
        this.materialBomAttachIdList = this.materialBomAttachIdList.filter(item => item !== attachInfo.attachId);
      }
    },


    /** 查看sop */
    handleSop(row) {
      this.fileList = [];
      if (row.planId != null && (!this.previewSopFlag[row.dispatchCode + "-" + row.processId + "-" + row.userId]
        || this.previewSopFlag[row.dispatchCode + "-" + row.processId + "-" + row.userId] !== "1")) {
        this.previewSopFlag[row.dispatchCode + "-" + row.processId + "-" + row.userId] = "1";
        getAttachInfoList(this.ATTACH_TYPE.SOP, row.dispatchCode, row.processId, row.userId).then(res => {
          let attachList = res.data;
          attachList.forEach(e => {
            let previewFile = {};
            previewFile.url = e.attachPath;
            previewFile.name = e.attachName;
            this.fileList.push(previewFile);

            let groupSopFile = {};
            groupSopFile.dispatchCode = row.dispatchCode;
            groupSopFile.processId = row.processId;
            groupSopFile.attachId = e.attachId;
            groupSopFile.attachPath = e.attachPath;
            groupSopFile.attachName = e.attachName;
            let groupSopFileList = this.groupSopFileList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId];
            this.groupSopFileList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId] = groupSopFileList ? this.groupSopFileList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId] : [];
            this.groupSopFileList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId].push(groupSopFile);

            let uploadSopList = this.uploadSopList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId];
            this.uploadSopList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId] = uploadSopList ? this.uploadSopList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId] : [];
            this.uploadSopList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId].push(e.attachId);

          })
        })
      } else {
        if (this.groupSopFileList[row.dispatchCode + "-" + row.processId + "-" + row.userId]) {
          this.groupSopFileList[row.dispatchCode + "-" + row.processId + "-" + row.userId].forEach(e => {
            let previewFile = {};
            previewFile.url = e.attachPath;
            previewFile.name = e.attachName;
            this.fileList.push(previewFile);
          })
        }
      }

      this.addProductPlanObject = row;
      this.materialBomAttachIdList = [];
      getBomAttachInfo(this.ATTACH_TYPE.SOP, this.addProductPlanObject.materialBomId).then(response => {
        this.attachInfoList = response.data;
        for (let e of this.fileList) {
          let attachInfo = this.attachInfoList.find(item => item.attachPath === e.url);
          if (attachInfo != null){
            this.materialBomAttachIdList.push(attachInfo.attachId);
          }
        }
        this.sopViewModel = true;
      });
    },

    //添加sop提交
    sopFileUploadSubmit() {
      for (let i = 0; i < this.mesProductPlanList.length; i++) {
        let mesProductPlan = this.mesProductPlanList[i];
        for (let child of mesProductPlan.children) {
          if (mesProductPlan.dispatchCode === this.addProductPlanObject.dispatchCode
            && mesProductPlan.processId === this.addProductPlanObject.processId
            && child.userId === this.addProductPlanObject.userId) {
            child.sopId = this.uploadSopList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId].join(",");
          }
        }
      }
      // this.uploadAttachList = [];
      this.addProductPlanObject = {};
      this.sopViewModel = false;
    },


    //Sop图片上传
    httpSopRequest(file) {
      // 文件信息
      const fileData = file.file;
      const formData = new FormData();
      formData.append("file", fileData);
      formData.append("processId", this.addProductPlanObject.processId);
      formData.append("attachType", this.ATTACH_TYPE.SOP);
      uploadFile(formData).then(
        (res) => {
          let uploadSopList = this.uploadSopList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId];
          this.uploadSopList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId] = uploadSopList ? this.uploadSopList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId] : [];
          this.uploadSopList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId].push(res.attachId);

          // 存储附件信息主键
          let groupSopFile = {};
          groupSopFile.dispatchCode = this.addProductPlanObject.dispatchCode;
          groupSopFile.processId = this.addProductPlanObject.processId;
          groupSopFile.attachId = res.attachId;
          groupSopFile.attachPath = res.imgUrl;
          groupSopFile.attachName = res.fileName;
          let groupSopFileList = this.groupSopFileList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId];
          this.groupSopFileList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId] = groupSopFileList ? this.groupSopFileList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId] : [];
          this.groupSopFileList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId].push(groupSopFile);
          this.$modal.closeLoading();
        }, (err) => {
          this.$refs.drawingUpload.clearFiles();  //上传失败后清除当前上传的图片
          this.$modal.closeLoading();
        }
      );
    },

    //删除上传的图片
    handleRemoveSop(file) {
      let arrPic = this.$refs.drawingUpload.uploadFiles;
      let index = arrPic.indexOf(file);
      this.uploadSopList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId].splice(index, 1);
      this.groupSopFileList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId].splice(index, 1);
      this.fileList.splice(index, 1);
      let num = 0;
      arrPic.map((item) => {
        if (item.uid === file.uid) {
          arrPic.splice(num, 1);
        }
        num++;
      });
      let attachInfo = this.attachInfoList.find(item => item.attachPath === file.url);
      if (attachInfo != null){
        this.materialBomAttachIdList = this.materialBomAttachIdList.filter(item => item !== attachInfo.attachId);
      }
    },


    // 上传前loading加载
    handleBeforeUpload(file) {
      let fileType, fileSize;
      if (this.sopViewModel) {
        fileType = this.sopFileType;
        fileSize = this.sopFileSize;
      } else if (this.blueprintModel) {
        fileType = this.drawingFileType;
        fileSize = this.drawingFileSize;
      }

      let isImg = false;
      if (fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${fileType.join("/")}格式文件!`);
        return false;
      }
      if (fileSize) {
        const isLt = file.size / 1024 / 1024 < fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传文件，请稍候...");
      this.number++;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} !`);
    },

    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);
      }

    },

    handleApplyRawOutstock(row) {
      if (row.processType === this.PROCESS_TYPE.AUTO) {
        this.applyRawOutstockOpen = true;
        this.productPlanData.planCode = row.planCode;
        this.productPlanData.planId = row.planId;
        this.productPlanData.dispatchAmount = row.dispatchAmount;
        this.productPlanData.saleOrderId = this.form.saleOrderId;
        this.productPlanData.materialBomId = this.form.materialBomId;
      }
    },

    closeRawOutstockDialog() {
      this.applyRawOutstockOpen = false;
    },
    //根据BOM更新图纸或SOP
    updateAttachInfoByBom(newVal, oldVal) {
      if (newVal.length === 0) {
        return
      }
      let result = [];
      let targetAttachIds = newVal.filter(item => !oldVal.includes(item));
      for (let targetAttachId of targetAttachIds) {
        result.push(this.attachInfoList.find(item => item.attachId === targetAttachId));
      }
      console.log("result:",result);
      let isDrawing = this.blueprintModel;
      //图纸
      if (isDrawing) {
        for (let e of result) {
          let previewFile = {};
          previewFile.url = e.attachPath;
          previewFile.name = e.attachName;
          this.fileList.push(previewFile);
          let groupAttachFile = {};
          groupAttachFile.dispatchCode = this.addProductPlanObject.dispatchCode;
          groupAttachFile.processId = this.addProductPlanObject.processId;
          groupAttachFile.attachId = e.attachId;
          groupAttachFile.attachPath = e.attachPath;
          groupAttachFile.attachName = e.attachName;
          let groupAttachFileList = this.groupAttachFileList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId];
          this.groupAttachFileList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId] = groupAttachFileList ? this.groupAttachFileList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId] : [];
          this.groupAttachFileList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId].push(groupAttachFile);
          let uploadAttachList = this.uploadAttachList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId];
          this.uploadAttachList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId] = uploadAttachList ? this.uploadAttachList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId] : [];
          this.uploadAttachList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId].push(e.attachId);
        }
      } else {
        //SOP
        for (let e of result) {
          let previewFile = {};
          previewFile.url = e.attachPath;
          previewFile.name = e.attachName;
          this.fileList.push(previewFile);
          let groupSopFile = {};
          groupSopFile.dispatchCode = this.addProductPlanObject.dispatchCode;
          groupSopFile.processId = this.addProductPlanObject.processId;
          groupSopFile.attachId = e.attachId;
          groupSopFile.attachPath = e.attachPath;
          groupSopFile.attachName = e.attachName;
          let groupSopFileList = this.groupSopFileList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId];
          this.groupSopFileList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId] = groupSopFileList ? this.groupSopFileList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId] : [];
          this.groupSopFileList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId].push(groupSopFile);
          let uploadSopList = this.uploadSopList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId];
          this.uploadSopList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId] = uploadSopList ? this.uploadSopList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId] : [];
          this.uploadSopList[this.addProductPlanObject.dispatchCode + "-" + this.addProductPlanObject.processId + "-" + this.addProductPlanObject.userId].push(e.attachId);
        }
      }
    },

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

  },



  mounted() {
  }
}
;
</script>

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