<template>
  <ele-modal
    width="80vw"
    :visible.sync="visible"
    v-if="visible"
    :close-on-click-modal="false"
    row-key="code"
    custom-class="ele-dialog-form"
    :title="'计划分解'"
    :maxable="true"
    @close="cancel"
  >
    <div class="form-wrapper">
      <el-form :model="requestData" label-width="0" :show-message="false">
        <el-descriptions title="" :column="3" border>
          <el-descriptions-item label="计划编号">
            {{ formData.code }}</el-descriptions-item
          >

          <el-descriptions-item label="产品编码">{{
            formData.productCode
          }}</el-descriptions-item>

          <el-descriptions-item label="产品名称">{{
            formData.productName
          }}</el-descriptions-item>

          <el-descriptions-item label="牌号|型号">
            {{ formData.brandNo }}|{{ formData.model }}</el-descriptions-item
          >

          <el-descriptions-item label="批次号">{{
            formData.batchNo
          }}</el-descriptions-item>

          <el-descriptions-item label="工艺路线">{{
            formData.produceRoutingName
          }}</el-descriptions-item>

          <el-descriptions-item label="要求生产数量">{{
            formData.requiredFormingNum
          }}</el-descriptions-item>
          <el-descriptions-item label="要求完成日期">{{
            formData.reqMoldTime
          }}</el-descriptions-item>

          <el-descriptions-item label="生产类型" class="produceType">
            <el-select v-model="formData.produceType" @change="getBomList">
              <el-option
                v-for="item of producedList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </el-descriptions-item>
        </el-descriptions>
        <headerTitle title="BOM信息" class="mt20"> </headerTitle>
        <!--      @update:selection="handleSelectionChange" -->
        <ele-pro-table
          ref="table"
          :needPage="false"
          :columns="columns"
          :datasource="bomList"
          :selection.sync="selection"
          tool-class="ele-toolbar-actions"
          max-height="360px"
          @select-all="selectAll"
          @select="select"
        >
          <template v-slot:toolbar>
            <div class="toolbar_box">
              <div
                ><span>基本数量</span>
                <el-input
                  placeholder="请输入"
                  v-model.number="baseCount"
                  disabled
                >
                </el-input>
                <DictSelection dictName="计量单位" v-model="unit" disabled
              /></div>
            </div>
          </template>
        </ele-pro-table>

        <headerTitle title="计划列表" class="mt20"> </headerTitle>

        <ele-pro-table
          ref="table2"
          :needPage="false"
          :columns="jsColumns"
          :datasource="jhList"
          tool-class="ele-toolbar-actions"
          max-height="360px"
        >
          <template v-slot:toolbar>
            <div class="toolbar_box">
              <el-button type="primary" size="mini" @click="handleAdd"
                >新增</el-button
              >
            </div>
          </template>
          <template v-slot:produceRoutingId="{ row }">
            <el-select
              v-model="row.produceRoutingId"
              filterable
              size="mini"
              @change="(e) => selectRout(e, row)"
            >
              <el-option
                v-for="item of routingList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </template>
          <template v-slot:startTime="{ row }">
            <el-date-picker
              class="w100"
              v-model="row.startTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="开始时间"
              @change="handleStartTimeChange(row)"
            ></el-date-picker>
          </template>
          <template v-slot:endTime="{ row }">
            <el-date-picker
              class="w100"
              v-model="row.endTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              @change="handleEndTimeChange(row)"
              placeholder="完成时间"
            ></el-date-picker>
          </template>
          <template v-slot:requiredFormingNum="{ row }">
            <el-input
              v-if="row.resourceType"
              size="mini"
              type="number"
              v-model="row.requiredFormingNum"
              @input="(e) => handleQuantityInput(e, row)"
            ></el-input>
            <span v-else>{{ row.requiredFormingNum }}</span>
          </template>
          <template v-slot:action="{ row, $index }">
            <el-popconfirm
              class="ele-action"
              title="确定要删除这条数据吗？"
              @confirm="removeRow(row, $index)"
            >
              <template v-slot:reference>
                <el-link type="danger" :underline="false" icon="el-icon-delete">
                  删除
                </el-link>
              </template>
            </el-popconfirm>
          </template>
        </ele-pro-table>
      </el-form>
    </div>
    <div slot="footer">
      <el-button plain @click="cancel">取消</el-button>
      <el-button type="primary" @click="confirm">确定</el-button>
    </div>

    <EquipmentDialog ref="equipmentRefs" @choose="choose"></EquipmentDialog>
  </ele-modal>
</template>

<script>
  import { deepClone } from '@/utils';
  import { getBom, batchSave } from '@/api/productionPlan/index.js';
  import { routeList } from '@/api/saleOrder';
  import EquipmentDialog from './EquipmentDialog.vue';
  import { start } from 'nprogress';

  export default {
    components: {
      EquipmentDialog
    },
    data() {
      return {
        visible: false,
        formData: {},
        requestData: {},
        bomList: [],
        baseCount: '',
        unit: '',
        selection: [],
        jhList: [],
        rules: {},
        producedList: [
          // { code: 2, name: '加工(MBOM)' },
          // { code: 3, name: '装配(ABOM)' }
          { code: 1, name: 'PBOM' },
          { code: 2, name: 'MBOM' },
          { code: 3, name: 'ABOM' }
        ],
        routingList: [],
        columns: [
          {
            columnKey: 'selection',
            type: 'selection',
            width: 45,
            align: 'center'
          },
          {
            prop: 'code',
            label: 'BOM编码',
            showOverflowTooltip: true
          },
          {
            prop: 'productCode',
            label: '编码',
            showOverflowTooltip: true
          },
          {
            prop: 'name',
            label: '名称',
            showOverflowTooltip: true
          },

          {
            prop: 'dosage',
            label: '用量',
            showOverflowTooltip: true
          },

          {
            prop: 'unit',
            label: '计量单位',
            showOverflowTooltip: true
          },

          {
            prop: 'brandNo',
            label: '牌号',
            align: 'center',
            showOverflowTooltip: true
          },

          {
            prop: 'specification',
            label: '规格',
            align: 'center',
            minWidth: 150,

            showOverflowTooltip: true
          },
          {
            prop: 'model',
            label: '型号',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'versions',
            label: '版本',
            formatter: (row) => {
              if (row.versions) {
                return `V${row.versions}.0`;
              }
              return '';
            }
          },
          {
            prop: 'status ',
            label: '状态',
            formatter: (row) => {
              return this.statusOpt[+row.status];
            }
          },
          {
            prop: 'createName',
            label: '创建人',
            showOverflowTooltip: true
          },
          {
            prop: 'createTime',
            label: '创建日期',
            showOverflowTooltip: true
          }
        ],
        statusOpt: {
          '': '全部',
          0: '已停用',
          1: '已发布'
        },
        jsColumns: [
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center'
          },
          {
            prop: 'productCode',
            label: '编码',
            align: 'center',
            minWidth: 140
          },
          {
            prop: 'productName',
            label: '名称',
            align: 'center',
            minWidth: 140
          },
          {
            prop: 'brandNo',
            label: '牌号',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'specification',
            label: '规格',
            align: 'center',
            minWidth: 150,
            showOverflowTooltip: true
          },
          {
            prop: 'model',
            label: '型号',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            slot: 'startTime',
            prop: 'startTime',
            label: '计划开始时间',
            align: 'center',
            minWidth: 180
          },
          {
            slot: 'endTime',
            prop: 'endTime',
            label: '计划完成时间',
            align: 'center',
            minWidth: 180
          },
          {
            prop: 'produceRoutingId',
            slot: 'produceRoutingId',
            label: '工艺路线',
            align: 'center',
            minWidth: 120
          },
          {
            prop: 'requiredFormingNum',
            label: '要求生产数量',
            align: 'center',
            slot: 'requiredFormingNum',
            width: 130
          },
          {
            prop: 'unit',
            label: '计量单位',
            showOverflowTooltip: true,
            align: 'center',
            width: 100
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 90,
            align: 'center',
            fixed: 'right',
            slot: 'action'
          }
        ],
        // bom信息map数据存储
        bomListMap: {}
      };
    },
    methods: {
      open(row) {
        this.unit = row.measuringUnit;
        this.formData = deepClone(row);
        this.getBomList();
        this.getRouteListFn();
      },

      // 全选/取消全选
      selectAll(selection) {
        // 说明是全选
        if (selection.length > 0) {
          this.bomList.forEach((el) => {
            this.bomListMap[el.id] = true;
            this.handleSelectionChange(el);
          });
        } else {
          // 取消全选
          this.bomList.forEach((el) => {
            delete this.bomListMap[el.id];
            this.deleteJhData(el.id);
          });
        }
      },

      // 勾选 取消勾选
      select(selection, row) {
        // 存在说明已勾选
        if (this.bomListMap[row.id]) {
          delete this.bomListMap[row.id];
          this.deleteJhData(row.id);
        } else {
          this.bomListMap[row.id] = true;
          this.handleSelectionChange(row);
        }
      },
      // 计划列表数据 BOM信息删除
      deleteJhData(id) {
        let index = this.jhList.findIndex((el) => el.id === id);
        if (index != -1) {
          this.jhList.splice(index, 1);
        }
      },
      // 计划列表数据 BOM信息添加
      handleSelectionChange(m) {
        for (let i = 0; i < this.jhList.length; i++) {
          let item = this.jhList[i];
          if (item.id == m.id) {
            return;
          }
        }
        let row = {};
        if (
          m.processRoute &&
          m.processRoute.list &&
          m.processRoute.list.length > 0
        ) {
          row = m.processRoute.list[0];
        }
        let _num =
          ((this.formData.requiredFormingNum || 0) / (this.baseCount || 0)) *
          m.dosage;
        // _num = _num.toFixed(3);
        _num = this.formattedNum(_num);
        let data = {
          id: m.id,
          categoryId: m.categoryId,
          productCode: m.productCode,
          productName: m.name,
          brandNo: m.brandNo,
          specification: m.specification,
          model: m.model,
          produceRoutingId: row.id || '',
          produceRoutingName: row.name || '',
          requiredFormingNum: _num,
          productUnitWeight: m.productUnitWeight,
          startTime: this.formData.startTime || '',
          endTime: this.formData.endTime || '',
          unit: this.unit,
          resourceType: 0
        };
        this.jhList.push(data);
        // this.jhList = _arr;
      },
      // 数量正则
      handleQuantityInput(e, row) {
        // 过滤非数字和非小数点字符（包括负号）
        let value = e.replace(/[^\d.]/g, '');
        // 限制只能有一个小数点
        const dotCount = (value.match(/\./g) || []).length;
        if (dotCount > 1) {
          value = value.slice(0, value.lastIndexOf('.'));
        }
        // 限制不能以小数点开头
        if (value.startsWith('.')) {
          value = '0' + value;
        }
        // 更新绑定值
        row.requiredFormingNum = value;
      },
      // 格式化后的结果
      formattedNum(num) {
        // 检查是否为整数（小数部分为0）
        if (Number.isInteger(num)) {
          return num; // 整数直接返回
        } else {
          // 保留小数点后有效数字（可根据需求调整保留位数）
          return num.toFixed(3);
        }
      },
      // 删除计划信息
      removeRow(row, index) {
        // 如果删除的是当前列表BOM信息的数据 就将它的勾选去掉
        let data = this.bomList.find((el) => el.id == row.id);
        if (data && data.id) {
          this.$refs.table.toggleRowSelection(data);
        }

        // 删除对应的存储数据
        if (this.bomListMap[row.id]) {
          delete this.bomListMap[row.id];
        }
        this.jhList.splice(index, 1);
      },
      // 【结束时间变化时】触发
      handleEndTimeChange(row) {
        this.checkEndTimeValid(row);
      },
      // 【开始时间变化时】触发
      handleStartTimeChange(row) {
        this.checkEndTimeValid(row);
      },
      // 时间校验
      checkEndTimeValid(row) {
        const { startTime: start, endTime: end } = row;
        // if (!start || !end) return; // 开始/结束时间未填，跳过
        const startTime = new Date(start); // 开始时间
        const endTime = new Date(end); // 结束时间
        if (endTime < startTime) {
          row.endTime = new Date(startTime); // 修正为开始时间
          this.$message.info('结束时间不能早于开始时间，已自动设为开始时间');
        }
      },
      getBomList() {
        let params = {
          id: this.formData.id,
          categoryId: this.formData.categoryId,
          bomType: this.formData.produceType,
          pageNum: 1,
          size: -1
        };
        getBom(params).then((res) => {
          this.bomList = res?.bomList || [];
          let ids = Object.keys(this.bomListMap);
          if (ids.length > 0) {
            this.checkBoxData();
          }
          (this.baseCount = res.baseCount),
            // (this.unit = res.unit),
            (this.visible = true);
        });
      },

      // 数据回显勾选
      checkBoxData() {
        let arr = Object.keys(this.bomListMap);
        setTimeout(() => {
          if (arr.length == 0) {
            this.$refs.table.clearSelection();
            return;
          }
          this.bomList.forEach((row) => {
            if (this.bomListMap[row.id]) {
              this.$refs.table.toggleRowSelection(row);
            }
          });
        }, 10);
      },

      // 选择工艺路线
      selectRout(e, row) {
        let data = this.routingList.find((el) => el.id == e);
        this.$set(row, 'produceRoutingName', data.name);
      },

      handleAdd() {
        let ids = [];
        ids = this.jhList.map((m) => m.id);
        // 打开设备选择弹窗
        this.$refs.equipmentRefs.open(ids);
      },

      choose(list) {
        let _list = [];

        _list = list.map((m) => {
          return {
            id: m.id,
            categoryId: m.id,
            productCode: m.code,
            productName: m.name,
            brandNo: m.brandNo,
            specification: m.specification,
            model: m.model,
            produceRoutingId: '',
            produceRoutingName: '',
            requiredFormingNum: '',
            productUnitWeight: m.productUnitWeight,
            unit: this.unit,
            startTime: this.formData.startTime || '',
            endTime: this.formData.endTime || '',
            resourceType: 1
          };
        });

        this.jhList.push(..._list);
      },

      cancel() {
        this.formData = {};
        this.jhList = [];
        this.visible = false;
        this.bomListMap = {};
      },

      getRouteListFn() {
        let params = {
          pageNum: 1,
          size: -1
        };
        routeList(params).then((res) => {
          this.routingList = res?.list || [];
        });
      },

      confirm() {
        let bol = this.jhList.every((m) => m.produceRoutingId);
        if (!bol) {
          return this.$message.warning('请选择工艺路线');
        }

        let bol2 = this.jhList.every((m) => m.requiredFormingNum);
        if (!bol2) {
          return this.$message.warning('请填写生产数量');
        }
        // 检查是否存在 requiredFormingNum 为 0 的元素
        const hasZeroNum = this.jhList.some((item) => {
          // 确保元素有 requiredFormingNum 属性，且值为 0
          return item.requiredFormingNum == 0;
        });
        if (hasZeroNum) {
          return this.$message.warning('不能有生产数量为0的数据');
        }

        let param = {
          addPOList: this.jhList,
          produceType: this.formData.produceType,
          id: this.formData.id
        };

        batchSave(param).then((res) => {
          this.$emit('close', true);
          // this.visible = false;
          this.cancel();
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  .mt20 {
    margin-top: 20px;
  }

  .el-form-item {
    margin-bottom: 0 !important;
  }

  .toolbar_box {
    display: flex;
    justify-content: space-between;
    margin-right: 10px;
    > div {
      display: flex;
      align-items: center;
      justify-content: center;
      > span {
        width: 150px;
      }
      > div {
        margin-left: 10px;
      }
    }
  }

  ::v-deep .is-bordered-label {
    background-color: #fff;
  }

  .produceType {
    // background: #e3fbdd;
    // color: #000;
  }
</style>
