<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">
      <!-- 通用信息：保留货物ID、计划总数量（全局字段） -->
      <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="openMaterialSelector = true"
              style="cursor: pointer"
            >
              <template slot="suffix">
                <el-button
                  icon="el-icon-search"
                  size="mini"
                  @click.native="openMaterialSelector = true"
                ></el-button>
              </template>
            </el-input>
            <!-- 物料选择器弹窗 -->
            <el-dialog
              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="true"
                />
              </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-col :span="12">
          <el-form-item label="计划总数量" prop="totalPlannedQuantity">
            <el-input
              v-model.number="form.totalPlannedQuantity"
              placeholder="请输入计划总数量"
              type="number"
              min="1"
            />
          </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="id" label="库存ID" width="100" /> 
            <el-table-column prop="materialId" label="货物ID" width="100" />
            <el-table-column prop="batchId" label="批次ID" width="100" />
            <el-table-column prop="orderId" label="订单ID" width="120" />
            <el-table-column prop="warehouseId" label="仓库ID" width="100" />
            <el-table-column prop="locationId" label="库位ID" width="100" />
            <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()"
                  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()"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="标签颜色" prop="labelColor">
                  <el-select v-model="currentSelectedRow.labelColor" placeholder="请选择标签颜色" @change="syncDetails()">
                    <el-option label="红色" value="1"></el-option>
                    <el-option label="蓝色" value="2"></el-option>
                    <el-option label="绿色" value="3"></el-option>
                    <el-option label="黄色" value="4"></el-option>
                  </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()"
                    placeholder="输入计划数量"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20" style="margin-top: 10px;">
              <el-col :span="12">
                <el-form-item label="发货方" prop="shippedBy">
                  <el-input
                    v-model="currentSelectedRow.shippedBy"
                    placeholder="请输入发货方"
                    @input="syncDetails()"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20" style="margin-top: 10px;">
              <el-col :span="24">
                <el-form-item label="凭证号" prop="voucherNumber">
                  <el-input
                    v-model="currentSelectedRow.voucherNumber"
                    placeholder="请输入凭证号"
                    @input="syncDetails()"
                  />
                </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()"
                  />
                </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="batchCode" 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="divisor" label="约数" />
            <el-table-column prop="labelColor" label="标签颜色">
              <template slot-scope="scope">
                {{ getLabelColorText(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',
  components: {
    MaterialSelector
  },
  props: {
    title: {
      type: String,
      default: '新增明细项'
    },
    open: {
      type: Boolean,
      default: false
    },
    initForm: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      form: {
        materialUuids: '',
        materialId: '',
        totalPlannedQuantity: null,
        itemStatus: 1 
      },
      details: [], 
      inventoryList: [],
      loadingInstance: null,
      rules: {
        materialId: [{ 
          required: true, 
          message: '请选择货物ID', 
          trigger: ['change', 'blur']
        }]
      },
      openMaterialSelector: false,
      selectedMaterialId: '',
      selectedMaterialInfo: null,
      currentSelectedRow: null 
    }
  },
  created() {
    this.debounceMaterialIdChange = debounce(this.handleMaterialIdChange.bind(this), 500)
  },
  watch: {
    open: {
      handler(newVal) {
        if (newVal) {
          this.form = { ...this.$options.data().form, ...this.initForm }
          this.selectedMaterialId = this.form.materialId || ''
          this.selectedMaterialInfo = null
          this.currentSelectedRow = null
          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 }
          this.selectedMaterialId = this.form.materialId || ''
          this.selectedMaterialInfo = null
          this.currentSelectedRow = null
          if (this.form.materialId && this.form.materialId.trim()) {
            this.handleMaterialIdChange()
          }
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    getLabelColorText(value) {
      const colorMap = {
        '1': '红色',
        '2': '蓝色',
        '3': '绿色',
        '4': '黄色'
      }
      return colorMap[value] || '-'
    },
    closeLoading() {
      if (this.loadingInstance) {
        this.loadingInstance.close()
        this.loadingInstance = null
      }
    },
    async handleMaterialIdChange() {
  const materialId = this.form.materialId?.trim() || ''; // 增加分号，避免解析错误
  if (!materialId) {
    this.inventoryList = [];
    this.closeLoading();
    return;
  }
  try {
    this.loadingInstance = this.$loading({
      text: '查询中...',
      target: this.$el,
      lock: true,
      background: 'rgba(0, 0, 0, 0.7)'
    });
    const res = await listInventoryByMaterialId(materialId); // 增加分号
    if (res.code === 200) {
      // 按库存ID去重（修复语法：确保Map操作正确）
      const uniqueInventoryMap = new Map();
      (res.rows || []).forEach(item => {
        if (!uniqueInventoryMap.has(item.id)) {
          uniqueInventoryMap.set(item.id, item);
        }
      });
      const uniqueRows = Array.from(uniqueInventoryMap.values()); // 增加分号
      
      this.inventoryList = uniqueRows.map(item => ({ 
        ...item, 
        actualQuantity: null,       
        plannedQuantity: null,      
        divisor: null,              
        labelColor: '',             
        unitPrice: null,            
        shippedAt: '',              
        shippedBy: '',              
        voucherNumber: '',          
        remark: '',                 
        quantity: item.quantity || 0,
        lockedQuantity: item.lockedQuantity || 0,
        batchCode: item.batchId || '' 
      })); // 增加分号
      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.closeLoading();
  }
},
    handleRowClick(row) {
      if (!row) return
      this.currentSelectedRow = row
    },
    handleRowActualQtyInput(row) {
      if (isNaN(row.actualQuantity) || row.actualQuantity === '') {
        row.actualQuantity = null
        return
      }
      const availableQty = (row.quantity || 0) - (row.lockedQuantity || 0)
      if (row.actualQuantity > availableQty) {
        this.$message.warning(`实际数量不能超过可用数量${availableQty}`)
        row.actualQuantity = availableQty
      } else if (row.actualQuantity < 1) {
        this.$message.warning('实际数量不能小于1')
        row.actualQuantity = 1
      }

      // 核心改造1：清空其他行的实际数量，确保仅当前行有值
      this.inventoryList.forEach(item => {
        if (item.id !== row.id) {
          item.actualQuantity = null
          item.plannedQuantity = null
          item.divisor = null
          item.labelColor = ''
          item.shippedBy = ''
          item.voucherNumber = ''
          item.remark = ''
        }
      })
    },
    handleRowPlannedQtyInput(row) {
      if (isNaN(row.plannedQuantity) || row.plannedQuantity === '') {
        row.plannedQuantity = null
        return
      }
      const availableQty = (row.quantity || 0) - (row.lockedQuantity || 0)
      if (row.plannedQuantity > availableQty) {
        this.$message.warning(`计划数量不能超过可用数量${availableQty}`)
        row.plannedQuantity = availableQty
      } else if (row.plannedQuantity < 1) {
        this.$message.warning('计划数量不能小于1')
        row.plannedQuantity = 1
      }
    },
    syncDetails() {
      // 核心修复2：先清空明细，避免重复累加
      this.details = []
      // 过滤出仅填写了实际数量的行（此时最多只有一行）
      const validRow = this.inventoryList.find(row => {
        if (row.actualQuantity === null || row.actualQuantity === '' || isNaN(row.actualQuantity)) return false
        const availableQty = (row.quantity || 0) - (row.lockedQuantity || 0)
        return row.actualQuantity <= availableQty && row.actualQuantity >= 1
      })

      if (validRow) {
        const newDetail = {
          inventoryId: validRow.id, // 确保库存ID唯一
          materialId: this.form.materialId,
          batchCode: validRow.batchCode || '',       
          warehouseId: validRow.warehouseId || '',
          locationId: validRow.locationId || '',
          plannedQuantity: Number(validRow.plannedQuantity),
          actualQuantity: Number(validRow.actualQuantity),
          divisor: Number(validRow.divisor) || 0,
          labelColor: Number(validRow.labelColor) || 0,
          unitPrice: Number(validRow.unitPrice) || 0,
          voucherNumber: validRow.voucherNumber || '',
          itemStatus: Number(this.form.itemStatus) || 1,
          shippedAt: validRow.shippedAt,
          shippedBy: validRow.shippedBy,
          remark: validRow.remark || '',
          isUsed: 1,
          sortNo: 0
        }
        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) {
        inventoryRow.actualQuantity = null
        inventoryRow.plannedQuantity = null
        inventoryRow.divisor = null
        inventoryRow.labelColor = ''
        inventoryRow.unitPrice = null
        inventoryRow.shippedAt = ''
        inventoryRow.shippedBy = ''
        inventoryRow.voucherNumber = ''
        inventoryRow.remark = ''
        if (this.currentSelectedRow && this.currentSelectedRow.id === row.inventoryId) {
          this.currentSelectedRow = null
        }
      }
    },
    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()

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

        // 核心改造3：兜底校验 - 检查是否存在重复的inventoryId（防御性编程）
        const inventoryIds = this.details.map(d => d.inventoryId)
        const uniqueInventoryIds = [...new Set(inventoryIds)]
        if (uniqueInventoryIds.length !== inventoryIds.length) {
          this.$message.error('发现重复的库存ID明细，请重新选择！')
          return
        }

        let hasError = false
        this.details.forEach(detail => {
          const row = this.inventoryList.find(r => r.id === detail.inventoryId)
          if (!row) return
          if (row.divisor === null && row.divisor !== 0) {
            this.$message.warning(`库存ID:${row.id} 请填写约数`)
            hasError = true
          }
          if (!row.labelColor) {
            this.$message.warning(`库存ID:${row.id} 请选择标签颜色`)
            hasError = true
          }
          if (!row.voucherNumber) {
            this.$message.warning(`库存ID:${row.id} 请填写凭证号`)
            hasError = true
          }
          if (!row.shippedBy) {
            this.$message.warning(`库存ID:${row.id} 请填写发货方`)
            hasError = true
          }
          if (!row.plannedQuantity) {
            this.$message.warning(`库存ID:${row.id} 请填写计划数量`)
            hasError = true
          }
          if (!row.actualQuantity) {
            this.$message.warning(`库存ID:${row.id} 请填写实际数量`)
            hasError = true
          }
        })
        if (hasError) return

        const totalActual = this.details.reduce((sum, d) => sum + (d.actualQuantity || 0), 0)
        if (this.form.totalPlannedQuantity && this.form.totalPlannedQuantity !== totalActual) {
          try {
            await this.$confirm(
              `实际总数量(${totalActual})与计划总数量(${this.form.totalPlannedQuantity})不一致，是否继续提交？`,
              '提示',
              {
                confirmButtonText: '继续',
                cancelButtonText: '取消',
                type: 'warning'
              }
            )
          } catch (e) {
            return
          }
        }
        this.$emit('submit', this.details)
        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.currentSelectedRow = null
        if (this.$refs.detailForm) {
          this.$refs.detailForm.resetFields()
        }
      })
      this.$emit('update:open', false)
    },
    handleMaterialSelectionChange() {
      const selectedData = this.$refs.materialsSeletor?.getSelectedMaterials?.() || this.$refs.materialsSeletor?.selectedList || []
      if (selectedData && selectedData.length > 0) {
        this.selectedMaterialInfo = selectedData[0]
        this.selectedMaterialId = this.selectedMaterialInfo || ''
      } else {
        this.selectedMaterialInfo = null
        this.selectedMaterialId = ''
      }
    },
    confirmMaterialSelect() {
      this.handleMaterialSelectionChange()
      if (!this.selectedMaterialId) {
        this.$message.warning('请选择物料后再确认')
        return
      }
      
      this.$set(this.form, 'materialId', this.selectedMaterialId)
      this.$set(this.form, 'materialUuids', this.selectedMaterialInfo.materialCode || 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;
  }
}
</style>