<template>
  <div class="app-container">
    <el-card>
      <el-form  ref="form" :model="form" :rules="formRules"  label-width="120px">
        <el-row :gutter="24">
          <el-col :span="18">
            <el-row>
              <el-col :span="8">
                <el-form-item label="生产计划单号" prop="productionPlanNumber">
                  <el-input v-model="form.productionPlanNumber">
                    <template #append>
                      <el-button
                        type="primary"
                        icon="el-icon-search"
                        @click="openPlanQueryDialog"
                      />
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <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-col>
              <el-col :span="8">
                <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-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="生猪批次" prop="pigBatch">
                  <el-input v-model="form.pigBatch">
                    <template #append>
                      <el-button
                        type="primary"
                        icon="el-icon-search"
                        @click="openPigBatchDialog"
                      />
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="检疫检验" prop="quarantineInspection">
                  <el-select filterable style="width: 100%;" v-model="form.quarantineInspection">
                    <el-option :value="1" label="合格"></el-option>
                    <el-option :value="0" label="不合格"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="采购品种" prop="procurementVariety">
                  <el-select filterable style="width: 100%;" v-model="form.procurementVariety" @change="changePurchaseVariety" disabled>
                    <el-option v-for="item in varietyList" :key="item.varietyNo" :value="item.varietyNo" :label="item.varietyName"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="生产记录单号" prop="productionRecordNumber">
                  <el-input v-model="form.productionRecordNumber" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <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-col>
              <el-col :span="8">
                <el-form-item label="品种" prop="variety">
                  <el-select filterable style="width: 100%;" v-model="form.variety" @change="changeVariety" disabled>
                    <el-option v-for="item in varietyList" :key="item.varietyNo" :value="item.varietyNo" :label="item.varietyName"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="级别" prop="grade">
                  <el-select style="width: 100%" filterable v-model="form.grade" @change="changeLevel" disabled>
                    <el-option v-for="item in levelList" :key="item.levelNo" :value="item.levelNo" :label="item.levelName"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="毛色" prop="coatColor">
                  <el-select style="width: 100%" filterable v-model="form.coatColor" @change="changeCoat" disabled>
                    <el-option v-for="item in coatList" :key="item.coatNum" :value="item.coatNum" :label="item.coatName"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="批次" prop="batch">
                  <el-input v-model="form.batch" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="动物标识" prop="animalIdentification">
                  <el-input v-model="form.animalIdentification"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="加工类型" prop="processingType">
                  <el-radio-group v-model="form.processingType">
                    <el-radio :label="1">常规</el-radio>
                    <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="8">
                <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="8">
                <el-form-item>
                  <el-button type="primary" :disabled="String(form.productionStatus) === '1'" @click="handleConfirm">确认</el-button>
                  <el-button @click="handleCancel">取消</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="6">
            <div class="red_left">
              <span class="max_red">白条编号：</span>
              <el-form-item label-width="0" prop="whiteStripNumber">
                <el-input size="large" class="large-input" v-model="form.whiteStripNumber"></el-input>
              </el-form-item>
            </div>
            <div class="red_left">
              <span class="max_red">本次重量(千克)：</span>
              <el-form-item label-width="0" prop="currentWeightKg">
                <decimal-input
                  v-model="form.currentWeightKg"
                  :min="0"
                  :max="999999"
                  :precision="2"
                  class="large-input"
                />
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-form>

      <!-- 表格独立，不放在上面表单内 -->
        <br>
        <el-table
          size="mini"
          :data="tableData"
          :row-class-name="getTableRowClassName"
                  style="width: 100%;"
                  border
                  stripe>
          <el-table-column label="白条编号" prop="whiteStripNumber" align="center" width="180" fixed></el-table-column>
          <el-table-column label="生猪批次" prop="pigBatch" align="center" width="180" ></el-table-column>
          <el-table-column label="物料名称" prop="goodsName" align="center" width="180">
            <template slot-scope="scope">
              <span>{{ scope.row.goodsName || getGoodsNameByNum(scope.row.goodsNum) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="品种" prop="variety" align="center" width="180" >
             <template slot-scope="scope">
              <span>{{ getVarietyLabel(scope.row.variety) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="级别" prop="grade" align="center" width="180" >
            <template slot-scope="scope">
              <span>{{ getLevelLabel(scope.row.grade) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="毛色" prop="coatColor" align="center" width="180" >
            <template slot-scope="scope">
              <span>{{ getCoatLabel(scope.row.coatColor) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="检疫检验" prop="quarantineInspection" align="center" width="180" >
            <template slot-scope="scope">
              <span>{{ getQuarantineLabel(scope.row.quarantineInspection) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="动物标识" prop="animalIdentification" align="center" width="180" ></el-table-column>
          <el-table-column label="二次计重重量" prop="currentWeightKg" align="center" width="180" ></el-table-column>
          <el-table-column label="钩重" prop="hookWeight" align="center" width="180" ></el-table-column>
          <el-table-column label="数量" prop="quantity" align="center" width="180"></el-table-column>
         <el-table-column label="加工类型" prop="processingType" align="center" width="180">
            <template slot-scope="scope">
              <span>{{ getProcessingTypeLabel(scope.row.processingType) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="生产计划单号" prop="productionPlanNumber" align="center" width="180"></el-table-column>
          <el-table-column label="生产类型" prop="productionType" align="center" width="180">
            <template slot-scope="scope">
              <span>{{ getProductionTypeLabel(scope.row.productionType) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="生产车间" prop="productionWorkshop" align="center" width="180">
            <template slot-scope="scope">
              <span>{{ getProductionWorkshopLabel(scope.row.productionWorkshop) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="生产记录单号" prop="productionRecordNumber" align="center" width="180"></el-table-column>
          <el-table-column label="生产日期" prop="productionDate" align="center" width="180"></el-table-column>
          <el-table-column label="采购品种" prop="procurementVariety" align="center" width="180">
            <template slot-scope="scope">
              <span>{{ getVarietyLabel(scope.row.procurementVariety) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="加工工艺" prop="processingTechnology" align="center" width="180"></el-table-column>
          <el-table-column label="扣重前重量" prop="preDeductionWeight" align="center" width="180"></el-table-column>
          <el-table-column label="扣重比例" prop="deductionRatio" align="center" width="180"></el-table-column>
        </el-table>

      <el-dialog
        title="生产计划单查询"
        :visible.sync="planQueryDialogOpen"
        width="1100px"
        append-to-body
        @close="onPlanQueryDialogClose"
      >
        <el-table
          ref="planQueryTable"
          :data="planQueryList"
          border
          stripe
          highlight-current-row
          height="420"
          style="width: 100%;"
          @row-click="handlePlanQueryRowClick"
        >
          <el-table-column label="生产日期" prop="orderDate" align="center" min-width="140" />
          <el-table-column label="单据编号" prop="orderNum" align="center" min-width="140" />
          <el-table-column label="生产类型" prop="productionType" align="center" min-width="120">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.inventory_production_type" :value="scope.row.productionType" />
            </template>
          </el-table-column>
          <el-table-column label="生产车间" prop="productionPlantName" align="center" min-width="160" show-overflow-tooltip />
          <el-table-column label="备注" prop="remark" align="center" min-width="140" />
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handlePlanQueryConfirm">确 定</el-button>
          <el-button @click="planQueryDialogOpen = false">取 消</el-button>
        </div>
      </el-dialog>

      <el-dialog
        title="生猪批次查询"
        :visible.sync="pigBatchDialogOpen"
        width="1000px"
        append-to-body
        @close="onPigBatchDialogClose"
      >
        <el-table
          ref="pigBatchTable"
          :data="pigBatchList"
          border
          stripe
          highlight-current-row
          height="420"
          style="width: 100%;"
          @row-click="handlePigBatchRowClick"
        >
          <el-table-column label="生产计划单号" prop="orderNum" align="center" min-width="140" />
          <el-table-column label="生猪批次" prop="batch" align="center" min-width="160" />
          <el-table-column label="数量" prop="assNum" align="center" min-width="120" />
          <el-table-column label="单位" prop="assistantUnit" align="center" min-width="120" />
          <el-table-column label="生产情况">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.productionStatus === 0" type="success">未生产</el-tag>
              <el-tag v-else-if="scope.row.productionStatus === 1" type="warning">生产完成</el-tag>
            </template>
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handlePigBatchConfirm">确 定</el-button>
          <el-button @click="pigBatchDialogOpen = false">取 消</el-button>
        </div>
      </el-dialog>
    </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 { getMaterialList } from "../../../api/baseInfo/material";
  import { editConvention, getConventionList, getLatestProductionRecordNumber } from "../../../api/production/convention";
  import { getPlanById, getPlanList } from "../../../api/production/plan";
  import { getRelatedList } from "../../../api/production/related";

  export default {
    /** 二次计重/测膘：字段与接口逻辑同常规生产（convention），不展示净重复用、批次进度与底部四列快捷选择 */
    name: 'ConventionMeasure',
    dicts: ['inventory_production_type'],
    data() {
      return {
        // 表单参数
        form: {},
        formRules: {
          productionPlanNumber: [{ required: true, message: '生产计划单号不能为空', trigger: 'blur' }],
          productionType: [{ required: true, message: '生产类型不能为空', trigger: 'change' }],
          productionWorkshop: [{ required: true, message: '生产车间不能为空', trigger: 'change' }],
          pigBatch: [{ required: true, message: '生猪批次不能为空', trigger: 'blur' }],
          quarantineInspection: [{ required: true, message: '检疫检验不能为空', trigger: 'change' }],
          procurementVariety: [{ required: true, message: '采购品种不能为空', trigger: 'change' }],
          productionRecordNumber: [{ required: true, message: '生产记录单号不能为空', trigger: 'blur' }],
          productionDate: [{ required: true, message: '生产日期不能为空', trigger: 'change' }],
          // variety: [{ required: true, message: '品种不能为空', trigger: 'change' }],
          // grade: [{ required: true, message: '级别不能为空', trigger: 'change' }],
          // coatColor: [{ required: true, message: '毛色不能为空', trigger: 'change' }],
          // batch: [{ required: true, message: '批次不能为空', trigger: 'blur' }],
          // animalIdentification: [{ required: true, message: '动物标识不能为空', trigger: 'blur' }],
          processingType: [{ required: true, message: '加工类型不能为空', trigger: 'change' }],
          processingTechnology: [{ required: true, message: '加工工艺不能为空', trigger: 'change' }],
          whiteStripNumber: [{ required: true, message: '白条编号不能为空', trigger: 'blur' }],
          currentWeightKg: [{
            required: true,
            validator: (rule, value, callback) => {
              if (value === null || value === undefined || value === '') {
                callback(new Error('本次重量不能为空'))
                return
              }
              const n = Number(value)
              if (!Number.isFinite(n) || n <= 0) {
                callback(new Error('本次重量必须大于0'))
                return
              }
              callback()
            },
            trigger: ['blur']
          }],
          suttle: [{ required: true, message: '净重不能为空', trigger: 'blur' }]
        },
        rules: {
          goodsNum: [
            { required: true, message: '货品编号不能为空', trigger: 'blur' },
          ],
        },
        productionPlantList: [
          {
            productionPlantNo: '001',
            productionPlantName: '常规生产车间'
          }
        ],
        varietyList: [],
        levelList: [],
        coatList: []
        ,
        /** 物料基础数据（用于 goodsNum -> goodsName 映射显示） */
        materialList: [],
        /** 物料生产对应管理（生产物料映射）列表：用于自动匹配物料编码 goodsNum */
        productionMaterialMappingList: [],
        /** 避免重复提示：记录上一次未匹配的组合 key */
        lastUnmatchedGoodsKey: null,
        // 明细表独立数据源（不挂在 form 上）
        tableData: [],
        // 生产计划单查询弹框
        planQueryDialogOpen: false,
        planQueryList: [],
        planQuerySelectedRow: null,
        // 当前所选生产计划单明细（goods）
        selectedPlanGoods: [],
        // 当前所选生产计划单ID（用于刷新明细）
        selectedPlanId: null,
        // 生猪批次查询弹框
        pigBatchDialogOpen: false,
        pigBatchList: [],
        pigBatchSelectedRow: null,
        // 选中生猪批次对应数量（用于白条进度计算）
        selectedPigBatchQuantity: 0
      }
    },
    computed: {
      /**
       * 表格展示数据：仅展示“二次计重重量”为空的数据
       * 说明：这里仅影响前端展示，不影响 tableData 原始数据及后续业务计算。
       */
      pendingSecondWeightTableData() {
        return this.getPendingSecondWeightQueue(this.tableData || [])
      },
      // 总白条数 = 选中生猪批次数量 * 2（整数）
      totalWhiteStripCount() {
        const qty = Number(this.selectedPigBatchQuantity || 0)
        if (!Number.isFinite(qty) || qty <= 0) return 0
        return Math.trunc(qty * 2)
      },
      // 当前白条数 = 下方表格里当前批次数量 + 1
      currentWhiteStripCount() {
        if (!this.form || !this.form.pigBatch) return 0
        const currentBatch = String(this.form.pigBatch)
        const count = (this.tableData || []).filter(item => String((item && item.pigBatch) || '') === currentBatch).length
        return count
      }
    },
    watch: {
      /** 采购品种变化：尝试匹配物料编码 */
      "form.procurementVariety": function () {
        this.tryFillGoodsNumByMapping()
      },
      /** 级别变化：尝试匹配物料编码 */
      "form.grade": function () {
        this.tryFillGoodsNumByMapping()
      },
      /** 毛色变化：尝试匹配物料编码 */
      "form.coatColor": function () {
        this.tryFillGoodsNumByMapping()
      },
      /** 加工工艺变化：尝试匹配物料编码 */
      "form.processingTechnology": function () {
        this.tryFillGoodsNumByMapping()
      }
    },
    created() {
      this.reset()
      this.getCoat()
      this.getLevel()
      this.getVariety()
      this.getMaterial()
      this.fetchProductionMaterialMappingList()
      this.fetchPlanQueryList()
    },
    methods: {
      /** 获取物料基础数据（包含 goodsNum/goodsName），用于列表反查展示名称 */
      getMaterial() {
        return getMaterialList({}).then(res => {
          const data = res && res.data ? 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 || '-') : '-'
      },
      /** 判断一条记录是否“二次计重重量为空”（待计重） */
      isPendingSecondWeight(item) {
        const weight = item && item.currentWeightKg
        if (weight === null || weight === undefined) return true
        if (typeof weight === "string" && weight.trim() === "") return true
        return false
      },
      /**
       * 生成“待二次计重”队列，并按白条编号从小到大排序。
       * 说明：白条编号优先按数字比较，无法转数字时按字符串比较。
       */
      getPendingSecondWeightQueue(list) {
        const source = Array.isArray(list) ? list : []
        return source
          .filter((item) => this.isPendingSecondWeight(item))
          .slice()
          .sort((a, b) => {
            const aRaw = a && a.whiteStripNumber != null ? String(a.whiteStripNumber).trim() : ''
            const bRaw = b && b.whiteStripNumber != null ? String(b.whiteStripNumber).trim() : ''
            const aNum = Number(aRaw.replace(/\D/g, ''))
            const bNum = Number(bRaw.replace(/\D/g, ''))
            const aValid = Number.isFinite(aNum) && aRaw !== ''
            const bValid = Number.isFinite(bNum) && bRaw !== ''
            if (aValid && bValid) return aNum - bNum
            if (aRaw < bRaw) return -1
            if (aRaw > bRaw) return 1
            return 0
          })
      },
      /** 从待二次计重队列中取下一个白条编号（最小号优先） */
      getNextPendingWhiteStripNumber(list) {
        const queue = this.getPendingSecondWeightQueue(list)
        if (queue.length === 0) return null
        const next = queue[0] && queue[0].whiteStripNumber
        return next == null ? null : String(next)
      },
      /** 从待二次计重队列中取首条记录（用于回填 form.id 与白条编号） */
      getNextPendingSecondWeightRow(list) {
        const queue = this.getPendingSecondWeightQueue(list)
        return queue.length > 0 ? queue[0] : null
      },
      /**
       * 将“下一条待二次计重记录”回填到表单。
       * 说明：这里需要同步 id，后续 editConvention 才能更新到对应记录。
       */
      assignPendingRowToForm(list) {
        const nextRow = this.getNextPendingSecondWeightRow(list)
        if (!nextRow) {
          this.form.id = null
          this.form.whiteStripNumber = null
          return null
        }
        this.form.id = nextRow.id == null ? null : nextRow.id
        this.form.whiteStripNumber = nextRow.whiteStripNumber == null ? null : String(nextRow.whiteStripNumber)
        return nextRow
      },
      /**
       * 获取“物料生产对应管理”（生产物料映射）列表
       * 用于在常规生产录入时，按(采购品种/级别/毛色)自动匹配物料编码(goodsNum)。
       */
      fetchProductionMaterialMappingList() {
        return getRelatedList({}).then(res => {
          const data = res && res.data ? res.data : res
          this.productionMaterialMappingList = Array.isArray(data) ? data : []
        }).catch(() => {
          this.productionMaterialMappingList = []
        })
      },
      /**
       * 按(采购品种/级别/毛色)匹配“物料生产对应管理”，自动填充 form.goodsNum。
       * 说明：该方法默认“静默匹配”，不在联动过程中弹窗；提交时由 handleConfirm 统一弹 alert。
       */
      tryFillGoodsNumByMapping() {
        if (!this.form) return
        const varietyNo = this.form.procurementVariety
        const levelNo = this.form.grade
        const coatNo = this.form.coatColor
        const process = this.form.processingTechnology

        // 四个字段齐全才尝试匹配（采购品种/级别/毛色/加工工艺）
        if (
          varietyNo == null || varietyNo === '' ||
          levelNo == null || levelNo === '' ||
          coatNo == null || coatNo === '' ||
          process == null || process === ''
        ) {
          return
        }

        const list = Array.isArray(this.productionMaterialMappingList) ? this.productionMaterialMappingList : []
        const hit = list.find(item =>
          item &&
          String(item.varietyNo) === String(varietyNo) &&
          String(item.levelNo) === String(levelNo) &&
          String(item.coatNo) === String(coatNo) &&
          String(item.process) === String(process)
        )

        if (hit && hit.goodsNum != null && String(hit.goodsNum).trim() !== '') {
          this.form.goodsNum = hit.goodsNum
          // 同步带出物料名称（用于表格展示/提交）
          this.form.goodsName = this.getGoodsNameByNum(hit.goodsNum)
          return
        }
        // 未匹配：静默清空，提交时统一提示
        this.form.goodsNum = null
        this.form.goodsName = null
      },
      getLevelLabel(val) {
        const item = getFindByKey(this.levelList, val, 'levelNo')
        return item ? item.levelName : (val ?? '-')
      },
      getCoatLabel(val) {
        const item = getFindByKey(this.coatList, val, 'coatNum')
        return item ? item.coatName : (val ?? '-')
      },
      getQuarantineLabel(val) {
        if (String(val) === '1') return '合格'
        if (String(val) === '0') return '不合格'
        return val ?? '-'
      },
      getProductionTypeLabel(val) {
        const list = (this.dict && this.dict.type && this.dict.type.inventory_production_type) || []
        const hit = list.find(item => String(item.value) === String(val))
        return hit ? hit.label : (val ?? '-')
      },
       /** 加工类型 value -> label（与表单 el-radio 一致：1常规 2精修 3预冷 4分割） */
      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
      },
      getProductionWorkshopLabel(val) {
        const item = getFindByKey(this.productionPlantList, val, 'productionPlantNo')
        return item ? item.productionPlantName : (val ?? '-')
      },
      /**
       * 表格行高亮：高亮当前表单对应的白条记录。
       * 匹配优先级：id > whiteStripNumber（避免仅按编号匹配出现误高亮）。
       */
      getTableRowClassName({ row }) {
        if (!row || !this.form) return ''
        if (this.form.id != null && row.id != null && String(row.id) === String(this.form.id)) {
          return 'active-white-strip-row'
        }
        if (
          this.form.id == null &&
          this.form.whiteStripNumber != null &&
          row.whiteStripNumber != null &&
          String(row.whiteStripNumber) === String(this.form.whiteStripNumber)
        ) {
          return 'active-white-strip-row'
        }
        return ''
      },
      getVarietyLabel(val) {
        const item = getFindByKey(this.varietyList, val, 'varietyNo')
        return item ? item.varietyName : (val ?? '-')
      },
      /** 毛色 **/
      getCoat() {
        getCoatList({}).then(res => {
          this.coatList = res.data
          if (!this.form.coatColor && Array.isArray(this.coatList) && this.coatList.length > 0) {
            this.form.coatColor = this.coatList[0].coatNum
            this.form.coatColorName = this.coatList[0].coatName
          }
        })
      },
      changeCoat(val) {
        let item = getFindByKey(this.coatList, val, 'coatNum')
        if(item) {
          this.form.coatColorName = item.coatName
        }
      },
      /** 级别 **/
      getLevel() {
        getLevelList({}).then(res => {
          this.levelList = res.data
          if (!this.form.grade && Array.isArray(this.levelList) && this.levelList.length > 0) {
            this.form.grade = this.levelList[0].levelNo
            this.form.gradeName = this.levelList[0].levelName
          }
        })
      },
      changeLevel(val) {
        let item = getFindByKey(this.levelList, val, 'levelNo')
        if(item) {
          this.form.gradeName = item.levelName
        }
      },
      /** 品种 **/
      getVariety() {
        getVarietyList({}).then(res => {
          this.varietyList = res.data
        })
      },
      changePurchaseVariety(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
        }
      },
      changeProductionPlant(val) {
        let item = getFindByKey(this.productionPlantList, val, 'productionPlantNo')
        if(item) {
          this.form.productionWorkshopName = item.productionPlantName
        }
      },
      openPlanQueryDialog() {
        this.planQueryDialogOpen = true
        this.planQuerySelectedRow = null
      },
      fetchPlanQueryList() {
        let params = {
           productionType: '1'
        }
        getPlanList(params).then(res => {
          const data = res && res.data ? res.data : res
          this.planQueryList = Array.isArray(data) ? data : []
        }).catch(() => {
          this.planQueryList = []
        })
      },
      handlePlanQueryRowClick(row) {
        this.planQuerySelectedRow = row
        this.$nextTick(() => {
          if (this.$refs.planQueryTable) {
            this.$refs.planQueryTable.setCurrentRow(row)
          }
        })
      },
      handlePlanQueryConfirm() {
        const row = this.planQuerySelectedRow
        if (!row) {
          this.$message.warning("请选择一条生产计划单")
          return
        }
        this.form.productionPlanNumber = row.orderNum || null
        this.selectedPlanId = row.id || null
        this.form.productionType = row.productionType || null
        this.form.productionWorkshop = row.productionPlantNo || null
        this.form.productionWorkshopName = row.productionPlantName || null
        this.form.productionDate = row.orderDate || this.form.productionDate
        // 默认值逻辑
        this.form.quarantineInspection = 1
        this.syncLatestProductionRecordNumber()
        // 按生产计划单号查询常规生产列表并填充表格
        this.fetchConventionByPlanNumber(this.form.productionPlanNumber)
        // 缓存该生产计划单 goods 明细（优先行内，缺失则按 id 补拉）
        const rowGoods = Array.isArray(row.goods) ? row.goods : []
        if (rowGoods.length > 0) {
          this.selectedPlanGoods = rowGoods
          this.planQueryDialogOpen = false
          return
        }
        const id = row && row.id
        if (!id) {
          this.selectedPlanGoods = []
          this.planQueryDialogOpen = false
          return
        }
        getPlanById({ id }).then(res => {
          const data = res && res.data ? res.data : res
          this.selectedPlanGoods = Array.isArray(data && data.goods) ? data.goods : []
        }).finally(() => {
          this.planQueryDialogOpen = false
        })
      },
      fetchConventionByPlanNumber(productionPlanNumber) {
        if (!productionPlanNumber) {
          this.tableData = []
          this.form.id = null
          this.form.whiteStripNumber = null
          this.form.currentWeightKg = 0
          return Promise.resolve()
        }
        return getConventionList({ productionPlanNumber }).then(res => {
          const data = res && res.data ? res.data : res
          const list = Array.isArray(data) ? data : []
          this.tableData = list
          this.assignPendingRowToForm(list)
          this.form.currentWeightKg = 0
        }).catch(() => {
          this.tableData = []
          this.form.id = null
          this.form.whiteStripNumber = null
          this.form.currentWeightKg = 0
        })
      },
      handleConfirm() {
        this.$refs.form.validate(valid => {
          if (!valid) return
          // 提交前兜底：再匹配一次物料编码（goodsNum 必须存在）
          this.tryFillGoodsNumByMapping()
          if (this.form.goodsNum == null || String(this.form.goodsNum).trim() === '') {
            this.$alert('没有对应的物料，请去物料生产对应管理添加', '提示', {
              type: 'warning'
            })
            return
          }
         
          editConvention(this.form).then(() => {
            this.$message.success("提交成功")
            return this.fetchConventionByPlanNumber(this.form.productionPlanNumber)
          }).then(() => {
            // 刷新生产计划单号弹框数据
            this.fetchPlanQueryList()
            // 提交后同步刷新当前生产计划单明细和生猪批次弹框数据
            this.refreshSelectedPlanGoods()
            this.syncLatestProductionRecordNumber()
            const nextRow = this.assignPendingRowToForm(this.tableData)
            // 当所有记录都已有二次计重重量时，按需求重置整个表单。
            if (!nextRow) {
              this.reset()
              this.$nextTick(() => {
                if (this.$refs.form) {
                  this.$refs.form.clearValidate()
                }
              })
              return
            }
            // 队列模式：每次确认后自动切到下一条待二次计重记录（含 id 和白条编号）。
          })
        })
      },
      handleCancel() {
        this.reset()
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      },
      // 白条编号递增（保留旧逻辑，当前页面改为“待二次计重队列”取号，不再使用）
      getNextWhiteStripNumber(list) {
        if (!Array.isArray(list) || list.length === 0) return '00001'
        let maxNum = 0
        let width = 5
        list.forEach(item => {
          const raw = item && item.whiteStripNumber != null ? String(item.whiteStripNumber).trim() : ''
          const digits = raw.replace(/\D/g, '')
          if (!digits) return
          const n = Number(digits)
          if (!Number.isFinite(n)) return
          if (n > maxNum) maxNum = n
          if (digits.length > width) width = digits.length
        })
        const nextNum = maxNum + 1
        return String(nextNum).padStart(width, '0')
      },
      // 白条编号 +1（保留旧逻辑，当前页面改为“待二次计重队列”取号，不再使用）
      incrementWhiteStripNumber(no) {
        const raw = no == null ? '' : String(no).trim()
        const digits = raw.replace(/\D/g, '')
        if (!digits) return '00001'
        const width = Math.max(digits.length, 5)
        const nextNum = Number(digits) + 1
        return String(nextNum).padStart(width, '0')
      },
      // 从接口获取最新生产记录单号
      syncLatestProductionRecordNumber() {
        return getLatestProductionRecordNumber().then(res => {
          const data = res && res.data ? res.data : res
          const latestNo =
            (data && (data.productionRecordNumber || data.recordNumber || data.productionNum || data.number)) ||
            (res && (res.msg || res.message)) ||
            null
          if (latestNo) {
            this.form.productionRecordNumber = latestNo
          }
        })
      },
      onPlanQueryDialogClose() {
        this.planQuerySelectedRow = null
      },
      refreshSelectedPlanGoods() {
        if (!this.selectedPlanId) {
          this.pigBatchList = Array.isArray(this.selectedPlanGoods) ? this.selectedPlanGoods : []
          return Promise.resolve()
        }
        return getPlanById({ id: this.selectedPlanId }).then(res => {
          const data = res && res.data ? res.data : res
          this.selectedPlanGoods = Array.isArray(data && data.goods) ? data.goods : []
          this.pigBatchList = Array.isArray(this.selectedPlanGoods) ? this.selectedPlanGoods : []
        }).catch(() => {
          this.pigBatchList = Array.isArray(this.selectedPlanGoods) ? this.selectedPlanGoods : []
        })
      },
      openPigBatchDialog() {
        if (!this.form.productionPlanNumber) {
          this.$message.warning("请先选择生产计划单号")
          return
        }
        const goods = Array.isArray(this.selectedPlanGoods) ? this.selectedPlanGoods : []
        this.pigBatchList = goods
        if (this.pigBatchList.length === 0) {
          this.$message.warning("当前生产计划单没有可用的生猪批次数据")
          return
        }
        this.pigBatchSelectedRow = null
        this.pigBatchDialogOpen = true
        this.$nextTick(() => {
          if (this.$refs.pigBatchTable) {
            this.$refs.pigBatchTable.setCurrentRow(null)
          }
        })
      },
      handlePigBatchRowClick(row) {
        this.pigBatchSelectedRow = row
        this.$nextTick(() => {
          if (this.$refs.pigBatchTable) {
            this.$refs.pigBatchTable.setCurrentRow(row)
          }
        })
      },
      handlePigBatchConfirm() {
        if (!this.pigBatchSelectedRow) {
          this.$message.warning("请选择一条生猪批次")
          return
        }
        const row = this.pigBatchSelectedRow
        // 生猪批次
        this.form.pigBatch = row.pigBatch || row.batch || null
        // 采购品种
        this.form.procurementVariety = row.procurementVariety || row.varietyNo || row.variety || null
        this.form.procurementVarietyName = row.procurementVarietyName || row.varietyName || null
        // 品种
        this.form.variety = row.variety || row.varietyNo || row.procurementVariety || null
        this.form.varietyName = row.varietyName || row.procurementVarietyName || null
        // 默认值
        this.form.qualityDeduction = 0
        this.form.procurementDeduction = 0
        this.form.processingTechnology = 1
        this.selectedPigBatchQuantity = Number(row.quantity != null ? row.quantity : row.assNum)
        // 生产记录单号统一从接口获取
        this.syncLatestProductionRecordNumber()
        // 生猪批次带出采购品种/级别/毛色后，尝试匹配物料编码
        this.tryFillGoodsNumByMapping()
        this.pigBatchDialogOpen = false
      },
      onPigBatchDialogClose() {
        this.pigBatchSelectedRow = null
      },
      reset() {
        this.form = {
          id: null,
          productionPlanNumber: null,
          productionType: '1',
          productionWorkshop: null,
          productionWorkshopName: null,
          pigBatch: null,
          quarantineInspection: 1,
          procurementVariety: null,
          procurementVarietyName: null,
          productionRecordNumber: null,
          productionDate: null,
          variety: null,
          varietyName: null,
          qualityDeduction: null,
          grade: null,
          gradeName: null,
          coatColor: null,
          coatColorName: null,
          batch: null,
          animalIdentification: null,
          procurementDeduction: null,
          processingType: 1,
          processingTechnology: null,
          whiteStripNumber: null,
          // 物料编码：根据(采购品种/级别/毛色)从“物料生产对应管理”自动匹配
          goodsNum: null,
          // 物料名称：由 goodsNum 反查带出
          goodsName: null,
          currentWeightKg: null,
          quantity: null,
          hookWeight: null,
          preDeductionWeight: null,
          deductionRatio: null,
          suttle: null,
          productionStatus:0
        }
        this.tableData = []
        this.selectedPlanGoods = []
        this.selectedPlanId = null
        this.pigBatchList = []
        this.selectedPigBatchQuantity = 0
      }
    },
    mounted() {
    }
  }
</script>


<style scoped lang="scss">
  .red_left {
    margin-left: 20px;
    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;
    color: red;
  }
  /* 高亮当前白条对应行（作用于 element-ui 表格行） */
  ::v-deep .el-table .active-white-strip-row > td {
    background-color: #fff3cd !important;
  }
</style>
