<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="货物" 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="confirmMaterialSelect"
            :selected-material-codes="form.materialUuids ? [form.materialUuids] : []"
            :multiple="false"
          />
        </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="批次" 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="plannedQuantity" required>
                  <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-col :span="8">
                <el-form-item label="单价" prop="unitPrice" required>
                  <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="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="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="shippedBy">
                  <el-input
                    v-model="currentSelectedRow.shippedBy"
                    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 style="margin: 10px 0;">
        <el-table
          v-if="details.length > 0"
          :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="批次" 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-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 {
      orderId: this.ordersId || this.outboundOrderId || '',
      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,
      isUserInitiatedSelect: false
    };
  },
  computed: {
    currentSelectedRow() {
      console.log('【computed currentSelectedRow】', {
        currentSelectedRowId: this.currentSelectedRowId,
        matchRow: this.inventoryList.find(row => row.inventoryId === this.currentSelectedRowId)
      });
      return this.inventoryList.find(row => row.inventoryId === this.currentSelectedRowId) || null;
    },
    isMaterialLocked() {
      const result = this.initDetails.length > 0 || !!this.initForm.materialId;
      console.log('【computed isMaterialLocked】', {
        initDetailsLength: this.initDetails.length,
        initFormMaterialId: this.initForm.materialId,
        result
      });
      return result;
    }
  },
  watch: {
    open: {
      handler(newVal) {
        console.log('【watch open】', { 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)) : [];
          console.log('【open=true 初始化数据】', {
            form: this.form,
            details: this.details,
            initDetails: 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) {
        console.log('【watch initForm】', { 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) {
        console.log('【watch inventoryList】', {
          newValLength: newVal.length,
          isInitEcho: this.isInitEcho,
          open: this.open
        });
        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) {
        console.log('【watch outboundOrderId】', { 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() {
      console.log('【handleMaterialIdChange 开始】', { materialId: this.form.materialId });
      this.closeLoading();
      const materialId = this.form.materialId?.trim() || '';
      if (!materialId) {
        this.inventoryList = [];
        console.log('【handleMaterialIdChange】物料ID为空，清空库存列表');
        return;
      }

      try {
        this.loadingInstance = this.$loading({
          text: '查询中...',
          target: this.$el,
          lock: true,
          background: 'rgba(0, 0, 0, 0.7)'
        });
        console.log("【handleMaterialIdChange】查询参数", {
          materialId: materialId,
          outboundOrderId: this.ordersId
        });
        const params = {
          materialId: materialId,
          outboundOrderId: this.ordersId
        };
        const res = await listInventoryByMaterialId(params);
        console.log('【handleMaterialIdChange】库存接口返回', res);
        if (res.code === 200) {
          this.inventoryList = [];
          (res.rows || []).forEach(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('【handleMaterialIdChange】组装后的库存列表', this.inventoryList);
          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 = [];
        console.error('【handleMaterialIdChange】查询库存异常', error);
      } finally {
        this.$nextTick(() => {
          this.closeLoading();
          // 新增：查询库存后主动同步明细
          this.syncDetails(false);
        });
      }
    },
    initEchoDetails() {
      console.log('【initEchoDetails 开始】', {
        inventoryList: this.inventoryList,
        initDetails: this.initDetails
      });
      if (this.initDetails.length === 0 || this.inventoryList.length === 0) {
        console.log('【initEchoDetails】initDetails或inventoryList为空，跳过回显');
        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', '');
      });

      // 回显initDetails数据
      this.initDetails.forEach((detail, index) => {
        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(`【initEchoDetails】第${index+1}条明细匹配失败`, {
            detailInventoryId: detail.inventoryId,
            detailBatchId: detail.batchId,
            inventoryList: this.inventoryList
          });
          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);
        
        console.log(`【initEchoDetails】第${index+1}条明细回显成功`, targetRow);
      });

      this.syncDetails(false);
      console.log('【initEchoDetails 完成】', { inventoryList: this.inventoryList });
    },
    handleRowClick(row) {
      console.log('【handleRowClick】', { row });
      if (!row) return;
      this.currentSelectedRowId = row.inventoryId;
      // 新增：点击行后同步明细
      this.syncDetails(false);
    },
    handleRowActualQtyInput(row) {
      console.log('【handleRowActualQtyInput】', {
        rowInventoryId: row.inventoryId,
        inputValue: row.actualQuantity,
        availableQty: (row.quantity || 0) - (row.lockedQuantity || 0)
      });
      if (isNaN(row.actualQuantity) || row.actualQuantity === '' || row.actualQuantity === null) {
        this.$set(row, 'actualQuantity', null);
        console.log('【handleRowActualQtyInput】输入值非法，重置为null');
        return;
      }
      const availableQty = (row.quantity || 0) - (row.lockedQuantity || 0);
      if (row.actualQuantity > availableQty) {
        this.$message.warning(`实际数量不能超过可用数量${availableQty}`);
        this.$set(row, 'actualQuantity', availableQty);
        console.log('【handleRowActualQtyInput】实际数量超限，重置为可用数量', availableQty);
      } else if (row.actualQuantity < 1) {
        this.$message.warning('实际数量不能小于1');
        this.$set(row, 'actualQuantity', 1);
        console.log('【handleRowActualQtyInput】实际数量小于1，重置为1');
      }
    },
    handleRowPlannedQtyInput(row) {
      console.log('【handleRowPlannedQtyInput】', {
        rowInventoryId: row.inventoryId,
        inputValue: row.plannedQuantity,
        availableQty: (row.quantity || 0) - (row.lockedQuantity || 0)
      });
      if (isNaN(row.plannedQuantity) || row.plannedQuantity === '' || row.plannedQuantity === null) {
        this.$set(row, 'plannedQuantity', null);
        console.log('【handleRowPlannedQtyInput】输入值非法，重置为null');
        return;
      }
      const availableQty = (row.quantity || 0) - (row.lockedQuantity || 0);
      if (row.plannedQuantity > availableQty) {
        this.$message.warning(`计划数量不能超过可用数量${availableQty}`);
        this.$set(row, 'plannedQuantity', availableQty);
        console.log('【handleRowPlannedQtyInput】计划数量超限，重置为可用数量', availableQty);
      } else if (row.plannedQuantity < 1) {
        this.$message.warning('计划数量不能小于1');
        this.$set(row, 'plannedQuantity', 1);
        console.log('【handleRowPlannedQtyInput】计划数量小于1，重置为1');
      }
    },
    // 核心方法：同步明细（添加完整日志）
    syncDetails(strict = true) {
      console.log('========== syncDetails 开始 ==========', {
        strictMode: strict,
        inventoryListLength: this.inventoryList.length,
        inventoryList: JSON.parse(JSON.stringify(this.inventoryList))
      });
      
      this.details = [];
      const errorMessages = [];
      let validRows = [];

      // 第一步：筛选有实际数量的行
      const rowsWithActualQty = this.inventoryList.filter(row => {
        const hasActualQty = row.actualQuantity !== null && row.actualQuantity !== undefined;
        console.log(`【syncDetails】库存行${row.inventoryId}`, {
          hasActualQty,
          actualQuantity: row.actualQuantity
        });
        return hasActualQty;
      });
      console.log('【syncDetails】筛选出有实际数量的行', {
        rowsWithActualQtyLength: rowsWithActualQty.length,
        rowsWithActualQty: rowsWithActualQty
      });

      if (strict && rowsWithActualQty.length > 0) {
        // 严格模式下校验
        validRows = rowsWithActualQty.filter((row, index) => {
          const rowErrors = [];
          const rowName = `第${index + 1}行【${row.materialName || '未知物料'}】(inventoryId:${row.inventoryId})`;
          const availableQty = (row.quantity || 0) - (row.lockedQuantity || 0);

          // 校验实际数量
          if (row.actualQuantity < 1) {
            rowErrors.push('实际数量不能小于1');
          }
          if (row.actualQuantity > availableQty) {
            rowErrors.push(`实际数量不能超过可用库存(${availableQty})`);
          }

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

          // 校验单价
          if (row.unitPrice !== null && row.unitPrice !== undefined) {
            if (row.unitPrice <= 0) {
              rowErrors.push('单价不能小于等于0');
            }
          }

          // 记录当前行的校验结果
          if (rowErrors.length > 0) {
            errorMessages.push(`${rowName}：${rowErrors.join('、')}`);
            console.log(`【syncDetails】${rowName} 校验失败`, rowErrors);
            return false;
          }
          console.log(`【syncDetails】${rowName} 校验通过`);
          return true;
        });
      } else {
        // 非严格模式：直接使用有实际数量的行
        validRows = rowsWithActualQty;
        console.log('【syncDetails】非严格模式，直接使用有实际数量的行', validRows);
      }

      // 填充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);
      });

      console.log('========== syncDetails 结束 ==========', {
        errorMessages,
        validRowsLength: validRows.length,
        finalDetailsLength: this.details.length,
        finalDetails: this.details
      });

      return errorMessages;
    },
    // 提交方法（添加完整日志）
    handleSubmit() {
      console.log('========== handleSubmit 开始 ==========');
      // 1. 校验物料ID
      if (!this.form.materialId?.trim()) {
        this.$message.error('请先选择物料ID');
        console.log('【handleSubmit】物料ID为空，提交失败');
        return;
      }

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

        console.log('【handleSubmit】基础表单校验通过，开始同步明细');
        // 执行明细校验
        const detailErrors = this.syncDetails(true);

        // 3. 提示校验错误
        if (detailErrors.length > 0) {
          this.$message.error({
            title: '明细数据校验失败',
            message: detailErrors.join('<br/>'),
            dangerouslyUseHTMLString: true,
            duration: 15000,
            showClose: true
          });
          console.log('【handleSubmit】明细校验失败', detailErrors);
          return;
        }

        // 4. 检查是否有有效明细
        if (this.details.length === 0) {
          this.$message.error('无有效明细数据，请检查实际数量及相关字段');
          console.log('【handleSubmit】无有效明细数据', {
            detailsLength: this.details.length,
            inventoryList: this.inventoryList
          });
          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('【handleSubmit】提交明细数据', submitDetails);

        this.$emit('submit', submitDetails);
        this.$emit('update:open', false);
        console.log('========== handleSubmit 完成 ==========');
      });
    },
    removeDetail(row) {
      console.log('【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);
      console.log('【removeDetail 完成】', { details: this.details });
    },
    handleClose() {
      console.log('【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);
    },
    handleMaterialSelectionChange(selectedData) {
      console.log('【handleMaterialSelectionChange】', { selectedData });
      // 兼容数组格式
      const selectList = Array.isArray(selectedData) ? selectedData : selectedData ? [selectedData] : [];

      if (selectList.length > 0) {
        this.selectedMaterialInfo = selectList[0];
        this.selectedMaterialId = this.selectedMaterialInfo.id || this.selectedMaterialInfo.materialId || this.selectedMaterialInfo.uuid || '';
        this.$set(this.form, 'materialName', this.selectedMaterialInfo.materialName || this.selectedMaterialInfo.name || '');
        console.log('【handleMaterialSelectionChange】物料选择成功', {
          selectedMaterialId: this.selectedMaterialId,
          materialName: this.form.materialName
        });
      } else {
        this.selectedMaterialInfo = null;
        this.selectedMaterialId = '';
        this.$set(this.form, 'materialName', '');
        console.log('【handleMaterialSelectionChange】物料选择清空');
      }
    },
    confirmMaterialSelect() {
      console.log('【confirmMaterialSelect】开始');
      this.isUserInitiatedSelect = true;

      // 1. 检查选择器组件是否存在
      if (!this.$refs.materialsSeletor) {
        this.$message.error('物料选择器组件加载失败，请重试');
        console.error('【confirmMaterialSelect】物料选择器组件不存在');
        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;
        }
        console.log('【confirmMaterialSelect】从选择器获取数据', selectedData);
        // 触发数据同步
        this.handleMaterialSelectionChange(selectedData);

        // 5. 容错处理：确保物料ID有效
        const materialId = this.selectedMaterialInfo.id || this.selectedMaterialInfo.materialId || this.selectedMaterialInfo.uuid || '';

        // 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');
        });

        // 重置标记
        this.isUserInitiatedSelect = false;
        console.log('【confirmMaterialSelect】完成');
      });
    }
  },
  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>