<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">
                    <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">
                    <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-col :span="8">
                <el-form-item label="质量扣分" prop="qualityDeduction">
                  <el-input v-model.number="form.qualityDeduction"></el-input>
                </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-col :span="8">
                <el-form-item label="采购扣分" prop="procurementDeduction">
                  <el-input v-model="form.procurementDeduction"></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>
            <!-- 定级页不展示本次重量、净重；form 仍保留 currentWeightKg、suttle，提交前统一补齐 -->
            <div class="batch-progress red_left" v-if="form.pigBatch">
              <div class="batch-progress-text">批次 {{ currentWhiteStripCount }}/{{ totalWhiteStripCount }}</div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-divider>级别</el-divider>
            <div class="box_item">
              <div v-for="item in levelList" :key="item.levelNo" :class="['item_i', form.grade === item.levelNo ? 'is-active' : '']" @click="clickLevel(item)">{{item.levelName}}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <el-divider>毛色</el-divider>
            <div class="box_item">
              <div v-for="item in coatList" :key="item.coatNum" :class="['item_g', form.coatColor === item.coatNum ? 'is-active' : '']" @click="clickCoat(item)">{{item.coatName}}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <el-divider>质量扣分</el-divider>
            <div class="box_item">
              <div v-for="item in [1,2,3,4, 5,6,7,8,9,0]" :key="`quality-${item}`" :class="['item_i', form.qualityDeduction === item ? 'is-active' : '']" @click="clickMass(item)">{{item}}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <el-divider>采购扣分</el-divider>
            <div class="box_item">
              <div v-for="item in [1,2,3,4, 5,6,7,8,9,0]" :key="`purchase-${item}`" :class="['item_i', form.procurementDeduction === item ? 'is-active' : '']" @click="clickPurchase(item)">{{item}}</div>
            </div>
          </el-col>
        </el-row>
      </el-form>

      <!-- 表格独立，不放在上面表单内 -->
        <br>
        <el-table
          size="mini"
          :data="tableData"
                  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="qualityDeduction" align="center" width="180" ></el-table-column>
          <el-table-column label="采购扣分" prop="procurementDeduction" align="center" width="180" ></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 { addConvention, getConventionList, getLatestProductionRecordNumber } from "../../../api/production/convention";
  import { getPlanById, getPlanList } from "../../../api/production/plan";
  import { getRelatedList } from "../../../api/production/related";

  export default {
    /** 常规生产定级：字段与常规生产页一致，不展示本次重量/净重录入，提交时补齐 */
    name: 'ConventionRank',
    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' }],
          qualityDeduction: [{ required: true, message: '质量扣分不能为空', trigger: 'blur' }],
          procurementDeduction: [{ required: true, message: '采购扣分不能为空', trigger: 'blur' }],
          processingType: [{ required: true, message: '加工类型不能为空', trigger: 'change' }],
          processingTechnology: [{ required: true, message: '加工工艺不能为空', trigger: 'change' }],
          whiteStripNumber: [{ required: true, message: '白条编号不能为空', trigger: 'blur' }],
          // 定级页不录入重量：不做表单项校验，由 ensureHiddenWeightFields 在提交前写入默认值
        },
        productionPlantList: [
          {
            productionPlantNo: '001',
            productionPlantName: '常规生产车间'
          }
        ],
        varietyList: [],
        levelList: [],
        coatList: []
        ,
        /** 物料基础数据（用于 goodsNum -> goodsName 映射显示） */
        materialList: [],
        /** 物料生产对应管理（生产物料映射）列表：用于自动匹配物料编码 goodsNum */
        productionMaterialMappingList: [],
        // 明细表独立数据源（不挂在 form 上）
        tableData: [],
        // 生产计划单查询弹框
        planQueryDialogOpen: false,
        planQueryList: [],
        planQuerySelectedRow: null,
        // 当前所选生产计划单明细（goods）
        selectedPlanGoods: [],
        // 当前所选生产计划单ID（用于刷新明细）
        selectedPlanId: null,
        // 生猪批次查询弹框
        pigBatchDialogOpen: false,
        pigBatchList: [],
        pigBatchSelectedRow: null,
        // 选中生猪批次对应数量（用于白条进度计算）
        selectedPigBatchQuantity: 0
      }
    },
    computed: {
      // 总白条数 = 选中生猪批次数量 * 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 || '-') : '-'
      },
      /**
       * 获取“物料生产对应管理”（生产物料映射）列表
       * 用于按(采购品种/级别/毛色/加工工艺)自动匹配物料编码(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 ?? '-')
      },
      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
        }
      },
      /** 定级页：快捷选择毛色（与下拉联动） */
      clickCoat(val) {
        this.form.coatColor = val.coatNum
        this.form.coatColorName = val.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
        }
      },
      /** 定级页：快捷选择级别（与下拉联动） */
      clickLevel(val) {
        this.form.grade = val.levelNo
        this.form.gradeName = val.levelName
      },
      clickMass(val) {
        this.form.qualityDeduction = val
      },
      clickPurchase(val) {
        this.form.procurementDeduction = val
      },
      /** 品种 **/
      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.whiteStripNumber = '00001'
          this.form.currentWeightKg = null
          this.form.suttle = null
          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.form.whiteStripNumber = this.getNextWhiteStripNumber(list)
          this.form.currentWeightKg = null
          this.form.suttle = null
        }).catch(() => {
          this.tableData = []
          this.form.whiteStripNumber = '00001'
          this.form.currentWeightKg = null
          this.form.suttle = null
        })
      },
      handleConfirm() {
        if (String(this.form.productionStatus) === '1') {
          this.$message.warning("已经生产完了，请选择其他生产计划单号")
          return
        }
        if (
          this.totalWhiteStripCount > 0 &&
          this.currentWhiteStripCount >= this.totalWhiteStripCount
        ) {
          this.$message.warning("已经生产完了，请选择其他生产计划单号")
          return
        }
        this.$refs.form.validate(valid => {
          if (!valid) return
          // 提交前判断：当前批次数 + 1 = 最大批次数，则本次提交状态置为生产完成
          if (
            this.totalWhiteStripCount > 0 &&
            this.currentWhiteStripCount + 1 === this.totalWhiteStripCount
          ) {
            this.form.productionStatus = 1
          }
          /** 定级页不展示重量录入：补齐与接口一致的字段 */
          this.ensureHiddenWeightFields()
          // 提交前兜底：匹配物料编码（goodsNum 必须存在）
          this.tryFillGoodsNumByMapping()
          if (this.form.goodsNum == null || String(this.form.goodsNum).trim() === '') {
            this.$alert('没有对应的物料，请去物料生产对应管理添加', '提示', {
              type: 'warning'
            })
            return
          }
          const submittedWhiteStripNumber = this.form.whiteStripNumber
          addConvention(this.form).then(() => {
            this.$message.success("提交成功")
            return this.fetchConventionByPlanNumber(this.form.productionPlanNumber)
          }).then(() => {
            // 刷新生产计划单号弹框数据
            this.fetchPlanQueryList()
            // 提交后同步刷新当前生产计划单明细和生猪批次弹框数据
            this.refreshSelectedPlanGoods()
            this.syncLatestProductionRecordNumber()
            // 白条编号：确认成功后按“本次提交值”递增 1，便于下一次录入
            this.form.whiteStripNumber = this.incrementWhiteStripNumber(submittedWhiteStripNumber)
          })
        })
      },
      handleCancel() {
        this.reset()
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      },
      /**
       * 定级页不展示本次重量、净重：提交前写入默认值，与常规生产接口字段一致。
       * 若后续需从其他环节带入真实重量，可在此赋值。
       */
      ensureHiddenWeightFields() {
        const w = this.form.currentWeightKg
        if (w === null || w === undefined || w === '') {
          this.form.currentWeightKg = null
        }
        const s = this.form.suttle
        if (s === null || s === undefined || s === '') {
          this.form.suttle = null
        }
      },
      // 白条编号递增：空列表默认 00001；有值取最后一条 +1，并按原位数补零
      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 = {
          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,
          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;
  }
  .box_item {
    width: 100%;
    height: 250px;
    box-sizing: border-box;
    border: 1px solid #ddd;
    display: flex;
    flex-flow: row wrap;
  }
  .box_item::-webkit-scrollbar{
    display: none;
  }
  .item_i {
    text-align: center;
    width: 50%;
    height: 50px;
    line-height: 50px;
    box-sizing: border-box;
    cursor: pointer;
  }
  .item_i:nth-child(4n+1),
  .item_i:nth-child(4n+2) {
    background-color: #F5F8EF;
  }

  .item_i:nth-child(4n+3),
  .item_i:nth-child(4n+4) {
    background-color: #F0F0E7;
  }
  .item_i:nth-child(odd) {
    border-bottom: 1px solid #ddd;
    border-right: 1px solid #ddd;
  }
  .item_i:nth-child(even) {
    border-bottom: 1px solid #ddd;
  }
  .item_g {
    text-align: center;
    width: 100%;
    height: 50px;
    line-height: 50px;
    box-sizing: border-box;
    border-bottom: 1px solid #ddd;
    //margin: -1px; /* 关键：负外边距使边框向外覆盖 */
    cursor: pointer;
  }
  .item_g:nth-child(odd) {
    background-color: #F5F8EF; /* 奇数行背景色 */
  }

  .item_g:nth-child(even) {
    background-color: #F0F0E7; /* 偶数行背景色 */
  }
  .is-active {
    background: #00afff !important;
    color: #fff;
  }
  .batch-progress-text {
    font-size: 40px;
    line-height: 1.2;
    font-weight: 700;
    color: red;
  }
</style>
