<template>
  <div class="ele-body">
    <salesToProductionNewTwo
      @cancel="cancel"
      :objData="objData"
      v-if="isNewShow && startRequest"
    ></salesToProductionNewTwo>
    <salesToProductionNew
      @cancel="cancel"
      :formData="form"
      v-if="!isNewShow && startRequest"
    ></salesToProductionNew>
  </div>
</template>
<script>
  import AdditionalOrder from './components/AdditionalOrder.vue';
  import PlanSubmit from './components/plan-submit.vue';
  import ProductionVersion from '@/components/CreatePlan/ProductionVersion2.vue';
  import salesToProductionNewTwo from './salesToProductionNewTwo.vue';
  import salesToProductionNew from './salesToProductionNew.vue';
  import {
    productionToPlan,
    saveSaleToPlan,
    updateSaleToPlan,
    releaseSave,
    getInventory,
    getUpdateInfoById,
    bomRoutingList,
    bomListByPlan,
    getFactoryList
  } from '@/api/saleOrder';

  import { getByCode } from '@/api/system/dictionary-data';

  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';
  export default {
    mixins: [dictMixins],
    components: {
      salesToProductionNewTwo,
      AdditionalOrder,
      ProductionVersion,
      salesToProductionNew,
      PlanSubmit
    },
    data() {
      return {
        type: this.$route.query.type,
        id: this.$route.query.id,
        objData: {},
        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)' }, //2 待确认
          { code: 3, name: '装配(ABOM)' }
        ],
        isNewShow: true,
        form: {
          planType: 1,
          produceRoutingId: '',
          stockCountBase: '',
          salesOrders: [],
          produceRoutingName: '',
          marginCoefficient: '1.0',
          batchNo: null,
          produceType: '',
          bomCategoryId: '',
          factoriesId: ''
        },

        marginList: [],
        startRequest: false,
        bomVersionList: [],
        routingList: [],
        factoryList: [],

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

        //   produceType: [
        //     { required: true, message: '请选择生产类型', trigger: 'blur' }
        //   ],
        //   bomCategoryId: [
        //     { required: true, message: '请选择BOM版本', trigger: 'blur' }
        //   ],
        //   factoriesId: [
        //     { required: true, message: '请选择所属工厂', trigger: 'change' }
        //   ]
        // },
        // selection: [],
        loading: false
      };
    },
    computed: {
      clientEnvironmentId() {
        return this.$store.state.user.info.clientEnvironmentId;
      },
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      }
    },
    created() {
      console.log(111111111111111111)
      // this.requestDict('按单按库');
      // this.requestDict('订单类型');
      // this.requestDict('交付要求');

      this.getByCodeFn();
      this.getFactoryList();

      this.objData = {
        id: this.id,
        type: this.type
      };
      console.log(this.type,'type')
      if (this.type == 'edit') {
        this.getPlanInfo(this.$route.query.id);
      } else {
        this.getSaleInfo();
      }
    },

    methods: {
      // 验证时间是否超期
      changeDate(item, i) {
        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();
      },
      async getPlanInfo(id) {
        try {
          this.startRequest = false;
          const data = await getUpdateInfoById(id);
          this.startRequest = true;
          this.form = data;
          if (!data.bomCategoryId || data.bomCategoryId == null) {
            console.log(1111111113333333333333)
            this.form.produceType = '';
            // this.selectionRowShow = true;
          } else {
            // this.selectionRowShow = false;
          }
          if (this.form.salesOrders.length) {
            // console.log(1);
            this.isNewShow = true;
          } else {
            this.isNewShow = false;
          }

          if (this.clientEnvironmentId != 4) {
            // this.bomListVersion()
            // this.getPlanRouting()
          }
        } catch (err) {
          this.startRequest = true;
        }
      },
      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 || [];
          });
        }
      },

      bomListVersion() {
        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 || [];
        });
      },

      changeProduceType() {
        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.bomListVersion();
      },

      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);
        this.startRequest = false;
        productionToPlan(params)
          .then((res) => {
            this.startRequest = true;
            this.form = deepClone(res);
            if (!this.form.produceType) {
              this.form.produceType = 2;
              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;
            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();
          })
          .catch((err) => {
            this.startRequest = true;
          });
        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 });
      },
      toSubmit() {
        if (!this.form.factoriesId)
          return this.$message.warning('请选择所属工厂');

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

      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) {
          this.$confirm('发布工单后不可撤回，确定发布吗？', '发布确认').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;
                }
                await releaseSave(data)
                  .then((res) => {
                    if (res === 1) {
                      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('提交失败，请重新提交！');
            });
        }
      }
    }
  };
</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;
  }
</style>
