<template>
  <div class="ele-body">
    <el-card shadow="never">
      <div class="body-title">
        <div class="title-left">{{
          type == 'edit' ? '计划修改' : '销售订单转生产计划'
        }}</div>
        <div class="title-right">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="toSubmit"> 保存 </el-button>
        </div>
      </div>

      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="formbox"
      >
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="计划类型:">
              <DictSelection
                dictName="订单计划类型"
                clearable
                v-model="form.planType"
                disabled
              >
              </DictSelection>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item
              :class="isRequired ? 'header_required' : ''"
              label="BOM类型:"
              prop="produceType"
            >
              <el-select
                v-model="form.produceType"
                style="width: 100%"
                @change="changeProduceType"
              >
                <el-option
                  v-for="item of producedList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6" v-if="clientEnvironmentId != 4">
            <el-form-item
              :class="isRequired ? 'header_required' : ''"
              label="BOM版本:"
              prop="bomCategoryId"
            >
              <el-select
                v-model="form.bomCategoryId"
                style="width: 100%"
                @change="changeBomId"
              >
                <el-option
                  v-for="item of bomVersionList"
                  :key="item.id"
                  :label="item.name + '(V' + item.versions + '.0)'"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="clientEnvironmentId != 4">
            <el-form-item label="工艺路线:" prop="produceRoutingId">
              <!--  @click.native="openVersion"   -->
              <div style="display: flex">
                <el-select
                  v-model="form.produceRoutingId"
                  style="width: 100%"
                  @change="changeRoute"
                  v-show="isRouteSelect"
                >
                  <el-option
                    v-for="item of routingList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>

                <div
                  :style="{
                    display: 'flex',
                    width: !isRouteSelect ? '100%' : ''
                  }"
                >
                  <el-input
                    v-show="!isRouteSelect"
                    disabled
                    v-model="form.produceRoutingName"
                    style="width: 100%"
                  ></el-input>
                  <el-button
                    v-show="isSelectShow"
                    type="primary"
                    size="mini"
                    @click="openDialog"
                    >选择</el-button
                  >
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="clientEnvironmentId == 4">
            <el-form-item label="工艺路线:" prop="produceRoutingId">
              <el-input
                v-model="form.produceRoutingName"
                style="width: 100%"
                readonly
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="余量系数:" prop="marginCoefficient">
              <el-select
                v-model="form.marginCoefficient"
                filterable
                allow-create
                @change="itemChange"
              >
                <el-option
                  v-for="(item, index) in marginList"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="批次号:" prop="batchNo">
              <el-input
                placeholder="请输入批次号"
                v-model="form.batchNo"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产要求:" prop="productionRequirements">
              <el-input
                placeholder=" "
                v-model="form.productionRequirements"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="所属工厂:" prop="factoriesId">
              <el-select v-model="form.factoriesId" style="width: 100%">
                <el-option v-for="item of factoryList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="6">
            <el-form-item label="工艺路线:" prop="produceRoutingId">
              <el-select v-model="form.produceRoutingId" style="width: 100%" @change="changeRoute">
                <el-option v-for="item of routingList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->

          <!-- <el-col :span="6">
            <el-form-item label="工艺路线:" prop="produceRoutingId">
              <el-input v-model="form.produceRoutingName" style="width: 100%" readonly></el-input>
            </el-form-item>
          </el-col> -->
        </el-row>

        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="计划数量:" prop="batchNo">
              <el-input
                placeholder="请输入计划数量"
                v-model="form.productNum"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>

          <!-- <el-col :span="6">
            <el-form-item label="计划重量:" prop="">
              <el-input placeholder="请输入计划重量" v-model="form.productWeight" disabled></el-input>
            </el-form-item>
          </el-col> -->

          <el-col :span="6">
            <el-form-item label="要求生产数量:">
              <el-input
                placeholder="请输入要求生产数量"
                v-model="form.requiredFormingNum"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>

          <!-- <el-col :span="6">
            <el-form-item label="要求生产重量:">
              <el-input placeholder="请输入要求生产重量" v-model="form.newSumOrderWeight" disabled></el-input>
            </el-form-item>
          </el-col> -->

          <el-col :span="6">
            <el-form-item label="名称:">
              <el-input
                placeholder="请输入名称"
                v-model="form.productName"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="编码:">
              <el-input
                placeholder="请输入编码"
                v-model="form.productCode"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="计划编号:">
              <el-input
                placeholder="请输入计划编号"
                v-model="form.code"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="牌号:">
              <el-input v-model="form.brandNo" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="规格:">
              <el-input v-model="form.specification" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="型号:">
              <el-input v-model="form.model" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <AdditionalOrder
        ref="additionalRefs"
        :productCode="form.productCode"
        :selectList="form.salesOrders"
        @choose="confirmChoose"
      ></AdditionalOrder>
      <ProductionVersion
        ref="versionRefs"
        @changeProduct="changeProduct"
      ></ProductionVersion>
      <PlanSubmit
        ref="submitRefs"
        :type="$route.query.type"
        :info="form"
        @publish="publishData"
      ></PlanSubmit>
      <ProcessRoute ref="processRouteRef" @changeParent="changeParent" />
    </el-card>
  </div>
</template>
<script>
  import AdditionalOrder from './components/AdditionalOrder.vue';
  import PlanSubmit from './components/plan-submit.vue';
  import ProductionVersion from '@/components/CreatePlan/ProductionVersion2.vue';
  import {
    bomListByPlan,
    bomRoutingList,
    getFactoryList,
    getInventory,
    getUpdateInfoById,
    productionToPlan,
    releaseSave,
    saveSaleToPlan,
    updateSaleToPlan
  } from '@/api/saleOrder';

  import { planIsReview } from '@/api/productionPlan/index.js';

  import { getByCode } from '@/api/system/dictionary-data';
  import { parameterGetByCode } from '@/api/mainData/index';
  import dictMixins from '@/mixins/dictMixins';
  import { deepClone } from '@/utils/index';
  import { getRouteTabKey, removePageTab } from '@/utils/page-tab-util';
  import { getCode } from '@/api/codeManagement';
  import dayjs from 'dayjs';
  import { debounce } from 'lodash';
  import ProcessRoute from '@/components/selectionDialog/processRoute.vue';

  export default {
    mixins: [dictMixins],
    components: {
      AdditionalOrder,
      ProductionVersion,
      PlanSubmit,
      ProcessRoute
    },
    props: {
      formData: {
        type: Object,
        default: {}
      }
    },
    watch: {
      formData: {
        handler(val) {
          Object.assign(this.form, val);
          // console.log(this.form,'1111111111122222');
          this.$nextTick(() => {
            if (val.produceRoutingId) {
              this.bomListVersion();
              this.changeBomId();
            }
            this.$set(this.form, 'produceRoutingId', val.produceRoutingId);
          });
        },
        deep: true,
        immediate: true
      },
      selectionRowShow(val) {
        console.log(val, 'val ++++++');
        this.selectionRowShow = val;
      }
    },
    data() {
      return {
        type: this.$route.query.type,
        weightList: [
          { code: 1, name: 'A' },
          { code: 2, name: 'B' },
          { code: 3, name: 'C' }
        ],
        isSlotting: [
          { code: 1, name: '是' },
          { code: 2, name: '否' }
        ], //是否开槽

        producedList: [
          // { code: 2, name: '加工(MBOM)' },
          // { code: 3, name: '装配(ABOM)' }
        ],

        form: {
          planType: 1,
          produceRoutingId: '',

          stockCountBase: '',
          salesOrders: [],
          produceRoutingName: '',
          marginCoefficient: '1.0',
          batchNo: null,
          produceType: 1,
          bomCategoryId: '',
          factoriesId: '',
          productPlanList: []
        },

        marginList: [],

        bomVersionList: [],
        routingList: [],
        factoryList: [],

        // 表单验证规则
        rules: {
          produceRoutingId: [
            { required: true, message: '请选择工艺路线', trigger: 'blur' }
          ]

          // factoriesId: [
          //   { required: true, message: '请选择所属工厂', trigger: 'change' }
          // ]
        },
        // selection: [],
        loading: false,
        processingRequired: 0, // 生产类型跟BOM 版本是否必填 1:是 0:否
        selectionRowShow: false, // 工艺路线输入框展示 状态
        isReview: false
      };
    },
    computed: {
      clientEnvironmentId() {
        return this.$store.state.user.info.clientEnvironmentId;
      },
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      },
      // 是否必填字段
      isRequired() {
        // if (this.form.planType == 5) {
        //   return false;
        // }
        return this.processingRequired == 1;
      },
      // 工艺路线 输入框展示跟选择框判断
      isRouteSelect() {
        if (this.isRequired) {
          return true;
        }
        if (!this.selectionRowShow) {
          return true;
        }
        return false;
      },

      // 选择按钮的显示
      isSelectShow() {
        return this.processingRequired == 0;
      }
    },
    created() {
      this.getProducedData();
      this.requestDict('按单按库');
      this.requestDict('订单类型');
      this.requestDict('交付要求');
      this.getByCodeFn();
      this.getFactoryList();
      if (this.type == 'edit') {
        this.getPlanInfo(this.$route.query.id);
      } else {
        this.getSaleInfo();
      }
      // this.bomListVersion();
      this.mandatoryField();
      this.getplannedReleaseRequire('planned_release_require');
    },
    methods: {
      async getProducedData() {
        console.log(3333333333333333333333333);
        let query = this.$route.query;
        let producedList = query.producedList
          ? JSON.parse(query.producedList)
          : [];
        console.log(query, 'query');
        console.log(producedList, 'producedList');
        // this.form.produceType = query.produceType || 2;
        if (!producedList || producedList.length === 0) {
          this.producedList = [
            { code: 2, name: 'MBOM' },
            { code: 3, name: 'ABOM' }
          ];
          return;
        }
        this.producedList = JSON.parse(this.$route.query.producedList);
      },
      // 是否必填
      mandatoryField() {
        parameterGetByCode({
          code: 'production_plan_code'
        }).then((res) => {
          if (res) {
            this.processingRequired = res.value;
          }
        });
      },

      async getplannedReleaseRequire(code) {
        parameterGetByCode({ code }).then((res) => {
          if (res) {
            this.isReview = res.value == '1' ? true : false;
          }
        });
      },
      // 验证时间是否超期
      changeDate(item, i) {
        console.log(
          this.isTimeAGreaterThanB(item.deliveryTime, item.reqMoldTime)
        );
        if (this.isTimeAGreaterThanB(item.deliveryTime, item.reqMoldTime)) {
          this.$message.error('交付时间大于了要求完成日期');
        }
      },
      isTimeAGreaterThanB(timeA, timeB) {
        return new Date(timeA) > new Date(timeB);
      },

      async getFactoryList() {
        this.factoryList = await getFactoryList();
        this.$nextTick(() => {
          this.form.factoriesId = this.factoryList[0].id;
        });
      },
      async getPlanInfo(id) {
        const data = await getUpdateInfoById(id);
        console.log('wwwwwwwwwwww', data);

        this.form = data;
        if (!data.bomCategoryId || data.bomCategoryId == null) {
          this.form.produceType = '';
          this.selectionRowShow = true;
        } else {
          this.selectionRowShow = false;
        }
        if (this.clientEnvironmentId != 4) {
          this.bomListVersion();
          // this.getPlanRouting();
        }
      },
      async _getInventory() {
        const res = await getInventory(
          this.form.productCode,
          this.form.planType
        );

        this.form.stockCountBase = res;
      },

      getByCodeFn() {
        getByCode('margin_code').then((res) => {
          let _arr = [];
          res.data.map((item) => {
            const key = Object.keys(item)[0];
            const value = item[key];

            _arr.push({ name: key, value: value });
          });
          this.marginList = _arr;
        });
      },

      getPlanRouting() {
        if (this.form.bomCategoryId) {
          bomRoutingList(this.form.bomCategoryId).then((res) => {
            this.routingList = res || [];
            if (res.length) {
              this.$nextTick(() => {
                this.$set(this.form, 'produceRoutingId', res[0].id);
              });

              console.log(this.form.produceRoutingId, '222222222');
            }
          });
        }
      },

      bomListVersion(type) {
        let categoryId = '';
        if (this.form.salesOrders.length) {
          categoryId = this.form.salesOrders[0].categoryId;
        } else if (this.form.categoryId) {
          categoryId = this.form.categoryId;
        } else {
          new Error('缺少产品信息');
        }
        let param = {
          bomType: this.form.produceType || null,
          categoryId: categoryId
        };
        bomListByPlan(param).then((res) => {
          this.bomVersionList = res || [];
          if (res.length) {
            let o = res[0];
            if (type == 'init') {
              let query = this.$route.query;
              let id = query.bomCategoryId ? query.bomCategoryId : o.id;
              this.$set(this.form, 'bomCategoryId', id);
            } else {
              this.$set(this.form, 'bomCategoryId', o.id);
            }
            this.changeBomId();
          }
        });
      },

      changeProduceType(type) {
        if (this.clientEnvironmentId == 4) {
          return false;
        }
        this.form.bomCategoryId = '';
        this.form['bomCategoryName'] = '';
        this.form['bomCategoryVersions'] = '';

        this.bomVersionList = [];

        this.routingList = [];
        this.form.produceRoutingId = '';
        this.form.produceRoutingName = '';
        this.form.produceVersionName = '';
        this.selectionRowShow = false; // ****
        this.bomListVersion(type);
      },

      changeBomId() {
        this.routingList = [];
        this.form.produceRoutingId = '';
        this.form.produceRoutingName = '';
        this.form.produceVersionName = '';

        this.bomVersionList.forEach((f) => {
          if (f.id == this.form.bomCategoryId) {
            this.$set(this.form, 'bomCategoryName', f.name);
            this.$set(this.form, 'bomCategoryVersions', f.versions);
          }
        });

        this.getPlanRouting();
      },

      changeRoute() {
        this.$forceUpdate();
        this.routingList.forEach((f) => {
          if (f.id == this.form.produceRoutingId) {
            this.$set(this.form, 'produceRoutingName', f.name);
            this.$set(this.form, 'produceVersionName', f.version);
          }
        });
      },

      getSaleInfo() {
        let params = JSON.parse(this.$route.query.selection);
        productionToPlan(params).then((res) => {
          console.log(res, '555555555555555555');
          this.form = deepClone(res);
          // if (!this.form.produceType) {
          //   this.form.produceType = 2;
          //   this.bomListVersion();
          // }
          // this.bomListVersion();
          this.form.produceRoutingName =
            res.produceRoutingName || this.$route.query.produceRoutingName;
          this.form.produceRoutingId =
            res.produceRoutingId || this.$route.query.produceRoutingId;
          this.form.factoriesId =
            res.factoriesId || this.$route.query.factoriesId;
          this.form.bomCategoryId =
            res.bomCategoryId || this.$route.query.bomCategoryId;
          this.changeProduceType('init');
          this.changeBomId();
          console.log(this.form.factoriesId, '99999999999999');
          if (this.clientEnvironmentId == '4') {
            if (this.form.salesOrders[0].productName.includes('板材')) {
              this.changeProduct({
                id: '1856970794952372226',
                name: '板材',
                produceVersionName: '板材'
              });
            } else {
              this.changeProduct({
                id: '1857313733642596353',
                name: '砌块',
                produceVersionName: '砌块'
              });
            }
          }
          this.form.salesOrders.map((item, index) => {
            if (this.clientEnvironmentId == '4') {
              this.tableHandleKeyUp(item, '', item.lackNum, 'sum');
            } else {
              item.planProductNum = item.lackNum;
              item.requiredFormingNum = item.lackNum;
            }
            item.slottingType = item.slottingType && item.slottingType + '';
            item.priority = index + 1;

            item.reqMoldTime = dayjs(
              new Date(item.deliveryTime).getTime() - 3600 * 1000 * 24 * 10
            ).format('YYYY-MM-DD');
          });
          if (this.form.salesOrders.every((itm) => itm.orderType == 2)) {
            this.form.planType = 2;
          } else if (this.form.salesOrders.every((itm) => itm.orderType == 1)) {
            this.form.planType = 1;
          } else {
            this.form.planType = 3;
          }
          this._getInventory();
        });
        this.$forceUpdate();
      },

      itemChange() {
        this.form.salesOrders.map((item, index) => {
          this.$set(
            item,
            'requiredFormingNum',
            item.planProductNum * (this.form.marginCoefficient || 1)
          );
        });
      },

      factoriesIdFn(e) {
        this.$forceUpdate();
      },

      toInt(planProductNum) {
        return planProductNum * (this.form.marginCoefficient || 1);
      },

      cancel() {
        const key = getRouteTabKey();
        // this.$router.go(-1);
        removePageTab({ key });

        this.$emit('cancel');
      },
      toSubmit() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            // this.mapList();

            this.$refs.submitRefs.open();
          }
        });
      },
      // // 对比日期，计算要求生产重量
      // mapList() {
      //   var _sumOrderWeight = 0;
      //   var requiredFormingNum = 0;
      //   var productNum = 0;
      //   this.form.salesOrders.map((item, index) => {
      //     requiredFormingNum = Number(requiredFormingNum) + Number(item.requiredFormingNum);

      //     if (this.form.weightUnit == 'G' || this.form.weightUnit == 'g' || this.form.weightUnit == '克') {
      //       this.form.newWeightUnit = 'kg';
      //       _sumOrderWeight = (this.form.salesOrders[0].requiredFormingNum * Number(this.form.salesOrders[0].productUnitWeight || 1)) / 1000;
      //     } else {
      //       this.form.newWeightUnit = this.form.weightUnit;
      //       _sumOrderWeight = (this.form.salesOrders[0].requiredFormingNum * Number(this.form.salesOrders[0].productUnitWeight || 1));
      //     }

      //     productNum += Number(item.planProductNum);
      //   });
      //   this.form.productNum = productNum;
      //   this.form.productUnitWeight = this.form.salesOrders[0]?.productUnitWeight;
      //   this.form.newSumOrderWeight = _sumOrderWeight.toFixed(2);
      //   this.form.requiredFormingNum = requiredFormingNum;
      //   const collection = deepClone(this.form.salesOrders);
      //   const sortedCollection = collection.sort(
      //     (a, b) => new Date(b.reqMoldTime) - new Date(a.reqMoldTime)
      //   );

      //   let latestData = {};
      //   for (let i = 0; i < sortedCollection.length; i++) {
      //     const data = sortedCollection[i];
      //     if (
      //       !latestData.reqMoldTime ||
      //       new Date(data.reqMoldTime) >= new Date(latestData.reqMoldTime)
      //     ) {
      //       latestData = data;
      //     }
      //   }
      //   this.form.reqMoldTime = latestData.reqMoldTime;

      //   console.log(this.form, '1111111111111');

      // },

      sortTop(row) {
        row.priority = Number(row.priority) + 1;
        this.priorityChange(row);
      },
      sortBottom(row) {
        if (row.priority <= 1) {
          return;
        }
        row.priority = Number(row.priority) - 1;
        this.priorityChange(row);
      },

      priorityChange(row) {
        if (row.priority > 10) {
          row.priority = 10; // 如果大于 10，则设置为 10
        } else if (row.priority < 0) {
          row.priority = 0; // 如果小于 0，则设置为 0
        }

        this.priorityFn(row);
      },

      priorityFn: debounce(function (row) {}, 800),

      // 删除产品
      handleDeleteItem(index) {
        this.form.salesOrders.splice(index, 1);
      },
      addEquipment() {
        this.$refs.additionalRefs.open(this.form.planType);
      },
      openVersion() {
        this.$refs.versionRefs.open();
      },
      changeProduct(data) {
        this.$set(this.form, 'produceRoutingName', data.name);
        this.$set(this.form, 'produceRoutingId', data.id);
        this.$set(this.form, 'produceVersionName', data.produceVersionName);
      },
      // 表格：模数、数量(方)、块数输入框 输入事件
      tableHandleKeyUp(row, index, e, name) {
        if (row.specification && this.clientEnvironmentId == '4') {
          let modelArr = row.specification.split('*');
          let modelLong = modelArr[0]; // model规格长度
          let modeWide = modelArr[1]; // model规格宽度
          let modeHight = modelArr[2].substr(0, modelArr[2].indexOf('cm')); // model规格高度
          modeHight = Number(modeHight);
          if (name === 'moCount') {
            // 模数
            row.moCount = e;
            // 计算块数的公式：
            // (一模6米长度 / model规格长度) * (一模1.2米宽度 / model规格宽度) = 每一模的块数
            // 每一模的块数*模数moCount = 总块数
            if (row.productName.includes('板材')) {
              row.blockCount =
                Math.floor(600 / modelLong) *
                Math.floor(120 / modeHight) *
                Math.floor(60 / modeWide) *
                row.moCount;
            } else if (row.productName.includes('砌块')) {
              let modelLongFixed = (600 / modelLong).toFixed(2);
              modelLongFixed = modelLongFixed.substring(
                0,
                modelLongFixed.length - 1
              );
              let modeWideFixed = (120 / modeWide).toFixed(2);
              modeWideFixed = modeWideFixed.substring(
                0,
                modeWideFixed.length - 1
              );
              let modeHightFixed = (60 / modeHight).toFixed(2);
              modeHightFixed = modeHightFixed.substring(
                0,
                modeHightFixed.length - 1
              );
              row.blockCount =
                Math.floor(modelLongFixed * modeWideFixed * modeHightFixed) *
                row.moCount;
            }

            row.planProductNum =
              Number((modelLong * modeWide * modeHight) / 1000000).toFixed(5) *
              row.blockCount;
          } else if (name === 'sum') {
            //方数
            row.planProductNum = e;

            row.blockCount = Math.floor(
              e / ((modelLong * modeWide * modeHight) / 1000000)
            );
            if (row.productName.includes('板材')) {
              row.moCount = Math.ceil(
                row.blockCount /
                  (Math.floor(600 / modelLong) *
                    Math.floor(120 / modeHight) *
                    Math.floor(60 / modeWide))
              );
            } else if (row.productName.includes('砌块')) {
              row.moCount = Math.ceil(
                row.blockCount /
                  Math.floor(
                    (600 / modelLong) * (120 / modeHight) * (60 / modeWide)
                  )
              );
            }
          } else if (name === 'blockCount') {
            //块数
            row.blockCount = e;

            if (row.productName.includes('板材')) {
              row.moCount = Math.ceil(
                row.blockCount /
                  (Math.floor(600 / modelLong) *
                    Math.floor(120 / modeHight) *
                    Math.floor(60 / modeWide))
              );
            } else if (row.productName.includes('砌块')) {
              row.moCount = Math.ceil(
                row.blockCount /
                  Math.floor(
                    (600 / modelLong) * (120 / modeHight) * (60 / modeWide)
                  )
              );
            }

            row.planProductNum =
              (Number(e) * modelLong * modeWide * modeHight) / 1000000;
          }
        }

        row.requiredFormingNum = Number(
          row.planProductNum * (this.form.marginCoefficient || 1)
        ).toFixed(5);
      },
      confirmChoose(list) {
        // 取出在弹窗中选中并且不在表格中的数据
        const result = list.filter(
          (i) => this.form.salesOrders.findIndex((p) => p.id === i.id) === -1
        );
        // 取出在表格中并且不在弹窗中选中的数据 即取消选中的数据
        const del = this.form.salesOrders.filter(
          (i) => list.findIndex((p) => p.id === i.id) === -1
        );
        for (let i = this.form.salesOrders.length - 1; i >= 0; i--) {
          for (let j in del) {
            if (this.form.salesOrders[i].id === del[j].id) {
              this.form.salesOrders.splice(i, 1);
            }
          }
        }
        let priority =
          this.form.salesOrders[this.form.salesOrders.length - 1]?.priority ||
          0;
        this.form.salesOrders = this.form.salesOrders.concat(
          result.map((item, index) => {
            item.priority = ++priority;

            item.planProductNum = item.lackNum;
            item.requiredFormingNum = item.lackNum;
            item.reqMoldTime = dayjs(
              new Date(item.deliveryTime).getTime() - 3600 * 1000 * 24 * 10
            ).format('YYYY-MM-DD');
            return item;
          })
        );
        this.changeData();
      },
      changeData() {
        var planProductNum = 0;
        var productWeight = 0;

        this.form.salesOrders.map((item, index) => {
          item.priority = index + 1;
          planProductNum = planProductNum + item.requiredFormingNum;
          productWeight = productWeight + Number(item.productSumWeight);
        });
        this.$set(this.form, 'codeNum', this.form.salesOrders.length);
        this.$set(this.form, 'contractNum', planProductNum);
        this.$set(this.form, 'sumOrderWeight', productWeight.toFixed(2));
      },

      async publishData(type) {
        const key = getRouteTabKey();
        let params = deepClone(this.form);
        params.categoryId = params.salesOrders[0]?.categoryId;
        if (this.$route.query.type != 'edit') {
          delete params.id;
        }

        if (type === 2) {
          const titleText = this.isReview
            ? '是否发起流程'
            : '发布工单后不可撤回，确定发布吗？';

          const title = this.isReview ? '流程确认' : '发布确认';

          const text = this.isReview ? '流程发布中...' : '工单发布中...';

          this.$confirm(titleText, title).then(async () => {
            const loading = this.$loading({
              lock: true,
              fullscreen: true,
              text
            });
            try {
              const code = await getCode('product_order_code');
              const data = {
                productionPlan: params,
                workOrder: {
                  productionPlanCode: params.code,
                  code: code,
                  // formingNum: params.contractNum,
                  formingNum: this.form.requiredFormingNum,
                  formingWeight: params.sumOrderWeight,
                  produceRoutingId: params.produceRoutingId,
                  status: 4,
                  model: params.model,
                  brandNo: params.brandNo,
                  categoryId: params.categoryId,
                  productCode: params.productCode,
                  productName: params.productName,

                  newWeightUnit: this.form.newWeightUnit,
                  newSumOrderWeight: this.form.newSumOrderWeight
                }
              };
              if (this.$route.query.type == 'edit') {
                data.workOrder.productionPlanId = params.id;
              }
              console.log(data);
              const URL = this.isReview ? planIsReview : releaseSave;
              await URL(data)
                // await releaseSave(data)
                .then((res) => {
                  if (res === 1) {
                    if (this.isReview) {
                      this.$message.success('流程已发布！');
                      this.$router.push({
                        path: '/productionPlan'
                      });
                    } else {
                      this.$message.success('工单已发布！');
                      this.$router.push({
                        path: '/workOrder'
                      });
                    }
                  } else {
                    if (this.isReview) {
                      this.$message.success('流程已发布！');
                      this.$router.push({
                        path: '/productionPlan'
                      });
                    } else {
                      this.$confirm(
                        '生产计划创建成功，但工单发布失败。请前往【生产计划】列表【重新发布】工单',
                        '提示',
                        {
                          confirmButtonText: '返回',
                          cancelButtonText: '立即前往',
                          type: 'warning'
                        }
                      )
                        .then(() => {
                          this.$router.push({
                            path: '/productionPlan'
                          });
                        })
                        .catch(() => {
                          this.$router.go(-1);
                        });
                    }
                  }
                  removePageTab({ key });
                })
                .catch(() => {
                  this.$message.error('发布失败，请重新发布！');
                });
            } catch (error) {}

            loading.close();
          });
        } else {
          let request =
            this.$route.query.type == 'edit'
              ? updateSaleToPlan
              : saveSaleToPlan;

          request(params)
            .then(async (res) => {
              // 提交
              this.$router.push({
                path: '/productionPlan'
              });
              removePageTab({ key });
            })
            .catch(() => {
              this.$message.error('提交失败，请重新提交！');
            });
        }
      },
      // 打开工艺路线
      openDialog() {
        // this.selectIndex = index;
        this.$refs.processRouteRef.open();
      },
      // 选择工艺路线
      changeParent(item) {
        this.routingList = [];
        this.bomVersionList = [];
        this.$set(this.form, 'bomCategoryId', null);
        this.$set(this.form, 'model', '');
        this.$set(this.form, 'produceType', '');
        this.$set(this.form, 'produceRoutingName', item.name);
        this.$set(this.form, 'produceRoutingId', item.id);
        this.form.bomCategoryName = '';
        this.form.bomCategoryVersions = '';
        this.selectionRowShow = true;
      }
    }
  };
</script>
<style lang="scss" scoped>
  .ele-body {
    background: #fff;
  }

  .body-title {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .title-left {
    font-size: 20px;
    color: #333;
  }

  .formbox {
    margin: 20px auto;
  }

  .row-intro {
    border-bottom: 1px dashed #ccc;
    margin-bottom: 20px;
  }

  .add-product {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    font-size: 30px;
    color: #1890ff;
    margin: 10px 0;
    cursor: pointer;
  }

  .table-item {
    margin-bottom: 0;
  }

  .header_required {
    position: relative;
  }

  .header_required:before {
    content: '*';
    color: #f56c6c;
    position: absolute;
    top: 11px;
    left: 15px;
  }
</style>
