<template>
  <div class="app-container">
    <el-card>
      <el-form ref="form" :model="form" :rules="formRules" label-width="120px">
        <el-row :gutter="24" class="form-three-cols">

          <!-- 左列：生产记录单号、投入原料日期、生产日期、品种、动物标识 -->
          <el-col :span="6" class="form-col">
            <el-form-item label="生产记录单号" prop="productionRecordNumber">
              <el-input v-model="form.productionRecordNumber" disabled></el-input>
            </el-form-item>
            <el-form-item label="投入原料日期" prop="rawMaterialInputDate">
              <el-date-picker
                style="width: 100%"
                v-model="form.rawMaterialInputDate"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="生产日期" prop="productionDate">
              <el-date-picker
                style="width: 100%"
                v-model="form.productionDate"
                value-format="yyyy-MM-dd"
                disabled
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="品种" prop="variety">
              <el-select filterable style="width: 100%;" v-model="form.variety" disabled @change="changeVariety">
                <el-option v-for="item in varietyList" :key="item.varietyNo" :value="item.varietyNo" :label="item.varietyName"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="动物标识" prop="animalIdentification">
              <el-input v-model="form.animalIdentification"></el-input>
            </el-form-item>
          </el-col>
          <!-- 中列：生产类型、生猪批次、生产计划单号、级别 -->
          <el-col :span="6" class="form-col">
            <el-form-item label="生产类型" prop="productionType">
               <el-select v-model="form.productionType" style="width: 100%;" disabled>
                    <el-option v-for="item in dict.type.inventory_production_type" :key="item.value" :value="item.value" :label="item.label"></el-option>
                  </el-select>
            </el-form-item>
            <el-form-item label="生猪批次" prop="pigBatch">
              <el-input v-model="form.pigBatch" disabled></el-input>
            </el-form-item>
            <el-form-item label="生产计划单号" prop="productionPlanNumber">
              <el-input v-model="form.productionPlanNumber" disabled></el-input>
            </el-form-item>
            <el-form-item label="级别" prop="grade">
              <el-select style="width: 100%" filterable v-model="form.grade" disabled @change="changeLevel">
                <el-option v-for="item in levelList" :key="item.levelNo" :value="item.levelNo" :label="item.levelName"></el-option>
              </el-select>
            </el-form-item>
             <el-form-item label="加工类型" prop="processingType">
              <el-radio-group v-model="form.processingType">
                <el-radio :label="2">精修</el-radio>
                <el-radio :label="3">预冷</el-radio>
                <el-radio :label="4">分割</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <!-- 右列：生产车间、质检结果、采购品种、供应来源 + 加工工艺 -->
          <el-col :span="6" class="form-col form-col-right">
            <el-form-item label="生产车间" prop="productionWorkshop">
              <el-select v-model="form.productionWorkshop" style="width: 100%;" disabled>
                <el-option
                  v-for="item in productionPlantList"
                  :key="item.productionPlantNo"
                  :value="item.productionPlantNo"
                  :label="item.productionPlantName"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="质检结果" prop="qualityInspectionResult">
              <el-select filterable style="width: 100%;" v-model="form.qualityInspectionResult">
                <el-option :value="1" label="合格"></el-option>
                <el-option :value="0" label="不合格"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="采购品种" prop="procurementVariety">
              <el-select filterable style="width: 100%;" v-model="form.procurementVariety" disabled @change="changeProcurementVariety">
                <el-option v-for="item in varietyList" :key="item.varietyNo" :value="item.varietyNo" :label="item.varietyName"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="供应来源" prop="supplySource">
              <el-input v-model="form.supplySource"></el-input>
            </el-form-item>
            <el-form-item label="加工工艺" prop="processingTechnology">
              <el-select filterable style="width: 100%" v-model="form.processingTechnology">
                 <el-option v-for="item in 12" :value="item" :key="item" :label="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
              <div class="red_left">
              <span class="max_red">白条编号：</span>
              <el-form-item label-width="0">
                <el-input
                  size="large"
                  class="large-input"
                  v-model="form.whiteStripNumber"
                  clearable
                  @blur="onWhiteStripNumberBlur"
                />
              </el-form-item>
            </div>
            <div class="red_left">
              <span class="max_red">本次重量(千克)：</span>
              <el-form-item label-width="0">
                <el-input v-model="form.tertiaryWeight" size="large" class="large-input"></el-input>
              </el-form-item>
            </div>
            <el-form-item>
              <el-button type="primary" @click="handleConfirm">确认</el-button>
              <el-button @click="handleCancel">取消</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <br>
        <el-table
          size="mini"
          :data="tableData"
          style="width: 100%;"
          border
          stripe
        >
          <el-table-column label="白条编号" align="center" width="120" prop="whiteStripNumber" min-width="120"></el-table-column>
          <el-table-column label="生猪批次" align="center" width="120" prop="pigBatch" min-width="120"></el-table-column>
          <el-table-column label="物料名称" align="center" width="120" prop="goodsNum" min-width="120">
            <template slot-scope="scope">
              <span>{{ getTableGoodsName(scope.row, 'goodsNum', 'goodsName') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="品种" align="center" width="100" prop="variety" min-width="100">
            <template slot-scope="scope">
              <span>{{ getTableVarietyLabel(scope.row, 'variety', 'varietyName') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="级别" align="center" width="100" prop="grade" min-width="100">
            <template slot-scope="scope">
              <span>{{ getTableLevelLabel(scope.row, 'grade', 'levelName') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="毛色" align="center" width="100" prop="coatColor" min-width="100">
            <template slot-scope="scope">
              <span>{{ getTableCoatLabel(scope.row) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="动物标记" align="center" width="120" prop="animalMark" min-width="120"></el-table-column>
          <el-table-column label="二次计重重量" align="center" width="120" prop="secondaryWeight" min-width="120"></el-table-column>
          <el-table-column label="三次计重重量" align="center" width="120" prop="tertiaryWeight" min-width="120"></el-table-column>
          <el-table-column label="钩重" align="center" width="100" prop="hookWeight" min-width="100"></el-table-column>
          <el-table-column label="加工类型" align="center" width="100" prop="processingType" min-width="100">
            <template slot-scope="scope">
              <span>{{ getProcessingTypeLabel(scope.row.processingType) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="加工扣分" align="center" width="100" prop="processingDeduction" min-width="100"></el-table-column>
          <el-table-column label="采购扣分" align="center" width="100" prop="procurementDeduction" min-width="100"></el-table-column>
          <el-table-column label="质检结果" align="center" width="100" prop="qualityInspectionResult" min-width="100">
            <template slot-scope="scope">
              <span>{{ getQualityInspectionLabel(scope.row.qualityInspectionResult) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="采购物料名称" align="center" width="120" prop="procurementMaterialName" min-width="120">
            <template slot-scope="scope">
              <span>{{ getTableGoodsName(scope.row, 'procurementMaterialName', 'procurementMaterialNameText') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="采购品种" align="center" width="120" prop="procurementVarietyDetail" min-width="120">
            <template slot-scope="scope">
              <span>{{ getTableVarietyLabel(scope.row, 'procurementVarietyDetail', 'procurementVarietyName') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="采购级别" align="center" width="100" prop="procurementGrade" min-width="100">
            <template slot-scope="scope">
              <span>{{ getTableLevelLabel(scope.row, 'procurementGrade', 'procurementGradeName') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="扣重前重量" align="center" width="120" prop="preDeductionWeight" min-width="120"></el-table-column>
          <el-table-column label="扣重比例%" align="center" width="100" prop="deductionRatio" min-width="100"></el-table-column>
        </el-table>
      </el-form>
    </el-card>
  </div>
</template>
<script>
  import { getFindByKey } from "../../../utils";
  import { getVarietyList } from "../../../api/baseInfo/variety";
  import { getLevelList } from "../../../api/baseInfo/level";
  import { getCoatList } from "../../../api/baseInfo/coat";
  import { getPlanList } from "../../../api/production/plan";
  import { getTruingList, getTruingById, addTruing, editTruing, delTruing, getTruingByWhiteStripNumber } from "../../../api/production/truing";
  import { getLatestProductionRecordNumber } from "../../../api/production/convention";
  import { getProductionPlantList } from "../../../api/production/productionPlant";
  import { getMaterialList } from "../../../api/baseInfo/material";

  export default {
    name: 'Truing',
    dicts: ['inventory_production_type'],
    data() {
      return {
        form: {},
        formRules: {
        },
        /** 生产车间下拉（由接口拉取 productionPlantNo / productionPlantName） */
        productionPlantList: [],
        varietyList: [],
        levelList: [],
        coatList: [],
        /** 物料基础数据：goodsNum -> goodsName（物料名称、采购物料名称共用） */
        materialList: [],
        planNum: null,
        tableData: []
      }
    },
    created() {
      this.reset();
      this.getCoat();
      this.getLevel();
      this.getVariety();
      this.getPlanList();
      this.fetchProductionPlantList();
      this.fetchMaterialList();
    },
    methods: {
      /** 拉取物料列表，用于表格编码转名称 */
      fetchMaterialList() {
        return getMaterialList({})
          .then((res) => {
            const data = res && res.data != null ? res.data : res
            this.materialList = Array.isArray(data) ? data : []
          })
          .catch(() => {
            this.materialList = []
          })
      },
      /** 根据 goodsNum 反查物料名称 */
      getGoodsNameByNum(goodsNum) {
        const key = goodsNum == null ? "" : String(goodsNum).trim()
        if (!key) return "-"
        const item = getFindByKey(this.materialList || [], key, "goodsNum")
        return item ? (item.goodsName || "-") : "-"
      },
      /**
       * 表格物料名称展示：优先行内名称字段，否则按编码查物料基础数据。
       * 物料名称、采购物料名称共用同一套 goodsNum 解析逻辑。
       */
      getTableGoodsName(row, codeKey, nameKey) {
        if (!row) return "-"
        const name = row[nameKey]
        if (name != null && String(name).trim() !== "") return name
        return this.getGoodsNameByNum(row[codeKey])
      },
      /** 品种编码 -> 名称（与采购品种共用） */
      getVarietyLabel(val) {
        const item = getFindByKey(this.varietyList || [], val, "varietyNo")
        return item ? item.varietyName : (val == null || val === "" ? "-" : val)
      },
      /**
       * 表格品种展示：优先行内名称，否则按 varietyNo 查基础数据。
       */
      getTableVarietyLabel(row, codeKey, nameKey) {
        if (!row) return "-"
        const name = row[nameKey]
        if (name != null && String(name).trim() !== "") return name
        return this.getVarietyLabel(row[codeKey])
      },
      /** 级别编码 -> 名称（与采购级别共用） */
      getLevelLabel(val) {
        const item = getFindByKey(this.levelList || [], val, "levelNo")
        return item ? item.levelName : (val == null || val === "" ? "-" : val)
      },
      /**
       * 表格级别展示：优先行内名称，否则按 levelNo 查基础数据。
       */
      getTableLevelLabel(row, codeKey, nameKey) {
        if (!row) return "-"
        const name = row[nameKey]
        if (name != null && String(name).trim() !== "") return name
        return this.getLevelLabel(row[codeKey])
      },
      /** 毛色编码 -> 名称 */
      getCoatLabel(val) {
        const item = getFindByKey(this.coatList || [], val, "coatNum")
        return item ? item.coatName : (val == null || val === "" ? "-" : val)
      },
      /** 表格毛色：优先行内 coatName，否则按 coatColor 查基础数据 */
      getTableCoatLabel(row) {
        if (!row) return "-"
        if (row.coatName != null && String(row.coatName).trim() !== "") return row.coatName
        return this.getCoatLabel(row.coatColor)
      },
      /** 生产车间列表：对接 /production-plant/list */
      fetchProductionPlantList() {
        return getProductionPlantList({})
          .then((res) => {
              this.productionPlantList = res.data || [];
          })
          .catch(() => {
            this.productionPlantList = []
          })
      },
      /** 查询 **/
      getList() {
        let params = {
          productionPlanNumber: this.planNum
        }
        getTruingList(params).then(res => {
          this.tableData = res.data || [];
        });
      },
      getCoat() {
        getCoatList({}).then(res => {
          this.coatList = res.data || [];
        });
      },
      getPlanList() {
        let params = {
          productionType: '2'
        }
        getPlanList(params).then(res => {
          if(res.data.length > 0) {
            this.planNum = res.data[0].orderNum;
          } else {
            this.planNum = null;
          }
        });
      },
      changeCoat(val) {
        let item = getFindByKey(this.coatList, val, 'coatNum');
        if (item) {
          this.form.costName = item.costName;
        }
      },
      getLevel() {
        getLevelList({}).then(res => {
          this.levelList = res.data || [];
        });
      },
      /** 级别变更：同步级别名称（表格/提交用 levelName，与基础数据字段一致） */
      changeLevel(val) {
        let item = getFindByKey(this.levelList, val, 'levelNo');
        if (item) {
          this.form.levelName = item.levelName;
        }
      },
      getVariety() {
        getVarietyList({}).then(res => {
          this.varietyList = res.data || [];
        });
      },
      /** 采购品种变更：同步展示名称（对应 procurement_variety_detail 等场景） */
      changeProcurementVariety(val) {
        let item = getFindByKey(this.varietyList, val, 'varietyNo');
        if (item) {
          this.form.procurementVarietyName = item.varietyName;
        }
      },
      changeVariety(val) {
        let item = getFindByKey(this.varietyList, val, 'varietyNo');
        if (item) {
          this.form.varietyName = item.varietyName;
        }
      },
      /**
       * 白条编号失焦：预留对接接口校验/拉取明细等逻辑。
       * @param {FocusEvent} [e] 原生失焦事件（按需使用）
       */
      onWhiteStripNumberBlur(/* e */) {
        const no = this.form.whiteStripNumber == null ? "" : String(this.form.whiteStripNumber).trim()
        if (!no) {
          // TODO: 空值时是否清空关联字段、是否提示，按产品约定补充
          return
        }
        let that = this;
        let params = {
          whiteStripNum: no,
          whiteStripDate: this.getTomorrowDateString(),
          productionType: '2'
        }
        getTruingByWhiteStripNumber(params).then(res1 => {
          this.form.pigBatch = res1.data.pigBatch;
          this.form.productionPlanNumber = this.planNum;
          this.form.productionWorkshop = res1.data.productionWorkshop;
          this.form.procurementVariety = res1.data.procurementVariety;
          this.form.procurementVarietyName = res1.data.procurementVarietyName;
          this.form.productionDate = res1.data.productionDate;
          this.form.grade = res1.data.grade;
          this.form.processingTechnology = res1.data.processingTechnology;
          this.form.whiteStripNumber = res1.data.whiteStripNumber;
          this.form.currentWeightKg = res1.data.currentWeightKg;
          this.form.hookWeight = res1.data.hookWeight;
          this.form.deductionRatio = res1.data.deductionRatio;
          this.form.secondaryWeight = res1.data.currentWeightKg;
          this.form.animalIdentification= res1.data.animalIdentification;
          this.form.variety = res1.data.variety;
          this.form.procurementMaterialName = res1.data.goodsNum;
          this.form.procurementVarietyDetail = res1.data.variety;
          this.form.procurementGrade = res1.data.grade;
          this.form.deductionRatio = res1.data.deductionRatio;
          this.form.coatColor = res1.data.coatColor;
          this.form.goodsNum = res1.data.goodsNum;
           this.getList();

          getLatestProductionRecordNumber().then(res => {
            this.form.productionRecordNumber = res.msg
          })
        }).catch((err) => {
          that.$alert(err, '提示', {
            type: 'warning',
          })
        })
      },
      /** 加工类型 value -> 文案（与表单 radio 一致） */
      getProcessingTypeLabel(val) {
        if (val == null || val === '') return '-'
        const map = { 1: '常规', 2: '精修', 3: '预冷', 4: '分割' }
        const key = String(val)
        if (map[key] != null) return map[key]
        const s = String(val)
        if (['常规', '精修', '预冷', '分割'].includes(s)) return s
        return val
      },
      /** 终检质检结果 0/1 -> 文案 */
      getQualityInspectionLabel(val) {
        if (String(val) === '1') return '合格'
        if (String(val) === '0') return '不合格'
        return val == null || val === '' ? '-' : val
      },
      handleConfirm() {
        this.$refs.form.validate(valid => {
          if (valid) {
            addTruing(this.form).then(() => {
              this.$message.success('确认成功');
              this.reset();
              this.getList();
            })
          }
        })
      },
    
      handleCancel() {
        this.reset();
      },
      /** 明天日期 yyyy-MM-dd，与投入原料日期 value-format 一致 */
      getTomorrowDateString() {
        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}`
      },
      reset() {
        this.form = {
          id: null,
          productionRecordNumber: null,
          rawMaterialInputDate: this.getTomorrowDateString(),
          productionDate: null,
          coatColor: null,
          goodsNum: null,
          variety: null,
          animalIdentification: null,
          productionType: '2',
          pigBatch: null,
          productionPlanNumber: null,
          grade: null,
          processingType: 2,
          productionWorkshop: null,
          qualityInspectionResult: 1,
          procurementVariety: null,
          procurementVarietyName: null,
          supplySource: null,
          processingTechnology: null,
          whiteStripNumber: null,
          currentWeightKg: null,
          animalMark: null,
          secondaryWeight: null,
          tertiaryWeight: null,
          hookWeight: null,
          processingDeduction: null,
          procurementDeduction: null,
          finalQualityInspectionResult: null,
          procurementMaterialName: null,
          procurementVarietyDetail: null,
          procurementGrade: null,
          preDeductionWeight: null,
          deductionRatio: null,
        };
      }
    },
    mounted() {}
  }
</script>

<style scoped lang="scss">
  .form-three-cols {
    display: flex;
    align-items: flex-start;
  }
  .form-col {
    display: flex;
    flex-direction: column;
  }
  .form-col .el-form-item {
    margin-bottom: 18px;
  }
  .form-col-right {
    max-width: 480px;
  }
  .red_left {
    margin-left: 0;
    margin-bottom: 20px;
  }
  .max_red {
    font-size: 24px;
    color: red;
  }
  .large-input {
    font-size: 32px;
    width: 300px;
  }
  .large-input > .el-input__inner {
    height: 60px;
    line-height: 60px;
  }
</style>
