<template>
  <el-dialog :title="'未完工资料查询'" :visible.sync="open" width="1200px" append-to-body>
    <el-form
      :model="queryForm"
      ref="queryForm"
      size="small"
      :inline="true"
      label-width="88px"
      :rules="rules"
    >
      <el-form-item label="生产类型" prop="productionType">
        <el-select v-model="queryForm.productionType" placeholder="请选择生产类型" clearable filterable>
          <el-option
            v-for="item in dict.type.inventory_production_type"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="生产车间" prop="productionPlantNo">
        <el-select v-model="queryForm.productionPlantNo" placeholder="请选择生产车间" clearable filterable>
          <el-option
            v-for="item in productionPlantList"
            :key="item.productionPlantNo"
            :label="item.productionPlantName"
            :value="item.productionPlantNo"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="生产日期" prop="productionDate">
        <el-date-picker
          v-model="queryForm.productionDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择生产日期"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
      </el-form-item>
    </el-form>

    <el-table
      border
      stripe
      :data="list"
      ref="table"
      @selection-change="handleSelectionChange"
      style="width: 100%;"
    >
      <el-table-column type="selection" width="55" align="center" fixed />
      <el-table-column label="生产计划单号" prop="productionPlanNumber" min-width="160" fixed />
      <el-table-column label="物料编码" prop="goodsNum" min-width="120" />
      <el-table-column label="物料名称" prop="materialName" min-width="140" />
      <el-table-column label="规格型号" prop="specificationModel" min-width="120" />
      <el-table-column label="品种种类" prop="varietyCategory" min-width="120" />
      <el-table-column label="品类级别" prop="categoryGrade" min-width="120" />
      <el-table-column label="批次" prop="batchNumber" min-width="100" />
      <el-table-column label="数量" prop="quantity" min-width="110" />
      <el-table-column label="计量单位" prop="measurementUnit" min-width="110" />
      <el-table-column label="辅助数量" prop="auxiliaryQuantity" min-width="120" />
      <el-table-column label="辅助数量单位" prop="auxiliaryMeasurementUnit" min-width="130" />
      <el-table-column label="合格数量" prop="qualifiedQuantity" min-width="120" />
      <el-table-column label="不合格数量" prop="unqualifiedQuantity" min-width="130" />
      <el-table-column label="仓库" prop="warehouse" min-width="120" />
      <el-table-column label="入库数量" prop="warehousingQuantity" min-width="120" />
      <el-table-column label="入库辅助数量" prop="warehousingAuxiliaryQuantity" min-width="140" />
    </el-table>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" :disabled="selected.length === 0" @click="confirm">确 定</el-button>
      <el-button @click="close">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getConventionList } from '../../api/production/convention'
import { getMaterialList } from '../../api/baseInfo/material'
import { getVarietyList } from '../../api/baseInfo/variety'
import { getLevelList } from '../../api/baseInfo/level'

export default {
  name: "UnfinishedDataQueryDialog",
  dicts: ["inventory_production_type"],
  props: {
    productionPlantList: {
      type: Array,
      default: () => [],
    },
    /** complete 页当前选择的生产类型（用于默认填充弹窗查询条件） */
    productionTypeDefault: {
      type: [String, Number, null],
      default: null,
    },
    /** complete 页当前选择的生产车间（用于默认填充弹窗查询条件） */
    productionWorkshopDefault: {
      type: [String, Number, null],
      default: null,
    },
  },
  data() {
    return {
      open: false,
      queryForm: {
        productionType: null,
        productionPlantNo: null,
        productionDate: this.getTomorrowYMD(),
      },
      rules: {
        productionType: [{ required: true, message: "生产类型不能为空", trigger: "change" }],
        productionPlantNo: [{ required: true, message: "生产车间不能为空", trigger: "change" }],
        productionDate: [{ required: true, message: "生产日期不能为空", trigger: "change" }],
      },
      rawList: [
      ],
      list: [],
      selected: [],
      /** 物料基础数据缓存（goodsNum -> material） */
      materialMap: {}
    };
  },
  created() {
    this.list = [];
  },
  methods: {
    getTomorrowYMD() {
      const d = new Date();
      d.setDate(d.getDate() + 1);
      const y = d.getFullYear();
      const m = String(d.getMonth() + 1).padStart(2, "0");
      const day = String(d.getDate()).padStart(2, "0");
      return `${y}-${m}-${day}`;
    },
    openDialog() {
      this.open = true;
      this.selected = [];
      // 用 complete 页默认值补齐查询条件（如有）
      if (this.productionTypeDefault != null) this.queryForm.productionType = this.productionTypeDefault
      if (this.productionWorkshopDefault != null) this.queryForm.productionPlantNo = this.productionWorkshopDefault
      // 保持默认生产日期为明天
      if (!this.queryForm.productionDate) this.queryForm.productionDate = this.getTomorrowYMD()
      this.$nextTick(() => {
        if (this.$refs.table) this.$refs.table.clearSelection();
      });
      // 不自动查询：由用户点击“查询”触发表单校验
    },
    close() {
      this.open = false;
    },
    handleSelectionChange(val) {
      this.selected = val || [];
    },
    handleQuery() {
      this.$refs.queryForm.validate(valid => {
        if (!valid) return

        const { productionType, productionPlantNo, productionDate } = this.queryForm
        // 接口参数：productionDate/productionType/productionWorkshop
        const params = {
          productionDate,
          productionType,
          productionWorkshop: productionPlantNo
        }

        getConventionList(params).then(res => {
          const data = res && res.data ? res.data : res
          this.list = Array.isArray(data)
            ? data
            : (Array.isArray(data && data.records) ? data.records : [])

          // 剔除当前重量为 null 的记录
          this.list = (this.list || []).filter(row => row && row.currentWeightKg !== null && row.currentWeightKg !== undefined)

          // 辅助数量默认 1，并根据检疫结果 quarantineInspection 回填：
          // - quarantineInspection === '1'：
          //   qualifiedQty/inQty = currentWeightKg，unqualifiedQty = null，inAuxQty = 1
          // - quarantineInspection === '0'：
          //   qualifiedQty/inQty/inAuxQty = null，unqualifiedQty = currentWeightKg
          this.list = (this.list || []).map(row => {
            const qi = row && row.quarantineInspection != null ? String(row.quarantineInspection) : ''
            const cw = row ? row.currentWeightKg : null

            // 辅助数量：默认 1（无论合格/不合格）
            const auxQty = row && (row.auxQty == null ? 1 : row.auxQty)

            if (qi === '1') {
              return {
                ...row,
                auxQty,
                auxiliaryQuantity: auxQty,
                qty: cw,
                quantity: cw,
                qualifiedQty: cw,
                qualifiedQuantity: cw,
                unqualifiedQty: null,
                unqualifiedQuantity: null,
                inQty: cw,
                warehousingQuantity: cw,
                inAuxQty: 1
                ,
                warehousingAuxiliaryQuantity: 1,
                // 字段对齐（用于 complete 页明细表格展示）
                batchNumber: row.batchNumber ?? row.batch ?? row.pigBatch,
                specificationModel: row.specificationModel ?? row.specModel,
                categoryGrade: row.categoryGrade ?? row.categoryLevel,
                measurementUnit: row.measurementUnit ?? row.unit,
                auxiliaryMeasurementUnit: row.auxiliaryMeasurementUnit ?? row.auxUnit
              }
            }

            if (qi === '0') {
              return {
                ...row,
                auxQty,
                auxiliaryQuantity: auxQty,
                qty: cw,
                quantity: cw,
                qualifiedQty: null,
                qualifiedQuantity: null,
                unqualifiedQty: cw,
                unqualifiedQuantity: cw,
                inQty: null,
                warehousingQuantity: null,
                inAuxQty: null
                ,
                warehousingAuxiliaryQuantity: null,
                // 字段对齐（用于 complete 页明细表格展示）
                batchNumber: row.batchNumber ?? row.batch ?? row.pigBatch,
                specificationModel: row.specificationModel ?? row.specModel,
                categoryGrade: row.categoryGrade ?? row.categoryLevel,
                measurementUnit: row.measurementUnit ?? row.unit,
                auxiliaryMeasurementUnit: row.auxiliaryMeasurementUnit ?? row.auxUnit
              }
            }

            // 兜底：未知检疫结果不改数量字段（或保持默认）
            return {
              ...row,
              auxQty,
              auxiliaryQuantity: auxQty,
              qty: cw,
              quantity: cw,
              // 字段对齐（用于 complete 页明细表格展示）
              batchNumber: row.batchNumber ?? row.batch ?? row.pigBatch,
              specificationModel: row.specificationModel ?? row.specModel,
              categoryGrade: row.categoryGrade ?? row.categoryLevel,
              measurementUnit: row.measurementUnit ?? row.unit,
              auxiliaryMeasurementUnit: row.auxiliaryMeasurementUnit ?? row.auxUnit
            }
          })
          this.selected = []

          // 用 goodsNum 匹配物料档案：补齐物料名称/规格/计量单位/辅助计量单位/仓库
          // 同时：品种种类/品类级别需要从 list 行的 procurementVariety/grade（value）转为 label
          getMaterialList({}).then(materialRes => {
            const materialData = materialRes && materialRes.data ? materialRes.data : materialRes
            const matArr = Array.isArray(materialData) ? materialData : []
            this.materialMap = {}
            matArr.forEach(m => {
              if (m && m.goodsNum != null) {
                this.materialMap[String(m.goodsNum).trim()] = m
              }
            })

            Promise.all([getVarietyList({}), getLevelList({})]).then(([varietyRes, levelRes]) => {
              const varietyData = varietyRes && varietyRes.data ? varietyRes.data : varietyRes
              const varietyList = Array.isArray(varietyData) ? varietyData : []
              const varietyMap = {}
              varietyList.forEach(v => {
                if (v && v.varietyNo != null) varietyMap[String(v.varietyNo)] = v.varietyName
              })

              const levelData = levelRes && levelRes.data ? levelRes.data : levelRes
              const levelList = Array.isArray(levelData) ? levelData : []
              const levelMap = {}
              levelList.forEach(l => {
                if (l && l.levelNo != null) levelMap[String(l.levelNo)] = l.levelName
              })

              this.list = (this.list || []).map(row => {
              const key = row && row.goodsNum != null ? String(row.goodsNum).trim() : ''
              if (!key || !this.materialMap || !this.materialMap[key]) return row

              const mat = this.materialMap[key]

              // 从 list 里的 value 字段拿 label
              const procurementVarietyNo = row.procurementVariety != null ? String(row.procurementVariety) : ''
              const gradeNo = row.grade != null ? String(row.grade) : ''

              return {
                ...row,
                materialName: mat.goodsName ?? row.materialName,
                specModel: mat.goodsSpec ?? row.specModel,
                specificationModel: mat.goodsSpec ?? row.specificationModel ?? row.specModel,
                varietyCategory: varietyMap[procurementVarietyNo] ?? (mat.varietyName ?? row.varietyCategory),
                categoryLevel: levelMap[gradeNo] ?? (mat.goodsLevelName ?? row.categoryLevel),
                categoryGrade: levelMap[gradeNo] ?? (mat.goodsLevelName ?? row.categoryGrade ?? row.categoryLevel),
                unit: mat.unit ?? row.unit,
                measurementUnit: mat.unit ?? row.measurementUnit ?? row.unit,
                auxUnit: mat.assistantUnit ?? row.auxUnit,
                auxiliaryMeasurementUnit: mat.assistantUnit ?? row.auxiliaryMeasurementUnit ?? row.auxUnit,
                warehouse: mat.warehouseName ?? row.warehouse,
                // 完成字段对齐：用 pigBatch 映射 batchNumber
                batchNumber: row.batchNumber ?? row.batch ?? row.pigBatch
              }
              })

              this.$nextTick(() => {
                if (this.$refs.table) this.$refs.table.clearSelection()
              })
            }).catch(() => {
              // label 查询失败：至少保证物料回填仍能展示
              this.list = (this.list || []).map(row => {
                const key = row && row.goodsNum != null ? String(row.goodsNum).trim() : ''
                if (!key || !this.materialMap || !this.materialMap[key]) return row
                const mat = this.materialMap[key]
                return {
                  ...row,
                  materialName: mat.goodsName ?? row.materialName,
                  specModel: mat.goodsSpec ?? row.specModel,
                  specificationModel: mat.goodsSpec ?? row.specificationModel ?? row.specModel,
                  varietyCategory: mat.varietyName ?? row.varietyCategory,
                  categoryLevel: mat.goodsLevelName ?? row.categoryLevel,
                  categoryGrade: mat.goodsLevelName ?? row.categoryGrade ?? row.categoryLevel,
                  unit: mat.unit ?? row.unit,
                  measurementUnit: mat.unit ?? row.measurementUnit ?? row.unit,
                  auxUnit: mat.assistantUnit ?? row.auxUnit,
                  auxiliaryMeasurementUnit: mat.assistantUnit ?? row.auxiliaryMeasurementUnit ?? row.auxUnit,
                  warehouse: mat.warehouseName ?? row.warehouse,
                  batchNumber: row.batchNumber ?? row.batch ?? row.pigBatch
                }
              })

              this.$nextTick(() => {
                if (this.$refs.table) this.$refs.table.clearSelection()
              })
            })
          }).catch(() => {
            // 物料/字典查询失败：至少保证 list 仍能展示原始字段
            this.$nextTick(() => {
              if (this.$refs.table) this.$refs.table.clearSelection()
            })
          })
        })
      })
    },
    confirm() {
      const selected = Array.isArray(this.selected) ? this.selected : []
      // 选中 0/1 条：无需合并，直接返回
      if (selected.length <= 1) {
        this.$emit("selectList", selected)
        this.close()
        return
      }

      const toKey = (v) => (v == null ? '' : String(v).trim())
      const toNum = (v) => {
        if (v === null || v === undefined || v === '') return 0
        const n = Number(v)
        return Number.isFinite(n) ? n : 0
      }
      const fixNullIfZero = (v) => {
        const n = toNum(v)
        return n === 0 ? null : n
      }

      // 先统计是否存在 goodsNum 重复
      const countMap = {}
      selected.forEach(row => {
        const k = toKey(row && row.goodsNum)
        if (!k) return
        countMap[k] = (countMap[k] || 0) + 1
      })
      const hasDuplicate = Object.keys(countMap).some(k => countMap[k] > 1)
      if (!hasDuplicate) {
        this.$emit("selectList", selected)
        this.close()
        return
      }

      // 存在重复 goodsNum：同 goodsNum 的数量类字段相加后回传（保持首次出现顺序）
      const mergedMap = {}
      const result = []
      selected.forEach(row => {
        const k = toKey(row && row.goodsNum)
        if (!k) return

        if (!mergedMap[k]) {
          mergedMap[k] = { ...row }
          result.push(mergedMap[k])
        }

        // 需要相加的字段（按 complete 明细字段名）
        mergedMap[k].quantity =
          toNum(mergedMap[k].quantity) + toNum(row && row.quantity)
        mergedMap[k].auxiliaryQuantity =
          toNum(mergedMap[k].auxiliaryQuantity) + toNum(row && row.auxiliaryQuantity)
        mergedMap[k].qualifiedQuantity =
          toNum(mergedMap[k].qualifiedQuantity) + toNum(row && row.qualifiedQuantity)
        mergedMap[k].unqualifiedQuantity =
          toNum(mergedMap[k].unqualifiedQuantity) + toNum(row && row.unqualifiedQuantity)
        mergedMap[k].warehousingQuantity =
          toNum(mergedMap[k].warehousingQuantity) + toNum(row && row.warehousingQuantity)
        mergedMap[k].warehousingAuxiliaryQuantity =
          toNum(mergedMap[k].warehousingAuxiliaryQuantity) + toNum(row && row.warehousingAuxiliaryQuantity)
      })

      // 相加后：0 回填 null（保持原先可为空的风格）
      result.forEach(r => {
        r.quantity = fixNullIfZero(r.quantity)
        r.auxiliaryQuantity = fixNullIfZero(r.auxiliaryQuantity)
        r.qualifiedQuantity = fixNullIfZero(r.qualifiedQuantity)
        r.unqualifiedQuantity = fixNullIfZero(r.unqualifiedQuantity)
        r.warehousingQuantity = fixNullIfZero(r.warehousingQuantity)
        r.warehousingAuxiliaryQuantity = fixNullIfZero(r.warehousingAuxiliaryQuantity)
      })

      this.$emit("selectList", result);
      this.close();
    },
  },
};
</script>
