<template>
  <ele-modal
    :visible.sync="visible"
    @closed="cancel"
    :title="`${type == 'add' ? '创建' : '编辑'}配料计划`"
    custom-class="ele-dialog-form"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="80%"
    :maxable="true"
  >
    <el-form
      :model="formData"
      ref="formRef"
      label-width="120px"
      class="ele-body"
      :rules="rules"
    >
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="需求类型" prop="demandType">
            <el-select
              v-model="formData.demandType"
              :key="formData.demandType"
              placeholder="请选择"
              style="width: 100%"
              @change="changeDemandType"
              :disabled="type == 'detail'"
            >
              <el-option
                v-for="item in demandTypeList"
                :key="item.dictCode"
                :label="item.dictValue"
                :value="item.dictCode"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="计划名称" prop="name">
            <el-input
              placeholder="请选择"
              v-model="formData.name"
              :readonly="type == 'detail'"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="备注" prop="remark">
            <el-input
              placeholder="备注"
              v-model="formData.remark"
              :readonly="type == 'detail'"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-form :model="formData" ref="tableForm">
      <ele-pro-table
        ref="table"
        :needPage="false"
        :columns="columns"
        row-key="id"
        :expanded-row-keys="expandedRowKeys"
      >
        <template v-slot:toolbar>
          <el-button
            size="small"
            type="primary"
            icon="el-icon-plus"
            class="ele-btn-icon"
            @click="saleAdd"
            v-if="type != 'detail'"
          >
            添加销售订单
          </el-button>
        </template>

        <template v-slot:code="{ row }">
          <el-input
            placeholder="请输入"
            readonly
            :value="row.code || row.salesOrderCode"
          ></el-input>
        </template>

        <template v-slot:bomId="{ row }">
          <el-select
            v-model="row.bomId"
            placeholder="请选择"
            style="width: 100%"
            :disabled="type == 'detail'"
            @change="changeVersions(row)"
          >
            <!-- <el-option
              v-for="item in row.bomCategoryList"
              :key="item.bomType == row.bomType ? item.id : ''"
              :label="
                item.bomType == row.bomType ? 'V' + item.versions + '.0' : ''
              "
              :value="item.bomType == row.bomType ? item.id : ''"
              v-if="item.id !== ''"
            >
            </el-option> -->
            <el-option
              v-for="item in getBOMData(row)"
              :key="item.id"
              :label="'V' + item.versions + '.0'"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </template>

        <template v-slot:bomType="{ row }">
          <el-select
            v-model="row.bomType"
            placeholder="请选择"
            style="width: 100%"
            :disabled="type == 'detail'"
            @change="changeType(row, row.bomType)"
          >
            <el-option
              v-for="item in bomTypeList"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </template>

        <template v-slot:action="{ row, $index }" v-if="type != 'detail'">
          <template>
            <el-link
              type="primary"
              :underline="false"
              @click="categorySelect(row)"
            >
              添加物料
            </el-link>
            <el-popconfirm
              class="ele-action"
              title="确定要删除此销售订单吗？"
              @confirm="remove(row, $index)"
            >
              <template v-slot:reference>
                <el-link type="danger" :underline="false" icon="el-icon-delete">
                  删除
                </el-link>
              </template>
            </el-popconfirm>
          </template>
        </template>

        <!-- 展开内容 -->
        <template v-slot:expand="{ row }">
          <div class="batch-actions" v-if="row.materialList.length > 0">
            <el-button @click="batchUpdateDeliveryMethod"
              >批量修改到货方式</el-button
            >
            <el-button
              @click="removeAll(row.id, row.materialList)"
              type="danger"
              >批量删除</el-button
            >
          </div>
          <div
            style="
              width: calc(100% - 95px);
              min-height: 60px;
              margin-left: 95px;
            "
            v-if="row.materialList.length > 0"
          >
            <ele-pro-table
              :toolbar="false"
              toolsTheme="none"
              ref="table2"
              :need-page="false"
              :datasource="row.materialList"
              :columns="columns2"
              :key="row.sort + '-' + row.materialList.sort"
              @selection-change="handleSelectionChange"
              maxHeight="350px"
            >
              <template v-slot:sort="{ $index }">
                {{ $index + 1 }}
              </template>

              <template v-slot:unit="{ row }">
                {{ row.unit }}
              </template>

              <template v-slot:supplierId="{ row }">
                <el-select
                  v-model="row.supplierId"
                  size="mini"
                  clearable
                  class="ele-block"
                  filterable
                  placeholder="请选择供应商"
                  disabled
                >
                  <el-option
                    v-for="(item, index) in gysList"
                    :key="item.id + index"
                    :value="item.id"
                    :label="item.name"
                  ></el-option>
                </el-select>
              </template>

              <template v-slot:demandQuantity="{ row }">
                <el-input
                  v-model="row.demandQuantity"
                  placeholder="请输入"
                  :readonly="type == 'detail'"
                  @input="
                    (value) =>
                      (row.demandQuantity = value.replace(
                        /^(-)*(\d+)\.(\d\d\d\d\d\d).*$/,
                        '$1$2.$3'
                      ))
                  "
                ></el-input>
              </template>
              <template v-slot:purchasingCycle="{ row }">
                {{ row.purchasingCycle }}{{ row.purchasingCycleUnit }}
              </template>

              <template v-slot:purchaseQuantity="{ row }">
                <el-input
                  v-model="row.purchaseQuantity"
                  placeholder="请输入"
                  :readonly="type == 'detail'"
                  @input="
                    (value) =>
                      (row.purchaseQuantity = value.replace(
                        /^(-)*(\d+)\.(\d\d\d\d\d\d).*$/,
                        '$1$2.$3'
                      ))
                  "
                ></el-input>
              </template>

              <template v-slot:deliveryMethod="{ row, $index }">
                <el-select
                  clearable
                  class="ele-block"
                  v-model="row.deliveryMethod"
                  placeholder="请选择"
                  :disabled="type == 'detail'"
                >
                  <el-option
                    label="一次性到货"
                    :value="1"
                    @click.native="row.timeList = null"
                  />
                  <el-option
                    label="分批到货"
                    :value="2"
                    @click.native="
                      handleMethod(row, $index);
                      row.requireDeliveryTime = null;
                    "
                  />
                </el-select>
              </template>

              <template v-slot:requireDeliveryTime="{ row, $index }">
                <el-date-picker
                  style="width: 100%"
                  clearable
                  v-model="row.requireDeliveryTime"
                  type="date"
                  v-show="row.deliveryMethod == 1"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择日期"
                  :pickerOptions="{
                    disabledDate: (time) =>
                      time.getTime() <
                      new Date(new Date().setHours(0, 0, 0, 0)).getTime()
                  }"
                  :readonly="type == 'detail'"
                >
                </el-date-picker>

                <el-link
                  type="primary"
                  :underline="false"
                  v-show="row.deliveryMethod == 2"
                  @click.native="handleMethod(row, $index)"
                >
                  设置分批时间
                </el-link>
              </template>

              <template v-slot:imgUrl="{ row }">
                <fileMain
                  v-model="row.imgUrl"
                  module="main"
                  :showLib="false"
                  :limit="1"
                  :disabled="type == 'detail'"
                />
              </template>

              <template v-slot:files="{ row }">
                <fileMain
                  v-model="row.files"
                  module="main"
                  :showLib="false"
                  :limit="1"
                  :disabled="type == 'detail'"
                />
              </template>

              <template
                v-slot:action="{ row, $index: idx }"
                v-if="type != 'detail'"
              >
                <el-popconfirm
                  class="ele-action"
                  title="确定要删除当前物料吗？"
                  @confirm="remove2(row, idx)"
                >
                  <template v-slot:reference>
                    <el-link
                      type="danger"
                      :underline="false"
                      icon="el-icon-delete"
                    >
                      删除
                    </el-link>
                  </template>
                </el-popconfirm>
              </template>
            </ele-pro-table>
          </div>
        </template>
      </ele-pro-table>
    </el-form>

    <div slot="footer" v-if="type != 'detail'">
      <el-button @click="cancel">取消</el-button>
      <el-button
        v-if="$hasPermission('aps:batchingplan:save')"
        type="primary"
        @click="confirm('save')"
        >保存</el-button
      >

      <el-button
        v-if="$hasPermission('aps:batchingplan:saveAndSubmit')"
        type="primary"
        @click="confirm('submit')"
        >提交</el-button
      >
      <el-button
        v-if="$hasPermission('aps:batchingplan:submitAndPublish')"
        type="primary"
        @click="confirm('publish')"
      >
        提交并发布
      </el-button>
    </div>

    <saleOrderPop ref="saleOrderRef" @chooseOrder="chooseOrder"></saleOrderPop>

    <ProductModal ref="productRefs" @chooseModal="chooseModal" />

    <ProductionVersion
      ref="versionRefs"
      @changeProduct="changeProduct"
    ></ProductionVersion>

    <timeDialog ref="timeDialogRef" @chooseTime="chooseTime"></timeDialog>

    <ele-modal
      :visible.sync="batchVisible"
      title="批量选择"
      width="25vw"
      append-to-body
      @close="handleCancel"
      :maxable="true"
    >
      <el-form :model="formData2" label-width="100px">
        <el-form-item label="到货方式" prop="deliveryMethod">
          <el-select
            clearable
            v-model="formData2.deliveryMethod"
            placeholder="请选择"
          >
            <el-option label="一次性到货" :value="1" />
            <el-option
              label="分批到货"
              :value="2"
              @click.native="handleMethod(null, null, true)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="要求到货时间" prop="requireDeliveryTime">
          <el-date-picker
            clearable
            v-model="formData2.requireDeliveryTime"
            type="date"
            v-show="formData2.deliveryMethod == 1"
            value-format="yyyy-MM-dd"
            placeholder="请选择日期"
            :pickerOptions="{
              disabledDate: (time) =>
                time.getTime() <
                new Date(new Date().setHours(0, 0, 0, 0)).getTime()
            }"
          >
          </el-date-picker>
          <el-link
            type="primary"
            :underline="false"
            v-show="formData2.deliveryMethod == 2"
            @click.native="handleMethod(null, null, true)"
          >
            设置分批时间
          </el-link>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </template>
    </ele-modal>
  </ele-modal>
</template>

<script>
  import saleOrderPop from './saleOrderPop.vue';
  import ProductModal from './ProductModal.vue';
  import {
    listBomBySalesOrderIdsOverride,
    listBomByBomVersionId,
    listBomBySalesOrderId,
    save,
    saveAndSubmit,
    submitAndPublish,
    getById,
    contactList
  } from '@/api/materialPlan/index';
  import ProductionVersion from '@/components/CreatePlan/ProductionVersion2.vue';

  import { getCode } from '@/api/codeManagement';

  // import fileUpload from '@/components/addDoc/index.vue';
  import timeDialog from './timeDialog.vue';
  import dictMixins from '@/mixins/dictMixins';
  export default {
    components: {
      saleOrderPop,
      ProductModal,
      ProductionVersion,
      // fileUpload,
      timeDialog
    },
    mixins: [dictMixins],
    data() {
      return {
        formData2: {
          deliveryMethod: 1,
          requireDeliveryTime: '',
          timeList: []
        },
        batchVisible: false,
        multipleSelection: [],
        visible: false,
        type: 'add',

        tableData: [],

        xsId: null,
        formData: {
          demandType: '1',
          name: '',
          remark: '',
          detailRemoveIds: [],
          materialRemoveIds: [],
          orderType: 1
        },
        demandTypeList: [
          {
            dictCode: '1',
            dictValue: '生产性物资采购'
          },
          {
            dictCode: '6',
            dictValue: '外协自供料采购'
          },
          {
            dictCode: '7',
            dictValue: '外协客供料采购'
          }
        ],
        expandedRowKeys: [],
        bomType: 1,
        gysList: [],
        bomCategoryList: [],
        bomTypeList: [
          { id: '1', label: 'PBOM' },
          { id: '2', label: 'MBOM' }
        ],
        rules: {
          demandType: [
            {
              required: true,
              message: '请选择需求类型',
              trigger: ['blur', 'change']
            }
          ],
          name: [
            {
              required: true,
              message: '请输入配料计划名称',
              trigger: ['blur', 'change']
            }
          ]
        }
      };
    },
    computed: {
      // 表格列配置
      columns() {
        const list = [
          {
            width: 45,
            type: 'expand',
            columnKey: 'materialList',
            align: 'center',
            slot: 'expand'
          },

          {
            width: 50,
            label: '序号',
            type: 'index',
            align: 'center',
            slot: 'index'
          },

          {
            prop: 'purchaseType',
            label: '采购类型',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 120,
            sortable: true,
            formatter: (row) => {
              return row.purchaseType == '2' ? '已采购' : '未采购';
            }
          },
          {
            prop: 'code',
            label: '销售订单号',
            slot: 'code',
            showOverflowTooltip: true,
            align: 'center',
            minWidth: 170,
            sortable: true
          },
          {
            prop: 'customerName',
            label: '客户名称',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'serialNo',
            label: '客户代号',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'productCode',
            label: '编码',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140
          },

          {
            prop: 'productName',
            label: '名称',
            align: 'center',
            minWidth: 120
          },

          {
            prop: 'model',
            label: '型号',
            align: 'center',
            minWidth: 120
          },

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

          {
            prop: 'deliveryTime',
            label: '交付日期',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'contractNum',
            label: '订单数量',
            align: 'center'
          },
          {
            prop: 'lackNum',
            label: '欠交数量',
            align: 'center'
          },
          {
            label: '选择BOM类型',
            slot: 'bomType',
            align: 'center',
            minWidth: 110
          },

          {
            prop: 'bomId',
            label: '选择BOM版本',
            slot: 'bomId',
            align: 'center',
            minWidth: 110
          },
          this.type != 'detail'
            ? {
                columnKey: 'action',
                label: '操作',
                width: 150,
                align: 'center',
                resizable: false,
                slot: 'action',
                showOverflowTooltip: true
              }
            : ''
        ].filter(Boolean);
        return list;
      },

      columns2() {
        const list = [
          {
            columnKey: 'selection',
            type: 'selection',
            width: 50,
            align: 'center',
            fixed: 'left'
          },
          {
            width: 50,
            label: '序号',
            prop: 'sort',
            slot: 'sort',
            align: 'center',
            fixed: 'left'
          },

          {
            label: '物料名称',
            prop: 'name',
            align: 'center',
            minWidth: 120,
            fixed: 'left'
          },

          {
            label: '物料编码',
            prop: 'code',
            align: 'center',
            minWidth: 120,
            fixed: 'left'
          },
          {
            label: '牌号',
            prop: 'brandNum',
            align: 'center'
          },
          {
            prop: 'specification',
            label: '规格',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            label: '型号',
            prop: 'modelType',
            align: 'center'
          },

          {
            prop: 'inventoryQuantity',
            label: '库存',
            showOverflowTooltip: true
          },
          // {
          //   prop: 'secureInventory',
          //   label: '安全库存',
          //   showOverflowTooltip: true
          // },
          // {
          //   prop: 'lockQuantity',
          //   label: '锁库数量',
          //   showOverflowTooltip: true
          // },
          // {
          //   prop: 'inTransitNum',
          //   label: '在途数量',
          //   showOverflowTooltip: true
          // },
          // {
          //   prop: 'inTransitOrdersNum',
          //   label: '在途已关联数量',
          //   showOverflowTooltip: true
          // },
          // {
          //   prop: 'availableQuantity',
          //   label: '可用数量',
          //   showOverflowTooltip: true
          // },
          {
            prop: 'unit',
            label: '计量单位',
            showOverflowTooltip: true,
            action: 'unit',
            slot: 'unit'
          },

          {
            label: '需求数量',
            slot: 'demandQuantity',
            action: 'demandQuantity',
            align: 'center',
            minWidth: 120
          },

          // {
          //   label: '采购数量',
          //   slot: 'purchaseQuantity',
          //   action: 'purchaseQuantity',
          //   align: 'center',
          //   minWidth: 120
          // },
          {
            label: '采购周期',
            slot: 'purchasingCycle',
            action: 'purchasingCycle',
            align: 'center',
            minWidth: 160
          },
          {
            label: '供应商',
            slot: 'supplierId',
            action: 'supplierId',
            align: 'center',
            minWidth: 160
          },
          {
            label: '到货方式',
            slot: 'deliveryMethod',
            action: 'deliveryMethod',
            align: 'center',
            minWidth: 140
          },

          {
            label: '要求到货时间',
            slot: 'requireDeliveryTime',
            action: 'requireDeliveryTime',
            align: 'center',
            minWidth: 180
          },

          {
            label: '图纸',
            slot: 'imgUrl',
            action: ' imgUrl',
            align: 'center',
            minWidth: 140
          },

          {
            label: '附件',
            slot: 'files',
            action: ' files',
            align: 'center',
            minWidth: 140
          },

          this.type != 'detail'
            ? {
                columnKey: 'action',
                label: '操作',
                width: 80,
                align: 'center',
                resizable: false,
                slot: 'action',
                showOverflowTooltip: true
              }
            : ''
        ].filter(Boolean);
        return list;
      },

      filteredOptions(row) {
        const date = [];
        row.bomCategoryList.map((item) => {
          item.bomCategoryList.forEach((i) => {
            if (item.bomType == i.bomType) {
              date.push(i);
            }
          });
        });
        console.log(date);
        // return date;
      }
    },

    created() {
      this.getContactList();
    },

    methods: {
      async open(type, row) {
        this.type = type;

        this.formData.demandType = '1';

        if (this.type == 'add') {
          this.formData.demandType = '1';
          const name = await getCode('purchase_apply_plan_name');
          console.log(name, 'name');
          this.formData.name = name;
        }

        this.formData.orderType = 1;
        this.visible = true;

        if (row) {
          this.getDetail(row.id);
        } else {
          this.$nextTick(() => {
            this.$refs.table.setData([]);
          });
        }
      },

      getContactList() {
        let param = {
          pageNum: 1,
          type: 2,
          size: -1,
          status: 1
        };
        contactList(param).then((res) => {
          this.gysList = res.list;
        });
      },

      getDetail(id) {
        getById(id).then((res) => {
          this.$set(this.formData, 'demandType', res.demandType);
          this.$set(this.formData, 'name', res.name);
          this.$set(this.formData, 'remark', res.remark);
          this.formData['id'] = res.id;

          if (res.salesOrderList) {
            this.$refs.table.setData([...res.salesOrderList]);
            // 展开所有行
            this.expandedRowKeys = this.$refs.table
              .getData()
              ?.map((item) => item.id)
              .filter((id) => id != null);
          }

          this.$nextTick(() => {
            this.$refs.table.toggleRowExpansionAll();
            this.$forceUpdate();
          });
        });
      },

      saleAdd() {
        this.tableData = this.$refs.table.getData();
        this.$refs.saleOrderRef.open(this.tableData);
      },
      async chooseOrder(list) {
        let salesOrderIds = [];
        console.log(list, 'listlistlistlistlistlistlistlistlist 获取的数据');
        const tableList = this.$refs.table.getData() || [];
        const existingIds = tableList.map((item) => item.id);
        console.log(existingIds, '获取已存在的ID');

        const list1 = list.filter((item) => !existingIds.includes(item.id));
        if (list1.length === 0) {
          this.$message.warning('所选订单已存在');
          return;
        }

        list1.forEach((m) => {
          salesOrderIds.push(m.id);
        });
        if (salesOrderIds.length === 0) return;
        // if (salesOrderIds.length > 0) {
        try {
          let res = await listBomBySalesOrderIdsOverride({
            salesOrderIds: salesOrderIds,
            demandType: this.formData.demandType
          });
          if (this.$store.state.user.info.clientEnvironmentId == '5') {
            if (res && res.length > 0) {
              const firstOrderName = res[0].productName || '';
              this.formData.name =
                `${firstOrderName} ${this.formData.name}`.trim();
            }
          }
          this.renderTable(tableList, res);
        } catch (e) {
          this.$refs.table.setData([]);
          this.expandedRowKeys = [];
        }
      },
      renderTable(tableList, res) {
        if (!res || res.length === 0) {
          this.$refs.table.setData([]);
          this.expandedRowKeys = [];
          return;
        }
        res.forEach((m) => {
          if (m.materialList.length > 0) {
            m.materialList.forEach((p) => {
              p.detailId = m.id;
            });
          }
        });
        this.bomType = 1;
        const finalData = res.filter(
          (item) => !tableList.some((existing) => existing.id === item.id)
        );
        this.bomCategoryList = finalData;
        this.$refs.table.setData([...tableList, ...finalData]);
        this.$nextTick(() => {
          this.expandedRowKeys = this.$refs.table
            .getData()
            .map((item) => item.id);
          this.$refs.table.toggleRowExpansionAll();
        });
      },
      async changeDemandType(e) {
        const tableList = this.$refs.table.getData() || [];
        if (!tableList || tableList.length === 0) {
          return;
        }
        try {
          const salesOrderIds = tableList.map((item) => item.id);
          const res = await listBomBySalesOrderIdsOverride({
            salesOrderIds: salesOrderIds,
            demandType: e
          });
          this.renderTable(tableList, res);
        } catch (e) {
          this.$refs.table.setData([]);
          this.expandedRowKeys = [];
        }
      },
      categorySelect(row) {
        this.$refs.productRefs.open(row.materialList, row, this.type);
      },
      remove(row, index) {
        this.formData.detailRemoveIds.push(row.id);
        let _arr = this.$refs.table.getData() || [];
        _arr.splice(index, 1);
        console.log(_arr, '_arr');
        this.$refs.table.setData([..._arr]);
      },
      chooseModal(data, current) {
        data.map((m) => {
          m.detailId = current.id;
          delete m.id;
          return {
            ...m
          };
        });
        console.log(data, 'data');
        let tableList = [];
        tableList = this.$refs.table.getData();

        tableList.forEach((e) => {
          if (e.id == current.id) {
            if (e.materialList.length == 0) {
              e.materialList = data;
            } else {
              e.materialList = [...e.materialList, ...data];
            }
          }
        });

        console.log(tableList);
        this.$refs.table.setData([...tableList]);
        this.$forceUpdate();
      },
      removeAll(detailId, materialList) {
        let data = this.multipleSelection.filter(
          (item) => item.detailId == detailId
        );
        data.forEach((e) => {
          this.remove2(e);
        });
      },
      remove2(row, idx) {
        console.log(idx, 'idx 333');
        const data = this.$refs.table.getData() ?? [];
        if (row.id) {
          this.formData.materialRemoveIds.push(row.id);
        }
        console.log(data, 'data 1');
        console.log(row, 'row 1');
        data.forEach((e) => {
          if (row.detailId == e.id) {
            e.materialList = e.materialList.filter(
              (d) => d.categoryId !== row.categoryId
            );
            // e.materialList.splice(idx, 1);
          }
        });

        this.$refs.table.setData([...data]);
        this.$forceUpdate();
      },
      changeVersions(row) {
        listBomByBomVersionId({
          bomId: row.bomId,
          contractNum: row.contractNum,
          demandType: this.formData.demandType,
          salesCode: row.code,
          salesId: row.id,
          bomType: row.bomType
        }).then((res) => {
          console.log(res, 'res');

          row.materialList = res || [];
          // this.$nextTick(() => {
          //   this.$refs.table.toggleRowExpansionAll();
          //   this.$forceUpdate();
          // });
        });
      },
      changeType(row, value) {
        // console.log(1121313123);
        const data = row.bomCategoryList.filter(
          (item) => item.bomType == row.bomType
        );
        if (data.length > 0) {
          row.bomId = data[0].bomId;
          this.changeVersions(row);
        } else {
          row.bomId = '';
        }
      },

      getBOMData(row) {
        return row.bomCategoryList.filter(
          (item) => item.bomType == row.bomType
        );
      },

      //选择工艺路线
      openVersion(row) {
        this.xsId = row.id;
        this.$refs.versionRefs.open();
      },
      changeProduct(data) {
        const param = {
          salesOrderIds: [this.xsId],
          produceRoutingId: data.id
        };

        listBomBySalesOrderId(param).then((res) => {
          if (!res) return;

          const tableList = this.$refs.table.getData();

          tableList
            .forEach((e) => {
              if (e.id == this.xsId) {
                e.materialList = res.map((m) => {
                  m.detailId = this.xsId;
                  return {
                    ...m
                  };
                });

                this.$nextTick(() => {
                  this.$refs.table.setData([...tableList]);
                  this.$refs.table.toggleRowExpansionAll();
                });
              }
            })
            .catch((error) => {
              console.error('Failed to change product:', error);
            });
        });
      },
      // ---------------------------

      // 批量修改到货方式
      batchUpdateDeliveryMethod() {
        if (this.multipleSelection.length === 0) {
          this.$message.warning('请选择要修改的行');
          return;
        }
        this.formData2 = {
          deliveryMethod: 1,
          requireDeliveryTime: '',
          timeList: []
        };
        this.batchVisible = true;
      },
      // 处理表格选中行的变化
      handleSelectionChange(selection) {
        this.multipleSelection = selection;
      },
      handleCancel() {
        this.batchVisible = false;
      },

      handleConfirm() {
        const { deliveryMethod, requireDeliveryTime } = this.formData2;
        const tableData = this.$refs.table.getData();

        // 创建深拷贝的 timeList 模板（假设当前表单中已填写了分批时间）
        const timeListTemplate = JSON.parse(
          JSON.stringify(this.formData2.timeList)
        );

        tableData.forEach((item) => {
          item.materialList.forEach((m) => {
            if (
              this.multipleSelection.some(
                (selected) => selected.categoryId === m.categoryId
              )
            ) {
              this.$set(m, 'deliveryMethod', deliveryMethod);
              if (deliveryMethod === 1) {
                //一次性到货逻辑
                this.$set(m, 'requireDeliveryTime', requireDeliveryTime);
                this.$set(m, 'timeList', null);
              } else if (deliveryMethod === 2) {
                this.$set(
                  m,
                  'timeList',
                  JSON.parse(JSON.stringify(timeListTemplate))
                );
              }
            }
          });
        });

        this.$refs.table.setData([...tableData]);
        this.batchVisible = false;
      },
      handleMethod(row, index, isAll) {
        console.log(index, 'index');
        if (row) {
          this.multipleSelection = [];
        }
        this.$refs.timeDialogRef.open(row || {}, index, isAll);
      },

      chooseTime(current, timeList, currentIndex) {
        const tableList = this.$refs.table.getData();

        if (current && current.categoryId) {
          // 单独修改逻辑：直接操作当前物料的 timeList
          tableList.forEach((item) => {
            if (item.id === current.detailId) {
              const material = item.materialList[currentIndex];

              this.$set(
                material,
                'timeList',
                JSON.parse(JSON.stringify(timeList))
              );
            }
          });
        } else if (this.multipleSelection.length > 0) {
          // 批量修改逻辑
          tableList.forEach((item) => {
            item.materialList.forEach((material) => {
              if (
                this.multipleSelection.some(
                  (selected) => selected.categoryId === material.categoryId
                )
              ) {
                this.$set(
                  material,
                  'deliveryMethod',
                  this.formData2.deliveryMethod
                );
                this.$set(
                  material,
                  'timeList',
                  JSON.parse(JSON.stringify(timeList))
                );
              }
            });
          });
          this.$refs.timeDialogRef.handleClose();
          this.batchVisible = false;
        }

        this.$refs.table.setData([...tableList]);
      },
      confirm(type) {
        this.$refs.formRef.validate(async (value) => {
          if (value) {
            let _arr = this.$refs.table.getData() ?? [];

            if (_arr.length == 0) {
              this.$message.info('请添加销售订单');
              return false;
            }
            let _arr2 = [],
              isNoMaterial = [];

            _arr2 = _arr.map((m) => {
              if (
                Object.prototype.hasOwnProperty.call(m, 'salesOrderId') &&
                m.salesOrderId
              ) {
              } else {
                m.salesOrderId = m.id;
                m.salesOrderCode = m.code;
                delete m.id;
                delete m.code;
              }
              if (!m.materialList.length) {
                isNoMaterial.push(m.productName);
              }
              return {
                ...m
              };
            });
            if (isNoMaterial.length) {
              this.$message.info(
                isNoMaterial.join(',') + ' 物料清单为空，请检查！'
              );
              return;
            }
            this.formData['type'] = 1;
            this.formData['salesOrderList'] = _arr2;
            this.formData.baitingType = 2;
            let deliveryTimeArr = [];
            let noDeliveryTimeArr = [];
            this.formData.salesOrderList.forEach((item) => {
              item.materialList.forEach((m) => {
                if (m.deliveryMethod == 2 && !m.timeList?.length) {
                  noDeliveryTimeArr.push({
                    name: m.name
                  });
                }
                if (m.deliveryMethod == 2 && m.timeList?.length) {
                  let purchaseQuantity =
                    m.timeList.reduce((pre, cur) => {
                      return pre + (Number(cur.purchaseQuantity) || 0);
                    }, 0) || 0;
                  if (purchaseQuantity != m.demandQuantity) {
                    deliveryTimeArr.push({
                      name: m.name
                    });
                  }
                }
              });
            });
            if (noDeliveryTimeArr.length) {
              this.$message.warning(
                `${noDeliveryTimeArr
                  .map((item) => item.name)
                  .join(',')} 物料未填写分批到货时间`
              );
              return;
            }
            if (deliveryTimeArr.length) {
              this.$message.warning(
                `${deliveryTimeArr
                  .map((item) => item.name)
                  .join(',')} 物料需求数量与分批到货数量不一致，请检查！`
              );
              return;
            }
            if (type == 'submit') {
              await saveAndSubmit(this.formData);
              this.$message.success('保存并提交成功！');
            } else if (type == 'publish') {
              await submitAndPublish(this.formData);
              this.$message.success('保存并发布成功！');
            } else {
              await save(this.formData);
              this.$message.success('保存成功！');
            }
            this.$emit('success');
            this.cancel();
          }
        });
      },
      cancel() {
        this.visible = false;

        this.formData = {
          demandType: '1', // 增加默认值重置
          name: '',
          remark: '',
          detailRemoveIds: [],
          materialRemoveIds: [],
          orderType: 1
        };
        this.$refs.table.setData([]);
        this.$refs.formRef.resetFields();
      },
      getNewData(row) {
        // row.bomCategoryList.forEach((item) => {

        // })

        return row;
      }
    }
  };
</script>

<style lang="scss" scoped>
  :deep(.el-table__expanded-cell) {
    padding-bottom: 30px !important;
    border-bottom: 12px solid #ccffcc !important;
  }

  .batch-actions {
    text-align: right;
    margin: 10px;
  }
</style>
