<template>
  <!-- 添加或修改入库单明细对话框 -->
  <el-dialog :title="title" v-model="open" width="600px" append-to-body>
    <el-form ref="wmsInboundOrderItemRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="物资" prop="materialId">
        <el-input v-model="form.materialName" placeholder="请输入物资名称" disabled />
      </el-form-item>
      <el-form-item label="实际数量" prop="actualQuantity">
        <el-input v-model="form.actualQuantity" placeholder="请输入实际数量" @change="calculateAmount" />
      </el-form-item>
      <el-form-item label="计量单位" prop="unit">
        <el-input v-model="form.unit" placeholder="请输入计量单位" disabled />
      </el-form-item>
      <el-form-item label="单价" prop="unitPrice">
        <el-input v-model="form.unitPrice" placeholder="请输入单价" @change="calculateAmount" />
      </el-form-item>
      <el-form-item label="金额" prop="amount">
        <el-input v-model="form.amount" placeholder="请输入金额" disabled />
      </el-form-item>
      <el-form-item label="批次号" prop="batchNo">
        <el-input v-model="form.batchNo" placeholder="请输入批次号" />
      </el-form-item>
      <el-form-item label="生产日期" prop="productionDate">
        <el-date-picker clearable v-model="form.productionDate" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择生产日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="失效日期" prop="expirationDate">
        <el-date-picker clearable v-model="form.expirationDate" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择失效日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="货架" prop="locationId">
        <LocationCascaderSelect
          class="w-full"
          :model-value="{ warehouseId: form.warehouseId, areaId: form.areaId, locationId: form.locationId }"
          @update:model-value="(value) => {
            if (value.locationId) {
              // 检查是否有其他行使用了相同的locationId（这里是单行，所以不需要检查）
            }
            form.warehouseId = value.warehouseId;
            form.areaId = value.areaId;
            form.locationId = value.locationId;
          }" />
      </el-form-item>
      <el-form-item label="PTL标签" prop="storageLocation">
        <el-input v-model="form.storageLocation" placeholder="请选择PTL标签" readonly >
          <template #append>
            <el-button slot="append" type="primary" size="small" @click="openPtlTagSelect">选择</el-button>
          </template>
        </el-input>
        
      </el-form-item>
      <el-form-item label="RFID标签" prop="rfidTagIds">
        <el-input v-model="form.rfidTagCodes" placeholder="请选择RFID标签" readonly >
          <template #append>
            <el-button slot="append" type="primary" size="small" @click="openRfidTagSelect">选择</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>

    <!-- RFID标签选择对话框组件 -->
    <RfidTagSelectDialog ref="rfidTagSelectDialogRef" v-model:visible="rfidTagDialogVisible" title="选择RFID标签"
      @confirm="handleRfidTagConfirm" />

    <!-- PTL标签选择对话框组件 -->
    <PtlTagSelectDialog ref="ptlTagSelectDialogRef" v-model:visible="ptlTagDialogVisible" title="选择PTL标签"
      @confirm="handlePtlTagConfirm" />
  </el-dialog>
</template>

<script setup name="WmsInboundOrderItem">
import { ref, reactive, toRefs, getCurrentInstance } from "vue"
import { getWmsInboundOrderItem } from "@/api/ware/wmsInboundOrderItem"
import { generateBatchNo } from "@/api/ware/codeGenerator" // 假设批次号生成接口在这个文件中
import LocationCascaderSelect from "@/components/LocationCascaderSelect.vue"
import RfidTagSelectDialog from "@/components/RfidTagSelectDialog.vue"
import PtlTagSelectDialog from "@/components/PtlTagSelectDialog.vue"

const { proxy } = getCurrentInstance()

const open = ref(false)
const ids = ref([])
const title = ref("")

// RFID标签选择对话框状态
const rfidTagDialogVisible = ref(false)
const rfidTagSelectDialogRef = ref(null)
// PTL标签选择对话框状态
const ptlTagDialogVisible = ref(false)
const ptlTagSelectDialogRef = ref(null)

const emit = defineEmits(['submit'])

const data = reactive({
  form: {
    itemId: null,
    orderId: null,
    materialId: null,
    materialName: null,
    planQuantity: null,
    actualQuantity: null,
    unit: null,
    unitPrice: null,
    amount: null,
    batchNo: null,
    productionDate: null,
    expirationDate: null,
    qualityStatus: null,
    checkQuantity: null,
    unqualifiedQuantity: null,
    unqualifiedReason: null,
    storageLocation: null,
    putawayStatus: null,
    remark: null,
    warehouseId: null,
    areaId: null,
    locationId: null,
    rfidTagIds: null,
    rfidTagCodes: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderId: null,
    materialId: null,
    planQuantity: null,
    actualQuantity: null,
    unit: null,
    unitPrice: null,
    amount: null,
    batchNo: null,
    productionDate: null,
    expirationDate: null,
    qualityStatus: null,
    checkQuantity: null,
    unqualifiedQuantity: null,
    unqualifiedReason: null,
    storageLocation: null,
    putawayStatus: null,
  },
  rules: {
    orderId: [
      { required: true, message: "入库单ID不能为空", trigger: "blur" }
    ],
    materialId: [
      { required: true, message: "物资ID不能为空", trigger: "blur" }
    ],
    planQuantity: [
      { required: true, message: "计划数量不能为空", trigger: "blur" }
    ],
    actualQuantity: [
      { required: true, message: "实际数量不能为空", trigger: "blur" }
    ],
    unit: [
      { required: true, message: "计量单位不能为空", trigger: "blur" }
    ],
    unitPrice: [
      { required: true, message: "单价不能为空", trigger: "blur" }
    ],
    amount: [
      { required: true, message: "金额不能为空", trigger: "blur" }
    ],
    batchNo: [
      { required: true, message: "批次号不能为空", trigger: "blur" }
    ],
    productionDate: [
      { required: true, message: "生产日期不能为空", trigger: "blur" }
    ],
    expirationDate: [
      { required: true, message: "过期日期不能为空", trigger: "blur" }
    ],
    warehouseId: [
      { required: true, message: "仓库ID不能为空", trigger: "blur" }
    ],
    areaId: [
      { required: true, message: "库区ID不能为空", trigger: "blur" }
    ],
    locationId: [
      { required: true, message: "存储位置ID不能为空", trigger: "blur" }
    ],
    rfidTagIds: [
      { required: true, message: "RFID标签ID不能为空", trigger: "blur" }
    ],
  }
})

const { form, rules } = toRefs(data)

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    itemId: null,
    orderId: null,
    materialId: null,
    planQuantity: null,
    actualQuantity: null,
    unit: null,
    unitPrice: null,
    amount: null,
    batchNo: null,
    productionDate: null,
    expirationDate: null,
    qualityStatus: null,
    checkQuantity: null,
    unqualifiedQuantity: null,
    unqualifiedReason: null,
    storageLocation: null,
    putawayStatus: null,
    remark: null
  }
  proxy.resetForm("wmsInboundOrderItemRef")
}

/** 新增按钮操作 */
function handleAdd(inBoundOrderItemDetail) {
  reset()
  open.value = true
  title.value = "执行入库"

  // 填充物资信息
  if (inBoundOrderItemDetail) {
    form.value.orderId = inBoundOrderItemDetail.orderId
    form.value.materialId = inBoundOrderItemDetail.materialId || inBoundOrderItemDetail.wmsMaterial?.materialId
    form.value.materialName = inBoundOrderItemDetail.materialName || inBoundOrderItemDetail.wmsMaterial?.materialName
    form.value.unit = inBoundOrderItemDetail.unit
    form.value.unitPrice = inBoundOrderItemDetail.unitPrice
    form.value.actualQuantity = inBoundOrderItemDetail.planQuantity // 默认实际数量等于计划数量

    generateBatchNo().then(response => {
      form.value.batchNo = response.msg
    }).catch(error => {
      proxy.$message.error('批次号生成失败：' + error.message)
    })

    // 计算金额
    calculateAmount()
  }
}

/** 计算金额（数量 * 单价） */
function calculateAmount() {
  if (form.value && form.value.actualQuantity !== undefined && form.value.unitPrice !== undefined) {
    // 确保数量和单价都是数字
    const quantity = parseFloat(form.value.actualQuantity) || 0;
    const unitPrice = parseFloat(form.value.unitPrice) || 0;
    // 计算金额，保留2位小数
    form.value.amount = parseFloat((quantity * unitPrice).toFixed(2));
  }
}

/** 打开RFID标签选择对话框 */
function openRfidTagSelect() {
  rfidTagDialogVisible.value = true
}

/** 处理RFID标签选择确认 */
function handleRfidTagConfirm(selectedTags) {
  const selectedTagIds = selectedTags.map(tag => tag.tagId).join(',')
  const selectedTagCodes = selectedTags.map(tag => tag.tagCode).join(',')

  form.value.rfidTagIds = selectedTagIds
  form.value.rfidTagCodes = selectedTagCodes
}

/** 打开PTL标签选择对话框 */
function openPtlTagSelect() {
  ptlTagDialogVisible.value = true
}

/** 处理PTL标签选择确认 */
function handlePtlTagConfirm(selectedTags) {
  const selectedTagIds = selectedTags.map(tag => tag.antennaId).join(',')

  form.value.storageLocation = selectedTagIds
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _itemId = row.itemId || ids.value
  getWmsInboundOrderItem(_itemId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改入库单明细"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["wmsInboundOrderItemRef"].validate(valid => {
    if (valid) {
      open.value = false
      emit('submit', form.value)
    }
  })
}
defineExpose({
  submitForm,
  handleAdd
})
</script>
