<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.materialId"
              placeholder="请选择或输入货物ID"
              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-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-form-item>
        </el-col>
      </el-row>

      <!-- 库存信息列表 - 添加库存ID列和单价列 -->
      <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.id"
          >
            <el-table-column prop="materialId" label="货物ID" width="120" />
            <el-table-column prop="batchId" label="批次ID" width="120" />
            <el-table-column prop="outboundOrderId" label="出库单号" width="120" />
            <el-table-column prop="warehouseId" label="仓库ID" width="120" />
            <el-table-column prop="locationId" label="库位ID" width="110" />
            <el-table-column
              prop="inventoryType"
              label="库存类型"
              width="100"
            >
              <template slot-scope="scope">
                <el-tag size="mini" :type="scope.row.inventoryType === 1 ? 'primary' : 'success'">
                  {{ scope.row.inventoryType === 1 ? '正品' : '次品' }}
                </el-tag>
              </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">
              <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="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="24">
                <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>

      <!-- 已生成的明细预览 - 添加库存ID列和单价列 -->
      <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="inventoryId" label="库存ID" width="100" />
            <el-table-column prop="batchId" label="批次ID" />
            <el-table-column prop="warehouseId" label="仓库ID" />
            <el-table-column prop="locationId" label="库位ID" />
            <el-table-column prop="plannedQuantity" label="计划数量" />
            <el-table-column prop="actualQuantity" label="实际数量" />
            <el-table-column prop="unitPrice" label="单价" />
            <el-table-column prop="divisor" label="约数" />
            <el-table-column prop="labelColor" label="标签颜色">
              <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="凭证号" />
            <el-table-column prop="shippedBy" label="发货方" />
            <el-table-column prop="remark" label="备注" />
            <el-table-column label="操作" width="80">
              <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'],
  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: () => ({})
    }
  },
  data() {
    return {
      form: {
        materialUuids: '',
        materialId: '',
        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.id === 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,
            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)) : [];
          if (this.form.materialId && this.form.materialId.trim()) {
            this.handleMaterialIdChange();
          }
        } 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,
            outboundOrderId: this.outboundOrderId || val.outboundOrderId || ''
          };
          const oldMaterialId = this.selectedMaterialId;
          this.selectedMaterialId = this.form.materialId || '';
          this.currentSelectedRowId = null;
          if (this.form.materialId && this.form.materialId.trim() && this.form.materialId !== oldMaterialId) {
            this.handleMaterialIdChange();
          }
        }
      },
      immediate: true,
      deep: true
    },
    inventoryList: {
      handler(newVal) {
        if (this.open && newVal.length > 0 && !this.isInitEcho) {
          this.initEchoDetails();
          this.isInitEcho = true;
          if (!this.currentSelectedRowId) {
            this.currentSelectedRowId = newVal[0].id;
          }
        }
      },
      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)'
        });
        const params = {
          materialId: materialId,
          outboundOrderId: this.form.outboundOrderId
        };
        const res = await listInventoryByMaterialId(params);
        if (res.code === 200) {
          this.inventoryList = [];
          (res.rows || []).forEach(item => {
            const newRow = {
              id: item.id,
              materialId: item.materialId || materialId,
              batchId: item.batchId || '',
              outboundOrderId: item.outboundOrderId || this.form.outboundOrderId,
              warehouseId: item.warehouseId || '',
              locationId: item.locationId || '',
              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.$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() {
      if (this.initDetails.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, 'shippedAt', '');
        this.$set(row, 'voucherNumber', '');
        this.$set(row, 'remark', '');
      });

      // 重新赋值所有明细
      this.initDetails.forEach(detail => {
        const targetRow = this.inventoryList.find(row => row.id === detail.inventoryId);
        if (targetRow) {
          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, 'shippedAt', detail.shippedAt ?? '');
          this.$set(targetRow, 'voucherNumber', detail.voucherNumber ?? '');
          this.$set(targetRow, 'remark', detail.remark ?? '');
        }
      });

      this.syncDetails(false);
    },
    handleRowClick(row) {
      if (!row) return;
      this.currentSelectedRowId = row.id;
    },
    handleRowActualQtyInput(row) {
      if (isNaN(row.actualQuantity) || row.actualQuantity === '') {
        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 === '') {
        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(strict = true) {
      this.details = [];

      let validRows = [];
      if (strict) {
        validRows = this.inventoryList.filter(row => {
          const availableQty = (row.quantity || 0) - (row.lockedQuantity || 0);
          // 修复：允许0值（但需大于0），同时确保必填字段不为空
          return row.actualQuantity !== null &&
                 row.actualQuantity !== undefined &&
                 row.actualQuantity >= 1 &&
                 row.actualQuantity <= availableQty &&
                 row.plannedQuantity !== null &&
                 row.divisor !== null &&
                 row.labelColor !== '' &&
                 row.voucherNumber !== '' &&
                 row.shippedBy !== '';
        });
      } else {
        validRows = this.inventoryList.filter(row => {
          return row.actualQuantity !== null ||
                 row.plannedQuantity !== null ||
                 row.divisor !== null ||
                 row.labelColor !== '' ||
                 row.unitPrice !== null ||
                 row.shippedBy !== '' ||
                 row.shippedAt !== '' ||
                 row.voucherNumber !== '' ||
                 row.remark !== '';
        });
      }

      // 修复：确保每条明细都有唯一标识
      validRows.forEach(row => {
        const newDetail = {
          inventoryId: row.id,
          materialId: row.materialId || this.form.materialId,
          batchId: row.batchId || row.batchCode || '',
          warehouseId: row.warehouseId || '',
          locationId: row.locationId || '',
          outboundOrderId: this.form.outboundOrderId || '',
          plannedQuantity: row.plannedQuantity,
          actualQuantity: row.actualQuantity,
          divisor: row.divisor,
          labelColor: row.labelColor,
          unitPrice: row.unitPrice,
          shippedBy: row.shippedBy,
          shippedAt: row.shippedAt,
          voucherNumber: row.voucherNumber,
          remark: row.remark
        };
        this.details.push(newDetail);
      });
    },
    removeDetail(row) {
      this.details = this.details.filter(d => d.inventoryId !== row.inventoryId);
      const inventoryRow = this.inventoryList.find(item => item.id === 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, 'shippedAt', '');
        this.$set(inventoryRow, 'voucherNumber', '');
        this.$set(inventoryRow, 'remark', '');
        if (this.currentSelectedRowId === row.inventoryId) {
          this.currentSelectedRowId = this.inventoryList.length > 0 ? this.inventoryList[0].id : null;
        }
      }
      this.syncDetails(this.initDetails.length === 0);
    },
    // 修复：提交逻辑 - 确保严格模式同步后再提交
    handleSubmit() {
      if (!this.form.materialId?.trim()) {
        this.$message.error('请先选择物料ID');
        return;
      }

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

        // 强制严格模式同步
        this.syncDetails(true);

        if (this.details.length === 0) {
          this.$message.error('请填写实际数量并完善所有必填明细信息');
          return;
        }

        // 移除重复的校验逻辑（已在syncDetails中处理）
        const submitDetails = this.details.map(detail => ({
          ...detail,
          outboundOrderId: this.form.outboundOrderId || detail.outboundOrderId,
          materialId: this.form.materialId || detail.materialId
        }));
        
        // 调试：打印提交的数据
        console.log('提交的明细数据：', submitDetails);
        
        this.$emit('submit', submitDetails);
        this.$emit('update:open', false);
      });
    },
    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() {
      // 核心修改：将物料选择器返回的sap_no作为物料ID
      const selectedData = this.$refs.materialsSeletor?.getSelectedMaterials?.() || this.$refs.materialsSeletor?.selectedList || [];
      if (selectedData && selectedData.length > 0) {
        this.selectedMaterialInfo = selectedData[0];
        // 替换：使用sapNo作为物料ID
        this.selectedMaterialId = this.selectedMaterialInfo.sapNo || this.selectedMaterialInfo.materialId || '';
        console.log("选中的SAP物料号:", this.selectedMaterialId);
      } else {
        this.selectedMaterialInfo = null;
        this.selectedMaterialId = '';
      }
    },
    // 修复：物料选择后的数据赋值 - 核心替换为sap_no
    confirmMaterialSelect() {
      this.handleMaterialSelectionChange();
      if (!this.selectedMaterialId) {
        this.$message.warning('请选择物料后再确认');
        return;
      }

      // 核心修改：将sapNo赋值给materialId和materialUuids
      this.$set(this.form, 'materialId', this.selectedMaterialInfo.sapNo || this.selectedMaterialId);
      this.$set(this.form, 'materialUuids', this.selectedMaterialInfo.sapNo || this.selectedMaterialId);

      this.openMaterialSelector = false;
      this.handleMaterialIdChange();
      this.$nextTick(() => {
        if (this.$refs.detailForm) {
          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>