<template>
  <el-dialog
    :title="title"
    :visible.sync="open"
    width="950px"
    append-to-body
    @close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form ref="detailForm" :model="form" label-width="100px" :rules="rules">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="货物ID" prop="materialId">
            <el-input
              v-model="form.materialName"
              placeholder="请选择物料"
              readonly
              @click.native="!isMaterialLocked && (openMaterialSelector = true)"
              style="cursor: pointer"
              :disabled="isMaterialLocked"
            >
              <template slot="suffix">
                <el-button
                  icon="el-icon-search"
                  size="mini"
                  @click.native="!isMaterialLocked && (openMaterialSelector = true)"
                  :disabled="isMaterialLocked"
                ></el-button>
              </template>
            </el-input>
            <el-input v-model="form.materialId" type="hidden" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 选择物料的弹窗 -->
      <el-dialog
        v-if="!isMaterialLocked"
        title="选择物料"
        :visible.sync="openMaterialSelector"
        width="90%"
        append-to-body
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :modal="true"
        :modal-append-to-body="true"
      >
        <div style="height: 70vh; overflow: auto; padding: 0 10px;">
          <MaterialSelector
            ref="materialsSeletor"
            @selection-change="handleMaterialSelectionChange"
            :selected-material-codes="form.materialUuids ? [form.materialUuids] : []"
            :multiple="false"
          />
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click.native="openMaterialSelector = false">取消</el-button>
          <el-button type="primary" @click.native="confirmMaterialSelect">确认选择</el-button>
        </div>
      </el-dialog>

      <!-- 库存信息列表 -->
      <el-row v-if="form.materialId && form.materialId.trim()" style="margin: 10px 0;">
        <el-col :span="24">
          <div style="margin-bottom: 8px; font-weight: 600; color: #1989fa;">
            库存信息列表
          </div>
          <el-table
            ref="inventoryTable"
            :data="inventoryList"
            border
            size="small"
            max-height="400"
            highlight-current-row
            stripe
            empty-text="暂无库存数据"
            @row-click="handleRowClick"
            :row-key="item => item.inventoryId"
          >
            <el-table-column prop="materialName" label="物料名称" width="180" />
            <el-table-column prop="batchId" label="批次ID" width="150" />
            <el-table-column prop="warehousesName" label="仓库名称" width="120" />
            <el-table-column prop="locationName" label="库位名称" width="120" />
            <el-table-column
              prop="inventoryType"
              label="库存类型"
              width="100"
            >
              <template slot-scope="scope">
                <dict-tag v-if="dict.type.inventory_type" :options="dict.type.inventory_type" :value="scope.row.inventoryType"/>
              </template>
            </el-table-column>
            <el-table-column label="可用数量" width="100">
              <template slot-scope="scope">
                {{ (scope.row.quantity || 0) - (scope.row.lockedQuantity || 0) }}
              </template>
            </el-table-column>
            <el-table-column label="实际数量" width="120" fixed="right">
              <template slot-scope="scope">
                <el-input
                  v-model.number="scope.row.actualQuantity"
                  type="number"
                  size="mini"
                  min="1"
                  :max="(scope.row.quantity || 0) - (scope.row.lockedQuantity || 0)"
                  @input="handleRowActualQtyInput(scope.row); syncDetails(false)"
                  placeholder="输入数量"
                />
              </template>
            </el-table-column>
          </el-table>

          <!-- 库存明细信息 -->
          <div
            v-if="currentSelectedRow"
            style="margin-top: 10px; padding: 10px; border: 1px solid #e6e6e6; border-radius: 4px;"
          >
            <div style="margin-bottom: 8px; font-weight: 600; color: #1989fa;">
              库存明细信息
            </div>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="约数" prop="divisor">
                  <el-input
                    v-model.number="currentSelectedRow.divisor"
                    placeholder="请输入约数"
                    type="number"
                    min="0"
                    @input="syncDetails(false)"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="标签颜色" prop="labelColor">
                  <el-select
                    v-model="currentSelectedRow.labelColor"
                    placeholder="请选择标签颜色"
                    style="width: 100%;"
                  >
                    <el-option
                      v-for="color in dict.type.label_color"
                      :key="color.value"
                      :label="color.label"
                      :value="Number(color.value)"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="计划数量" prop="plannedQuantity">
                  <el-input
                    v-model.number="currentSelectedRow.plannedQuantity"
                    type="number"
                    min="1"
                    :max="(currentSelectedRow.quantity || 0) - (currentSelectedRow.lockedQuantity || 0)"
                    @input="handleRowPlannedQtyInput(currentSelectedRow); syncDetails(false)"
                    placeholder="输入计划数量"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20" style="margin-top: 10px;">
              <el-col :span="8">
                <el-form-item label="单价" prop="unitPrice">
                  <el-input
                    v-model.number="currentSelectedRow.unitPrice"
                    placeholder="请输入单价"
                    type="number"
                    min="0"
                    step="0.01"
                    @input="syncDetails(false)"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="发货方" prop="shippedBy">
                  <el-input
                    v-model="currentSelectedRow.shippedBy"
                    placeholder="请输入发货方"
                    @input="syncDetails(false)"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="凭证号" prop="voucherNumber">
                  <el-input
                    v-model="currentSelectedRow.voucherNumber"
                    placeholder="请输入凭证号"
                    @input="syncDetails(false)"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20" style="margin-top: 10px;">
              <el-col :span="16">
                <el-form-item label="备注" prop="remark">
                  <el-input
                    v-model="currentSelectedRow.remark"
                    placeholder="请输入备注"
                    type="textarea"
                    rows="2"
                    @input="syncDetails(false)"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>

      <!-- 已生成明细项 -->
      <el-row v-if="details.length > 0" style="margin: 10px 0;">
        <el-col :span="24">
          <div style="margin-bottom: 8px; font-weight: 600; color: #1989fa;">
            已生成明细项
          </div>
          <el-table
            :data="details"
            border
            size="small"
            max-height="200"
            :row-key="item => item.inventoryId"
          >
            <el-table-column prop="materialName" label="物料名称" width="180" />
            <el-table-column prop="batchId" label="批次ID" width="150" />
            <el-table-column prop="warehousesName" label="仓库名称" width="120" />
            <el-table-column prop="locationName" label="库位名称" width="120" />
            <el-table-column prop="plannedQuantity" label="计划数量" width="100" />
            <el-table-column prop="actualQuantity" label="实际数量" width="100"  fixed="right"/>
            <el-table-column prop="unitPrice" label="单价" width="100" />
            <el-table-column prop="divisor" label="约数" width="80" />
            <el-table-column prop="labelColor" label="标签颜色" width="100">
              <template slot-scope="scope">
                <dict-tag v-if="dict.type.label_color" :options="dict.type.label_color" :value="scope.row.labelColor"/>
              </template>
            </el-table-column>
            <el-table-column prop="voucherNumber" label="凭证号" width="120" />
            <el-table-column prop="shippedBy" label="发货方" width="120" />
            <el-table-column prop="remark" label="备注" width="150" />
            <el-table-column label="操作" width="80" fixed="right">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="mini"
                  @click.native="removeDetail(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-form>

    <!-- 弹窗底部按钮 -->
    <div slot="footer" class="dialog-footer">
      <el-button @click.native="handleClose">取消</el-button>
      <el-button type="primary" @click.native="handleSubmit">生成明细</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { listInventoryByMaterialId } from "@/api/inventory/inventory";
import MaterialSelector from '@/components/materialsSeletor.vue';

function debounce(fn, delay = 500) {
  let timer = null;
  return function(...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}

export default {
  name: 'OutboundOrderFormWithItems',
  dicts: ['inbound_order_status', 'inbound_order_type', 'inbound_order_item_status', 'label_color','inventory_type'],
  components: {
    MaterialSelector
  },
  props: {
    title: {
      type: String,
      default: '新增明细项'
    },
    open: {
      type: Boolean,
      default: false
    },
    initForm: {
      type: Object,
      default: () => ({})
    },
    initDetails: {
      type: Array,
      default: () => []
    },
    outboundOrderId: {
      type: [String, Number],
      default: ''
    },
    groupData: {
      type: Object,
      default: () => ({})
    },
    ordersId: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      form: {
        materialUuids: '',
        materialId: '',
        materialName: '',
        itemStatus: 1,
        outboundOrderId: ''
      },
      details: [],
      inventoryList: [],
      loadingInstance: null,
      rules: {
        materialId: [{
          required: true,
          message: '请选择货物ID',
          trigger: ['change', 'blur']
        }]
      },
      openMaterialSelector: false,
      selectedMaterialId: '',
      selectedMaterialInfo: null,
      currentSelectedRowId: null,
      isInitEcho: false
    };
  },
  computed: {
    currentSelectedRow() {
      return this.inventoryList.find(row => row.inventoryId === this.currentSelectedRowId) || null;
    },
    isMaterialLocked() {
      return this.initDetails.length > 0 || !!this.initForm.materialId;
    }
  },
  watch: {
    open: {
      handler(newVal) {
        if (newVal) {
          this.isInitEcho = false;
          this.form = {
            ...this.$options.data().form,
            ...this.initForm,
            materialName: this.initForm.materialName || '',
            outboundOrderId: this.outboundOrderId || this.initForm.outboundOrderId || ''
          };
          this.selectedMaterialId = this.form.materialId || '';
          this.selectedMaterialInfo = null;
          this.currentSelectedRowId = null;
          this.details = this.initDetails.length > 0 ? JSON.parse(JSON.stringify(this.initDetails)) : [];
          this.$nextTick(async () => {
            if (this.form.materialId && this.form.materialId.trim()) {
              await this.handleMaterialIdChange();
              if (this.inventoryList.length > 0 && !this.isInitEcho) {
                this.initEchoDetails();
                this.isInitEcho = true;
                this.currentSelectedRowId = this.inventoryList[0].inventoryId;
              }
            }
          });
        } else {
          this.$nextTick(() => {
            this.closeLoading();
            if (this.$refs.detailForm) {
              this.$refs.detailForm.resetFields();
            }
          });
        }
      },
      immediate: true
    },
    initForm: {
      handler(val) {
        if (this.open) {
          this.form = {
            ...this.$options.data().form,
            ...val,
            materialName: val.materialName || '',
            outboundOrderId: this.outboundOrderId || val.outboundOrderId || ''
          };
          const oldMaterialId = this.selectedMaterialId;
          this.selectedMaterialId = this.form.materialId || '';
          this.currentSelectedRowId = null;
          this.$nextTick(async () => {
            if (this.form.materialId && this.form.materialId.trim() && this.form.materialId !== oldMaterialId) {
              await this.handleMaterialIdChange();
              if (this.inventoryList.length > 0 && !this.isInitEcho) {
                this.initEchoDetails();
                this.isInitEcho = true;
                this.currentSelectedRowId = this.inventoryList[0].inventoryId;
              }
            }
          });
        }
      },
      immediate: true,
      deep: true
    },
    inventoryList: {
      handler(newVal) {
        if (this.open && newVal.length > 0 && !this.isInitEcho) {
          this.initEchoDetails();
          this.isInitEcho = true;
          this.currentSelectedRowId = newVal[0].inventoryId;
        }
      },
      immediate: true,
      deep: true
    },
    outboundOrderId: {
      handler(val) {
        if (this.open) {
          this.form.outboundOrderId = val || this.form.outboundOrderId;
        }
      },
      immediate: true
    }
  },
  methods: {
    closeLoading() {
      if (this.loadingInstance) {
        try {
          this.loadingInstance.close();
        } catch (e) {
          console.warn('关闭加载状态失败:', e);
        }
        this.loadingInstance = null;
      }
    },
    async handleMaterialIdChange() {
      this.closeLoading();
      const materialId = this.form.materialId?.trim() || '';
      if (!materialId) {
        this.inventoryList = [];
        return;
      }

      try {
        this.loadingInstance = this.$loading({
          text: '查询中...',
          target: this.$el,
          lock: true,
          background: 'rgba(0, 0, 0, 0.7)'
        });
        console.log("this.form", this.form);
        const params = {
          materialId: materialId,
          outboundOrderId: this.ordersId
        };
        console.log('【查询库存参数】', params);
        const res = await listInventoryByMaterialId(params);
        console.log('【库存接口返回】', res);
        console.log('【库存接口原始行数据】', res.rows);
        if (res.code === 200) {
          this.inventoryList = [];
          (res.rows || []).forEach(item => {
            console.log('【单条库存数据】', item);
            const newRow = {
              inventoryId: item.id,
              id: item.id,
              materialId: item.materialId || materialId,
              materialName: item.materialName || '',
              batchId: item.batchId || '',
              outboundOrderId: item.orderId || this.form.outboundOrderId,
              warehouseId: item.warehousesId || '',
              warehousesId: item.warehousesId || '',
              warehousesName: item.warehousesName || '',
              locationId: item.locationId || '',
              locationName: item.locationName || '',
              inventoryType: item.inventoryType || 1,
              quantity: item.quantity || 0,
              lockedQuantity: item.lockedQuantity || 0,
              batchCode: item.batchId || '',
              actualQuantity: null,
              plannedQuantity: null,
              divisor: null,
              labelColor: '',
              unitPrice: null,
              shippedBy: '',
              shippedAt: '',
              voucherNumber: '',
              remark: ''
            };
            this.inventoryList.push(newRow);
          });
          if (this.inventoryList.length > 0 && !this.form.materialName) {
            this.$set(this.form, 'materialName', this.inventoryList[0].materialName || '');
          }
          console.log('【组装后的库存列表】', this.inventoryList);
          console.log('【待回显的initDetails】', this.initDetails);

          if (this.inventoryList.length === 0) {
            this.$message.warning('未查询到该物料的库存信息');
          }
        } else {
          this.inventoryList = [];
          this.$message.error(res.msg || '查询库存失败');
        }
      } catch (error) {
        this.$message.error('查询库存失败：' + (error.message || '网络异常'));
        this.inventoryList = [];
      } finally {
        this.$nextTick(() => {
          this.closeLoading();
        });
      }
    },
    initEchoDetails() {
      console.log('【开始回显】inventoryList=', this.inventoryList, 'initDetails=', this.initDetails);
      if (this.initDetails.length === 0 || this.inventoryList.length === 0) return;

      this.inventoryList.forEach(row => {
        this.$set(row, 'actualQuantity', null);
        this.$set(row, 'plannedQuantity', null);
        this.$set(row, 'divisor', null);
        this.$set(row, 'labelColor', '');
        this.$set(row, 'unitPrice', null);
        this.$set(row, 'shippedBy', '');
        this.$set(row, 'voucherNumber', '');
        this.$set(row, 'remark', '');
      });

      this.initDetails.forEach(detail => {
        let targetRow = null;
        targetRow = this.inventoryList.find(row => row.inventoryId === detail.inventoryId);
        
        if (!targetRow) {
          targetRow = this.inventoryList.find(row => 
            row.batchId === detail.batchId && 
            row.warehousesId === detail.warehousesId && 
            row.locationId === detail.locationId
          );
        }

        if (!targetRow) {
          targetRow = this.inventoryList.find(row => 
            row.batchId === detail.batchId && 
            row.materialId === detail.materialId
          );
        }

        if (!targetRow) {
          console.warn('【匹配失败】明细无对应库存行，detail.inventoryId=', detail.inventoryId);
          return;
        }

        this.$set(targetRow, 'actualQuantity', detail.actualQuantity ?? null);
        this.$set(targetRow, 'plannedQuantity', detail.plannedQuantity ?? null);
        this.$set(targetRow, 'divisor', detail.divisor ?? null);
        this.$set(targetRow, 'labelColor', detail.labelColor ?? '');
        this.$set(targetRow, 'unitPrice', detail.unitPrice ?? null);
        this.$set(targetRow, 'shippedBy', detail.shippedBy ?? '');
        this.$set(targetRow, 'voucherNumber', detail.voucherNumber ?? '');
        this.$set(targetRow, 'remark', detail.remark ?? '');
        if (detail.warehousesName) this.$set(targetRow, 'warehousesName', detail.warehousesName);
        if (detail.locationName) this.$set(targetRow, 'locationName', detail.locationName);
        if (detail.materialName) this.$set(targetRow, 'materialName', detail.materialName);
      });

      this.syncDetails(false);
      console.log('【回显完成】inventoryList=', this.inventoryList);
    },
    handleRowClick(row) {
      if (!row) return;
      this.currentSelectedRowId = row.inventoryId;
    },
    handleRowActualQtyInput(row) {
      if (isNaN(row.actualQuantity) || row.actualQuantity === '' || row.actualQuantity === null) {
        this.$set(row, 'actualQuantity', null);
        return;
      }
      const availableQty = (row.quantity || 0) - (row.lockedQuantity || 0);
      if (row.actualQuantity > availableQty) {
        this.$message.warning(`实际数量不能超过可用数量${availableQty}`);
        this.$set(row, 'actualQuantity', availableQty);
      } else if (row.actualQuantity < 1) {
        this.$message.warning('实际数量不能小于1');
        this.$set(row, 'actualQuantity', 1);
      }
    },
    handleRowPlannedQtyInput(row) {
      if (isNaN(row.plannedQuantity) || row.plannedQuantity === '' || row.plannedQuantity === null) {
        this.$set(row, 'plannedQuantity', null);
        return;
      }
      const availableQty = (row.quantity || 0) - (row.lockedQuantity || 0);
      if (row.plannedQuantity > availableQty) {
        this.$message.warning(`计划数量不能超过可用数量${availableQty}`);
        this.$set(row, 'plannedQuantity', availableQty);
      } else if (row.plannedQuantity < 1) {
        this.$message.warning('计划数量不能小于1');
        this.$set(row, 'plannedQuantity', 1);
      }
    },
    // 改造后的 syncDetails：仅校验有实际数量的行，且有值才校验
syncDetails(strict = true) {
  this.details = [];
  const errorMessages = []; // 收集有值但不合规的字段提示
  let validRows = [];

  // 第一步：先过滤出「实际数量有值」的行（核心：无实际数量的行直接排除）
  const rowsWithActualQty = this.inventoryList.filter(row => {
    return row.actualQuantity !== null && row.actualQuantity !== undefined;
  });

  if (strict && rowsWithActualQty.length > 0) {
    // 严格模式：仅校验有实际数量的行，且「有值才校验」
    validRows = rowsWithActualQty.filter((row, index) => {
      const rowErrors = [];
      const rowName = `第${index + 1}行【${row.materialName || '未知物料'}】`;
      const availableQty = (row.quantity || 0) - (row.lockedQuantity || 0);

      // 1. 实际数量（必校验，因为能走到这步说明有值）
      if (row.actualQuantity < 1) {
        rowErrors.push('实际数量不能小于1');
      }
      if (row.actualQuantity > availableQty) {
        rowErrors.push(`实际数量不能超过可用库存(${availableQty})`);
      }

      // 2. 计划数量（有值才校验）
      if (row.plannedQuantity !== null && row.plannedQuantity !== undefined) {
        if (row.plannedQuantity < 1) {
          rowErrors.push('计划数量不能小于1');
        }
        if (row.plannedQuantity > availableQty) {
          rowErrors.push(`计划数量不能超过可用库存(${availableQty})`);
        }
      }

      // 3. 除数（有值才校验，无值不提示）
      if (row.divisor !== null && row.divisor !== undefined) {
        // 若有值但为0/负数，可补充校验（按需）
        if (row.divisor <= 0) {
          rowErrors.push('换算率（除数）必须大于0');
        }
      }

      // 4. 标签颜色（有值才校验，空字符串算不合规）
      if (row.labelColor !== undefined && row.labelColor === '') {
        rowErrors.push('请填写标签颜色');
      }

      // 5. 凭证号（有值才校验，空字符串算不合规）
      if (row.voucherNumber !== undefined && row.voucherNumber === '') {
        rowErrors.push('请填写凭证号');
      }

      // 6. 发货人（有值才校验，空字符串算不合规）
      if (row.shippedBy !== undefined && row.shippedBy === '') {
        rowErrors.push('请填写发货人');
      }

      // 收集当前行的错误（仅有值但不合规的字段）
      if (rowErrors.length > 0) {
        errorMessages.push(`${rowName}：${rowErrors.join('、')}`);
        return false;
      }
      return true;
    });
  }

  // 格式化通过校验的行并同步到details
  validRows.forEach(row => {
    const newDetail = {
      inventoryId: row.inventoryId,
      materialId: row.materialId || this.form.materialId,
      materialName: row.materialName || this.form.materialName || '',
      batchId: row.batchId || row.batchCode || '',
      warehouseId: row.warehouseId,
      warehousesId: row.warehousesId || '',
      warehousesName: row.warehousesName || '',
      locationId: row.locationId || '',
      locationName: row.locationName || '',
      outboundOrderId: this.form.outboundOrderId || '',
      plannedQuantity: row.plannedQuantity,
      actualQuantity: row.actualQuantity,
      divisor: row.divisor,
      labelColor: row.labelColor,
      unitPrice: row.unitPrice,
      shippedBy: row.shippedBy,
      voucherNumber: row.voucherNumber,
      remark: row.remark
    };
    this.details.push(newDetail);
  });

  // 返回错误信息，供提交方法使用
  return errorMessages;
},

// 提交方法：集成精准提示
handleSubmit() {
  // 1. 校验物料ID
  if (!this.form.materialId?.trim()) {
    this.$message.error('请先选择物料ID');
    return;
  }

  // 2. 校验表单基础项
  this.$refs.detailForm.validate(async (valid) => {
    if (!valid) {
      this.$message.error('表单校验失败，请检查必填项');
      return;
    }

    console.log("syncDetails前", this.details);
    // 执行明细校验，接收错误信息
    const detailErrors = this.syncDetails(true);
    console.log("syncDetails后", this.details);

    // 3. 提示有值但不合规的字段
    if (detailErrors.length > 0) {
      this.$message.error({
        title: '明细数据校验失败',
        message: detailErrors.join('<br/>'),
        dangerouslyUseHTMLString: true,
        duration: 15000,
        showClose: true
      });
      return;
    }

    // 4. 兜底：有实际数量的行都校验通过，但无有效行（比如实际数量都<1）
    if (this.details.length === 0) {
      this.$message.error('无有效明细数据，请检查实际数量及相关字段');
      return;
    }

    // 5. 组装提交数据
    const submitDetails = this.details.map(detail => ({
      ...detail,
      materialName: this.form.materialName || detail.materialName,
      outboundOrderId: this.form.outboundOrderId || detail.outboundOrderId,
      materialId: this.form.materialId || detail.materialId
    }));
    
    console.log('提交的明细数据：', submitDetails);
    
    this.$emit('submit', submitDetails);
    this.$emit('update:open', false);
  });
},
    removeDetail(row) {
      this.details = this.details.filter(d => d.inventoryId !== row.inventoryId);
      const inventoryRow = this.inventoryList.find(item => item.inventoryId === row.inventoryId);
      if (inventoryRow) {
        this.$set(inventoryRow, 'actualQuantity', null);
        this.$set(inventoryRow, 'plannedQuantity', null);
        this.$set(inventoryRow, 'divisor', null);
        this.$set(inventoryRow, 'labelColor', '');
        this.$set(inventoryRow, 'unitPrice', null);
        this.$set(inventoryRow, 'shippedBy', '');
        this.$set(inventoryRow, 'voucherNumber', '');
        this.$set(inventoryRow, 'remark', '');
        if (this.currentSelectedRowId === row.inventoryId) {
          this.currentSelectedRowId = this.inventoryList.length > 0 ? this.inventoryList[0].inventoryId : null;
        }
      }
      this.syncDetails(this.initDetails.length === 0);
    },
  
    handleClose() {
      this.closeLoading();
      this.$nextTick(() => {
        this.form = this.$options.data().form;
        this.details = [];
        this.inventoryList = [];
        this.selectedMaterialId = '';
        this.selectedMaterialInfo = null;
        this.openMaterialSelector = false;
        this.currentSelectedRowId = null;
        this.isInitEcho = false;
        if (this.$refs.detailForm) {
          this.$refs.detailForm.resetFields();
        }
      });
      this.$emit('update:open', false);
    },
    // 修复：接收selection-change事件参数，兼容多种字段名
    handleMaterialSelectionChange(selectedData) {
      console.log("【物料选择事件触发】选中数据：", selectedData);
      // 兼容数组格式（multiple=false时可能返回对象，需转为数组）
      const selectList = Array.isArray(selectedData) ? selectedData : selectedData ? [selectedData] : [];
      
      if (selectList.length > 0) {
        this.selectedMaterialInfo = selectList[0]; 
        // 关键：兼容常见的物料ID字段名（id/materialId/uuid）
        this.selectedMaterialId = this.selectedMaterialInfo.id || this.selectedMaterialInfo.materialId || this.selectedMaterialInfo.uuid || '';
        // 兼容常见的物料名称字段名（materialName/name）
        this.$set(this.form, 'materialName', this.selectedMaterialInfo.materialName || this.selectedMaterialInfo.name || '');
        console.log("【物料选择成功】ID:", this.selectedMaterialId, "名称:", this.form.materialName);
      } else {
        this.selectedMaterialInfo = null;
        this.selectedMaterialId = '';
        this.$set(this.form, 'materialName', '');
        console.log("【物料选择清空】");
      }
    },
    // 修复：增强校验逻辑，增加组件存在性检查和异步同步
    confirmMaterialSelect() {
      // 1. 检查选择器组件是否存在
      if (!this.$refs.materialsSeletor) {
        this.$message.error('物料选择器组件加载失败，请重试');
        return;
      }

      // 2. 异步等待组件数据同步（避免取值过早）
      this.$nextTick(() => {
        // 3. 强制触发选中数据同步
        const selector = this.$refs.materialsSeletor;
        let selectedData = [];
        // 兼容组件的多种取值方式
        if (selector.getSelectedMaterials) {
          selectedData = selector.getSelectedMaterials();
        } else if (selector.selectedList) {
          selectedData = selector.selectedList;
        } else if (selector.value) {
          selectedData = selector.value;
        }
        // 触发数据同步（覆盖事件未触发的场景）
        this.handleMaterialSelectionChange(selectedData);

        // 4. 增强空值校验
        if (!this.selectedMaterialInfo || !this.selectedMaterialId) {
          this.$message.warning('请选择物料后再确认');
          return;
        }

        // 5. 容错处理：确保物料ID有效
        const materialId = this.selectedMaterialInfo.id || this.selectedMaterialInfo.materialId || this.selectedMaterialInfo.uuid || '';
        if (!materialId) {
          this.$message.error('选中的物料缺少有效ID，请重新选择');
          return;
        }

        // 6. 赋值并关闭弹窗
        this.$set(this.form, 'materialId', materialId);
        this.$set(this.form, 'materialUuids', materialId);
        this.openMaterialSelector = false;

        // 7. 查询库存并校验字段
        this.handleMaterialIdChange();
        this.$nextTick(() => {
          this.$refs.detailForm?.validateField('materialId');
        });
      });
    }
  },
  beforeDestroy() {
    this.closeLoading();
  }
};
</script>

<style scoped>
.dialog-footer {
  text-align: center;
}

/deep/ .el-table {
  --el-table-header-text-color: #303133;
  --el-table-row-hover-bg-color: #f8f9fa;
}

/deep/ .el-table th {
  background-color: #f8f9fa;
  font-weight: 600;
}

/deep/ .el-table .el-tag {
  margin: 0;
}

/deep/ .el-table .el-input {
  width: 100px;
}

/deep/ .material-selector-container {
  height: 100%;
  min-height: 500px;
}

/deep/ .el-dialog__wrapper {
  .el-modal__mask {
    pointer-events: auto !important;
  }
  .el-dialog {
    pointer-events: auto !important;
  }
}

/deep/ .el-input.is-disabled {
  background-color: #f5f7fa;
  cursor: not-allowed;
}
/deep/ .el-button.is-disabled {
  cursor: not-allowed;
}
</style>