<template>
  <div>
    <ele-modal
      width="90vw"
      :visible.sync="visible"
      :close-on-click-modal="false"
      row-key="code"
      custom-class="ele-dialog-form"
      :title="'齐套性检查'"
      :maxable="true"
    >
      <el-form
        label-width="107px"
        :inline="true"
        class="demo-form-inline"
        style="margin-bottom: 16px"
      >
        <el-form-item label="选择日期">
          <!-- <el-date-picker
            v-model="startTime"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            size="large"
            :picker-options="pickerOptions"
          >
          </el-date-picker> -->
          <el-date-picker
            v-model="startTime"
            type="daterange"
            value-format="yyyy-MM-dd"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :clearable="false"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button class="" type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
      <div v-loading="loading">
        <el-form label-width="107px" :model="orderInfo" class="order_form">
          <el-row :gutter="20" type="flex" style="flex-wrap: wrap">
            <el-col :span="6">
              <el-form-item label="销售单号:">
                <el-input readonly v-model="orderInfo.code"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="行号:">
                <el-input readonly v-model="orderInfo.lineNumber"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="名称:">
                <el-input readonly v-model="orderInfo.productName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="规格:">
                <el-input readonly v-model="orderInfo.specification"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="编码:">
                <el-input readonly v-model="orderInfo.productCode"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="型号:">
                <el-input readonly v-model="orderInfo.model"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="订单数量:">
                <el-input readonly v-model="orderInfo.contractNum"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="produceType == 1">
              <el-form-item label="未发总数:">
                <el-input
                  readonly
                  v-model="kitComInfo.totalUnshippedQuantity"
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="库存数量:">
                <el-input
                  readonly
                  v-model="kitComInfo.inventoryQuantity"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="produceType == 1">
              <el-form-item label="在制总数:">
                <el-input
                  readonly
                  v-model="kitComInfo.totalNumberProduction"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="produceType == 1">
              <el-form-item label="最终缺料数量:">
                <el-input
                  readonly
                  v-model="kitComInfo.finalFilledShortCount"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="最终状态:">
                <el-input
                  :class="
                    kitComInfo.finalFilledShortState == '缺料'
                      ? 'statusRed'
                      : 'statusGreen'
                  "
                  readonly
                  v-model="kitComInfo.finalFilledShortState"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="form-wrapper">
          <div
            class="left_tree"
            v-show="leftShow"
            :style="{ width: leftWidth }"
          >
            <el-tree
              ref="treeRef"
              :expand-on-click-node="false"
              :data="cardList"
              :props="treeProps"
              node-key="id"
              highlight-current
              @node-click="handleNodeClick"
            ></el-tree>
          </div>
          <div :style="{ width: rightWidth }">
            <div>
              <ele-pro-table
                ref="table"
                :needPage="false"
                :columns="columns"
                key="checkTable"
                :init-load="false"
                :datasource="datasourceList"
                :selection.sync="selection"
              >
                <template v-slot:default>
                  <div class="tool">
                    <div class="tool_l">
                      <el-button
                        v-if="produceType == 2"
                        type="primary"
                        @click="bulkPurchase"
                        size="medium"
                        >下发采购计划</el-button
                      >
                    </div>
                    <div class="tool_r">
                      <el-form
                        :inline="true"
                        :model="formInline"
                        class="demo-form-inline"
                      >
                        <el-form-item label="BOM类型">
                          <el-select
                            size="medium"
                            v-model="formInline.bomType"
                            placeholder="BOM类型"
                            class="select-type"
                            @change="bomTypeChange"
                          >
                            <el-option
                              v-for="item in bomListType"
                              :key="item.bomType"
                              :label="item.bomName"
                              :value="item.bomType"
                            >
                            </el-option>
                          </el-select>
                        </el-form-item>
                        <el-form-item label="BOM版本">
                          <el-select
                            class="select-type"
                            size="medium"
                            v-model="formInline.bomId"
                            placeholder="BOM版本"
                            @change="bomVChange"
                          >
                            <el-option
                              v-for="item in bomListV"
                              :key="item.bomId"
                              :label="item.versions"
                              :value="item.bomId"
                            >
                            </el-option>
                          </el-select>
                        </el-form-item>
                        <el-form-item label="属性类型" v-if="produceType == 2">
                          <el-select
                            size="medium"
                            v-model="formInline.attributeType"
                            placeholder="属性类型"
                            class="select-type"
                            @change="attributeChange"
                          >
                            <el-option
                              v-for="item in attributeList"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"
                            >
                            </el-option>
                          </el-select>
                        </el-form-item>
                        <el-form-item label="最终状态">
                          <el-select
                            class="select-type"
                            size="medium"
                            v-model="formInline.finalState"
                            placeholder="最终状态"
                            @change="finalChange"
                          >
                            <el-option
                              v-for="item in finalStateList"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"
                            >
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-form>
                    </div>
                  </div>
                </template>
                <!-- 默认按订单 -->
                <template v-slot:toolbar v-if="produceType == 1">
                  <el-form :inline="true">
                    <el-form-item label="定额计算方法:">
                      <el-radio-group
                        v-model="quota_calculation"
                        @change="selectCalculate"
                      >
                        <el-radio :label="1">按订单数量</el-radio>
                        <el-radio :label="2">按缺料数量</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-form>
                </template>
                <template v-slot:toolkit>
                  <el-form :inline="true">
                    <el-form-item label="基本数量">
                      <el-input size="medium" v-model="baseCount" disabled>
                        <template slot="append">{{ baseUnit }}</template>
                      </el-input>
                    </el-form-item>
                  </el-form>
                </template>
                <template v-slot:inventoryQuantity="{ row }">
                  <el-link
                    type="primary"
                    :underline="false"
                    @click="stockDetail(row)"
                  >
                    {{ row.inventoryQuantity }}
                  </el-link>
                </template>
                <template v-slot:inTransitNum="{ row }">
                  <el-link
                    type="primary"
                    :underline="false"
                    @click="currentDetail(row)"
                  >
                    {{ row.inTransitNum }}
                  </el-link>
                </template>
                <template v-slot:inventoryStatusText="{ row }">
                  <div
                    :class="
                      row.inventoryStatusText == '缺料'
                        ? 'statusRed'
                        : 'statusGreen'
                    "
                  >
                    {{ row.inventoryStatusText }}
                  </div>
                </template>
                <template v-slot:inTransitStatusText="{ row }">
                  <div
                    :class="
                      row.inTransitStatusText == '缺料'
                        ? 'statusRed'
                        : 'statusGreen'
                    "
                  >
                    {{ row.inTransitStatusText }}
                  </div>
                </template>
                <template v-slot:finalStateText="{ row }">
                  <div
                    :class="
                      row.finalStateText == '缺料' ? 'statusRed' : 'statusGreen'
                    "
                  >
                    {{ row.finalStateText }}
                  </div>
                </template>
                <!-- <template v-slot:stockColor="{ row }">
                  <div :class="{ statusRed: row.stockStatus == '缺料' }">
                    {{ row.stockStatus }}
                  </div>
                </template>
                <template v-slot:currentColor="{ row }">
                  <div :class="{ statusRed: row.currentStatus == '缺料' }">
                    {{ row.currentStatus }}
                  </div>
                </template>
                <template v-slot:finishColor="{ row }">
                  <div :class="{ statusRed: row.finishStatus == '缺料' }">
                    {{ row.finishStatus }}
                  </div>
                </template>
                <template v-slot:finishCount="{ row }">
                  <div>
                    <div v-if="row.finishCount > 0">{{ row.finishCount }}</div>
                    <div v-else>-</div>
                  </div>
                </template> -->
              </ele-pro-table>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer">
        <el-button plain @click="cancel">取消</el-button>
        <!-- <el-button type="primary" @click="confirm">确定</el-button> -->
      </div>
      <!-- <CreateOrder
        ref="createDialog"
        name="createDialog1"
        :is-add="false"
        v-if="orderShow"
        @refresh="refresh"
      ></CreateOrder> -->
    </ele-modal>

    <stockDetailDialog ref="stockDetailDialog" />
    <currentDetailDialog ref="currentDetailDialog" />
    <purchaseDialog ref="purchaseDialogRef" :orderType="1" @success="success" />
    <!-- <create-order ref="createDialog" /> -->
  </div>
</template>

<script>
  import {
    findBomSalesorderCategoryId,
    findMaterialInfoSalesorder,
    findMaterialInfoByCategory,
    findBomSalesorderCategoryIdV2,
    bomVersionList,
    listBomType,
    getProductKitting
  } from '@/api/productionPlan/index.js';
  import { orderHomogeneityInspect } from '@/api/saleOrder/index.js';
  import stockDetailDialog from '../../productionPlan/components/stockDetailDialog.vue';
  import currentDetailDialog from '../../productionPlan/components/currentDetailDialog.vue';
  import purchaseDialog from '@/views/productionPlan/components/purchaseDialog.vue';
  // import CreateOrder from './create-order.vue';
  // import { findBomCategoryByCategoryId } from '@/api/productionPlan/index';
  // import CreateOrder from '../components/create-order.vue';
  export default {
    components: {
      // CreateOrder,
      stockDetailDialog,
      currentDetailDialog,
      purchaseDialog
    },
    computed: {
      fieldShow() {
        return this.produceType == 1 && this.quota_calculation === 2;
      },
      columns() {
        return [
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            fixed: 'left'
          },
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center',
            slot: 'selection',
            fixed: 'left'
          },
          {
            prop: 'batchNo',
            label: '批次号',
            align: 'center',
            minWidth: 100,
            showOverflowTooltip: true
          },
          {
            prop: 'bomCode',
            label: 'BOM编码',
            align: 'center',
            minWidth: 100,
            showOverflowTooltip: true
          },
          {
            prop: 'code',
            label: '物料编码',
            align: 'center',
            minWidth: 100,
            showOverflowTooltip: true
          },
          {
            prop: 'name',
            label: '物料名称',
            align: 'center',
            minWidth: 100,
            showOverflowTooltip: true
          },
          {
            prop: 'level',
            label: '层级',
            align: 'center',
            minWidth: 50
          },
          {
            prop: 'supplierName',
            label: '供应商',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140
          },
          {
            prop: 'demandQuantity',
            label: '定额数量',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            prop: 'unit',
            label: '单位',
            showOverflowTooltip: true,
            align: 'center',
            width: 60
          },
          {
            prop: 'totalUnshippedQuantity',
            label: '未发总数',
            showOverflowTooltip: true,
            align: 'center',
            show: this.fieldShow
            //   如果按订单状态 的话 隐藏
          },
          {
            prop: 'inventoryQuantity',
            slot: 'inventoryQuantity',
            label: '库存数量',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            prop: 'secureInventory',
            label: '安全库存',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            prop: 'lockQuantity',
            label: '锁库数量',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            slot: 'inventoryStatusText',
            prop: 'inventoryStatusText',
            label: '库存状态',
            align: 'center',
            minWidth: 80
          },
          {
            slot: 'inTransitNum',
            prop: 'inTransitNum',
            label: '在途数量',
            align: 'center',
            minWidth: 80,
            show: this.produceType == 2
          },
          {
            prop: 'inTransitOrdersNum',
            label: '在途已关联数量	',
            align: 'center',
            minWidth: 120,
            show: this.produceType == 2
          },
          {
            slot: 'inTransitStatusText',
            prop: 'inTransitStatusText',
            label: '在途状态',
            align: 'center',
            minWidth: 80,
            show: this.produceType == 2
          },
          {
            prop: 'totalNumberProduction',
            label: '在制总数',
            showOverflowTooltip: true,
            align: 'center',
            show: this.fieldShow
            //   如果按订单状态 的话 隐藏
          },
          {
            prop: 'numberProductionStateText',
            slot: 'numberProductionStateText',
            label: '在制齐套',
            showOverflowTooltip: true,
            align: 'center',
            show: this.fieldShow
            //   如果按订单状态 的话 隐藏
          },
          // {
          //   prop: 'productFinalStateText',
          //   slot: 'productFinalStateText',
          //   label: '成品的最终齐套',
          //   showOverflowTooltip: true,
          //   align: 'center',
          //   minWidth: 160,
          //   show: this.produceType == 1 && this.quota_calculation === 2
          // },
          {
            label: '最终可用数量',
            prop: 'finalAvailableQuantity',
            align: 'center',
            minWidth: 110
          },
          {
            label: '最终缺料数量',
            prop: 'finalShortageQuantity',
            align: 'center',
            minWidth: 120
          },
          {
            label: '下发状态',
            align: 'center',
            minWidth: 90,
            fixed: 'right',
            formatter: (row) => {
              return row.hasIssued ? '已下发' : '未下发';
            }
          },
          {
            slot: 'finalStateText',
            prop: 'finalStateText',
            label: '最终状态',
            align: 'center',
            minWidth: 80,
            fixed: 'right'
          }
        ];
      }
    },
    data() {
      return {
        visible: false,
        kitComInfo: {},
        bomIdList: [],
        requiredFormingNum: 0,
        formInline: {
          finalState: 0,
          attributeType: 2
        },
        finalStateList: [
          {
            label: '全部',
            value: 0
          },
          {
            label: '齐套',
            value: 1
          },
          {
            label: '缺料',
            value: 2
          }
        ],
        loading: false,
        datasourceAllList: [], // 表格物料全部数据
        datasourceList: [], // 表格物料数据
        bomListV: [], // BOM版本
        bomListType: [], // BOM 类型
        form: {
          homogeneityInspect: []
        },
        ids: [],
        leftShow: false,
        leftWidth: '0%',
        rightWidth: '100%',
        cardList: [],
        treeProps: {
          label: 'codeH',
          children: 'children'
        },
        orderInfo: {
          code: '',
          productCode: '',
          productName: '',
          contractNum: '',
          specification: '',
          model: ''
        },
        salesOrderId: '',
        // 来源
        source: 'list',
        bomCode: '',
        produceType: 1,
        selection: [],
        orderShow: false,
        attributeList: [
          {
            value: 'all',
            label: '全部'
          },
          {
            value: 2,
            label: '采购件'
          },
          {
            value: 3,
            label: '外协件'
          }
        ],
        baseCount: '',
        baseUnit: '',
        quota_calculation: 1,
        pickerOptions: {
          // 限制最大可选日期为今天
          disabledDate(time) {
            const today = new Date();
            return time.getTime() > today.getTime();
          }
        },
        startTime: [],
        kitting: false
      };
    },
    watch: {
      leftShow(newVal, oldVal) {
        if (newVal) {
          this.leftWidth = '250px';
          this.rightWidth = 'calc(100% - 260px)';
        } else {
          this.leftWidth = '0';
          this.rightWidth = '100%';
        }
      }
    },
    methods: {
      reload(where) {
        this.$nextTick(() => {
          this.$refs.table.reload({ page: 1, where });
        });
      },
      /* 表格数据源 */
      datasource({ page, limit, where }) {
        return orderHomogeneityInspect({
          pageNum: page,
          size: limit,
          ...where
        });
      },
      // 定额数量
      stockDetail(row) {
        this.$refs.stockDetailDialog.open({ bomCode: row.code });
      },
      // 在途
      currentDetail(row) {
        this.$refs.currentDetailDialog.open({ bomCode: row.code });
      },
      initTime() {
        // 获取当前日期（今天）
        const today = new Date(); // 注意：月份是0-based，8月对应7
        // 计算三个月前的日期
        const threeMonthsAgo = new Date(today);
        threeMonthsAgo.setMonth(today.getMonth() - 3);
        let start = this.formatDate(threeMonthsAgo);
        let end = this.formatDate(today);
        this.startTime = [start, end];
      },
      formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      },
      open(dataList, order, source, produceType) {
        this.clearData();
        this.produceType = produceType;
        this.initTime();
        this.source = source;
        this.visible = true;
        this.cardList = dataList.map((el) => {
          return {
            ...order,
            ...el,
            codeH: el.code ? `${el.code}--${el.lineNumber}` : ''
          };
        });
        if (dataList.length === 1) {
          this.leftShow = false;
        } else {
          this.leftShow = true;
          const firstNodeKey = dataList[0].id;
          this.$nextTick(() => {
            this.$refs.treeRef.setCurrentKey(firstNodeKey);
          });
        }
        this.handleNodeClick(this.cardList[0]);
        // this.visible = true;
        // this.bomIdList = [];
        // if (data) {
        //   if (data.length == 1) {
        //     this.orderInfo = data[0];
        //     this.orderInfo.code = order.code;
        //     console.log(this.orderInfo);
        //     this.leftShow = false;
        //   } else {
        //     this.leftShow = true;
        //   }
        //   let list = [];
        //   for (let item of data) {
        //     list.push({ bomId: item.bomCategoryId, planNum: item.contractNum });
        //   }
        //   this.bomIdList = list;
        //   this.reload({ bomIdList: this.bomIdList });
        // }
      },
      cancel() {
        this.clearData();
        this.visible = false;
      },
      refresh() {
        this.cancel();
        this.orderShow = false;
        this.$emit('reload');
      },
      confirm() {
        this.visible = false;
      },

      async handleNodeClick(data) {
        this.orderInfo = data;
        try {
          await this.getKitting();
          await this.getBomData(data);
        } catch (e) {
          console.log(e, 'eeeeeeeeeeeeeeeeeee');
        }
      },
      async getKitting() {
        let { startTime, endTime } = this.getTimeData();
        let params = {
          categoryId: this.orderInfo.categoryId,
          startTime,
          endTime
        };
        const res = await getProductKitting(params);
        if (res) {
          this.kitComInfo = res;
        }
      },
      selectCalculate(val) {
        this.attributeChange(this.formInline.attributeType);
      },

      // 获取bom 数据
      async getBomData(data) {
        try {
          this.salesOrderId = data.id;
          let params = { categoryId: data.categoryId };
          const res = await listBomType(params);
          if (!res || res.length === 0) return;
          let bomMap = {
            1: 'PBOM',
            2: 'MBOM',
            3: 'ABOM'
          };
          let list = res.map((item) => {
            return {
              bomType: item.bomType,
              id: item.id,
              bomId: item.id,
              bomName: bomMap[item.bomType]
            };
          });
          let bom = list.find((el) => el.bomType == data.produceType);
          let bomType = bom ? bom.bomType : list[0].bomType;
          this.bomListType = list;
          this.formInline.bomType = bomType;
          this.bomTypeChange(bomType, 'init');
        } catch (e) {
          this.$message.error(err.message);
          this.loading = false;
        }
      },
      // 选择BOM类型
      async bomTypeChange(e, type) {
        this.formInline.bomType = e;
        const params = {
          categoryId: this.orderInfo.categoryId,
          bomType: e,
          isTemp: 0
        };
        const res = await bomVersionList(params);
        if (!res || res.length == 0) {
          this.bomListV = [];
          return;
        }
        let list = [];
        res.forEach((el) => {
          if (el.status != 1) return;
          let obj = {
            bomId: el.id,
            id: el.id,
            versions: `V${el.versions}.0`
          };
          list.push(obj);
        });
        this.bomListV = list;
        if (type == 'init') {
          let obj = list.find((el) => el.bomId == this.orderInfo.bomCategoryId);
          let id = obj ? obj.bomId : list[0].bomId;
          this.formInline.bomId = id;
          this.bomVChange(id);
        } else {
          let id = list[0].bomId;
          this.formInline.bomId = id;
          this.bomVChange(id);
        }
      },
      // 选择BOM版本
      async bomVChange(e) {
        this.datasourceList = [];
        this.datasourceAllList = [];
        await this.getMaterialData({ bomId: e }, this.formInline.attributeType);
      },

      // 查询采购价跟外协件两个类型数据
      async dataMerging() {
        if (!this.formInline.bomId) {
          return;
        }
        let kitting = this.quota_calculation == 1 ? false : true;
        let { startTime, endTime } = this.getTimeData();
        let params1 = {
          salesOrderId: this.salesOrderId,
          bomVersionId: this.formInline.bomId,
          produceType: 2,
          startTime,
          endTime,
          kitting: kitting
        };
        let params2 = {
          salesOrderId: this.salesOrderId,
          bomVersionId: this.formInline.bomId,
          produceType: 3,
          startTime,
          endTime,
          kitting: kitting
        };
        this.loading = true;
        try {
          // 直接调用接口函数，因为其返回Promise，无需额外包装
          let p1 = findMaterialInfoSalesorder(params1);
          let p2 = findMaterialInfoSalesorder(params2);
          // 使用Promise.all并行执行多个Promise
          let results = await Promise.all([p1, p2]);
          this.loading = false;
          // 这里可以继续对results做后续处理，比如解构等
          const [result1, result2] = results;
          // 示例：可以接着处理result1和result2，比如合并数据等
          const mergeData = this.handleMergedData(result1, result2);
          this.resultProcess(mergeData);
        } catch (error) {
          this.loading = false;
          console.error('接口请求出错:', error);
        }
      },
      handleMergedData(result1, result2) {
        // 处理合并后的数据逻辑
        return [...result1, ...result2];
      },
      // 切换属性
      async attributeChange(e) {
        if (e == 'all') {
          this.dataMerging();
          return;
        }
        let data = this.bomListV.find(
          (el) => el.bomId === this.formInline.bomId
        );
        if (!data) return;
        await this.getMaterialData(data, e);
      },
      // 获取物料数据信息
      async getMaterialData(data, attributeType) {
        if (attributeType == 'all') {
          this.dataMerging();
          return;
        }
        let params = {};
        let api = null;
        if (this.source == 'list') {
          let produceType =
            this.produceType == 1 ? 1 : attributeType == 2 ? 2 : 3;
          let kitting = this.quota_calculation == 1 ? false : true;
          let { startTime, endTime } = this.getTimeData();
          params = {
            salesOrderId: this.salesOrderId,
            bomVersionId: data.bomId,
            produceType: produceType,
            startTime,
            endTime,
            kitting: kitting
          };
          api = findMaterialInfoSalesorder;
        } else {
          api = findMaterialInfoByCategory;
          params = {
            categoryId: this.orderInfo.categoryId,
            bomVersionId: this.orderInfo.bomCategoryId,
            requiredFormingNum: this.orderInfo.contractNum,
            startTime,
            endTime,
            kitting: kitting
          };
        }
        this.loading = true;
        try {
          const result = await api(params);
          // 结果数据处理
          this.resultProcess(result);
          this.loading = false;
        } catch (err) {
          this.loading = false;
        }
      },
      getTimeData() {
        let startTime = '';
        let endTime = '';
        if (this.startTime.length > 0) {
          startTime = this.startTime[0];
          endTime = this.startTime[1];
        }
        return { startTime, endTime };
      },
      // 结果数据处理
      resultProcess(result) {
        this.datasourceList = [];
        if (!result || result.length == 0) {
          this.baseCount = '';
          this.baseUnit = '';
          this.datasourceAllList = [];
          return;
        }
        let first = result[0];
        this.baseCount = first.baseCount;
        this.baseUnit = first.measuringUnit;
        result.map((item) => {
          item.batchNo = this.orderInfo.batchNo;
          item.productCode = this.orderInfo.productCode;
          item.finalState =
            item.finalStateText == '齐套'
              ? 1
              : item.finalStateText == '缺料'
              ? 2
              : '';
        });
        this.datasourceAllList = result;
        this.finalChange(this.formInline.finalState);
      },
      // 选择状态
      finalChange(e) {
        if (e === 0 || !e) {
          this.datasourceList = this.datasourceAllList;
          return;
        }
        this.datasourceList = this.datasourceAllList.filter(
          (item) => item.finalState === e
        );
      },
      // 批量采购
      async bulkPurchase() {
        if (this.selection.length == 0) {
          return this.$message.warning('请至少选择一条数据');
        }
        for (let i = 0; i < this.selection.length; i++) {
          let el = this.selection[i];
          if (el.finalState == 1) {
            return this.$message.warning('必须选择最终状态为缺料的数据');
          }
          if (el.hasIssued) {
            return this.$message.warning('必须选择下发状态为未下发的数据');
          }
        }
        let arr = JSON.parse(JSON.stringify(this.selection));
        let obj = this.bomListType.find(
          (el) => el.bomType === this.formInline.bomType
        );
        let data = {
          ...this.orderInfo,
          bomId: this.formInline.bomId,
          bomType: obj.bomType
        };
        this.$refs.purchaseDialogRef.open(arr, data);
      },
      success() {
        this.bomVChange(this.formInline.bomId);
      },

      // 获取新建销售订单数据
      getSalaOrder() {
        let obj = {};
        let producedList = this.bomListType.map((item) => {
          if (item.id === this.formInline.bomType) {
            obj = item;
          }
          return {
            code: item.bomType,
            name: item.bomName
          };
        });
        let o = {};
        const bomListV = this.bomListV.map((el) => {
          if (el.bomId === this.formInline.bomId) {
            o = el;
          }
          let versions = this.getIntegerPart(el.versions);
          return {
            ...el,
            id: el.bomId,
            versions: versions
          };
        });
        let list = this.selection.map((item) => {
          return {
            ...item,
            producedList,
            productType: obj.bomType,
            bomVersionList: bomListV,
            bomCategoryId: o.bomId
          };
        });
        return list;
      },
      getIntegerPart(str) {
        // 使用正则表达式匹配数字部分（包括整数和小数）
        const numMatch = str.match(/\d+\.\d+/);
        if (numMatch) {
          // 分割小数点，取前面的整数部分并转为数字
          return parseInt(numMatch[0].split('.')[0], 10);
        }
        return null; // 没有匹配到符合格式的数据
      },
      clearData() {
        this.formInline = {
          finalState: 0,
          attributeType: 2
        };
        this.baseCount = '';
        this.baseUnit = '';
        this.bomListV = [];
        this.bomListType = [];
        this.datasourceList = [];
        this.datasourceAllList = [];
        this.orderInfo = {};
        this.kitComInfo = {};
      },

      onSubmit() {
        this.getKitting();
        this.attributeChange(this.formInline.attributeType);
      }
    }
  };
</script>

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

  .el-form-item {
    margin-bottom: 0 !important;
  }
  .planInfo {
    display: flex;
    font-size: 16px;
  }

  .form-wrapper {
    display: flex;
  }

  .order_form {
    .el-col {
      margin-bottom: 16px;
    }
  }

  .statusRed {
    color: red;
    :deep(.el-input__inner) {
      color: red;
    }
  }

  .statusGreen {
    color: green;
    :deep(.el-input__inner) {
      color: green;
    }
  }

  .left_tree {
    width: 250px;
    max-height: 600px;
    min-height: 300px;
    overflow: auto;
    border: 1px solid #ccc;
    margin-right: 10px;
  }

  // ::v-deep .basic_quantity{
  //   padding-top: 4px;
  // }

  .tool {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 5px 10px;
    border-left: 1px solid #ededed;
    border-right: 1px solid #ededed;
  }
</style>
