<template>
  <div class="app-container">
    <el-card>
      <div class="page-header">分割品副产品生产</div>
      <el-form ref="form" :model="form" :rules="formRules" label-width="120px">
        <el-row :gutter="24" class="form-three-cols">
          <!-- 左列：生产记录单号、生产日期、生猪批次、计量单位、辅助计量单位 -->
          <el-col :span="8" 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="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="pigBatch">
              <el-input v-model="form.pigBatch"></el-input>
            </el-form-item>
            <el-form-item label="计量单位" prop="measurementUnit">
              <el-input v-model="form.measurementUnit" disabled></el-input>
            </el-form-item>
            <el-form-item label="辅助计量单位" prop="auxiliaryMeasurementUnit">
              <el-input v-model="form.auxiliaryMeasurementUnit" disabled></el-input>
            </el-form-item>
          </el-col>
          <!-- 中列：生产类型、生产计划单号、物料编号、计重数量、辅助数量 -->
          <el-col :span="8" class="form-col">
            <el-form-item label="生产类型" prop="productionType">
              <el-select v-model="form.productionType" placeholder="生产类型" 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="productionPlanNumber">
              <el-input v-model="form.productionPlanNumber" placeholder="请选择生产计划单号" readonly>
                <template #append>
                  <el-button
                    type="primary"
                    icon="el-icon-search"
                    @click="openPlanQueryDialog"
                  />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="物料编号" prop="materialCode">
              <el-input v-model="form.materialCode" placeholder="请选择物料编号" readonly>
                <template #append>
                  <el-button
                    type="primary"
                    icon="el-icon-search"
                    @click="openQueryMaterial"
                  />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="计重数量" prop="weightQuantity">
              <decimal-input
                v-model="form.weightQuantity"
                :min="0"
                :max="999999"
                :precision="2"
              />
            </el-form-item>
            <el-form-item label="辅助数量" prop="auxiliaryQuantity">
              <decimal-input
                v-model="form.auxiliaryQuantity"
                :min="0"
                :max="999999"
                :precision="2"
              />
            </el-form-item>
          </el-col>
          <!-- 右列：生产车间、质检结果、物料名称、皮重、计重重量 -->
          <el-col :span="8" 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="materialName">
              <el-input v-model="form.materialName" disabled></el-input>
            </el-form-item>
            <el-form-item label="皮重" prop="peelWeight">
              <decimal-input
                v-model="form.peelWeight"
                :min="0"
                :max="999999"
                :precision="2"
              />
            </el-form-item>
            <el-form-item label="计重重量" prop="totalWeight">
              <decimal-input
                v-model="form.totalWeight"
                :min="0"
                :max="999999"
                :precision="2"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item>
              <el-button type="primary" @click="handleConfirm">确认</el-button>
              <el-button @click="handleCancel">取消</el-button>
            </el-form-item>
          </el-col>
        </el-row>
       
      </el-form>
        <br>
       <el-table
          ref="mainTable"
          size="mini"
          :data="tableData"
          style="width: 100%;"
          border
          stripe
          highlight-current-row
          @row-click="handleTableRowClick"
        >
          <el-table-column label="生产记录单号" align="center" width="150" prop="productionRecordNumber" min-width="150"></el-table-column>
          <el-table-column label="生产计划单号" align="center" width="150" prop="productionPlanNumber" min-width="150"></el-table-column>
          <el-table-column label="生产日期" align="center" width="120" prop="productionDate" min-width="120"></el-table-column>
          <el-table-column label="生产车间" align="center" width="140" prop="productionWorkshop" min-width="140">
            <template slot-scope="scope">
              <span>{{ getProductionWorkshopLabel(scope.row.productionWorkshop) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料编号" align="center" width="120" prop="materialCode" min-width="120"></el-table-column>
          <el-table-column label="物料名称" align="center" width="140" prop="materialName" min-width="140"></el-table-column>
          <el-table-column label="规格型号" align="center" width="120" prop="specificationModel" 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="productionType" min-width="120">
            <template slot-scope="scope">
              <span>{{ getProductionTypeLabel(scope.row.productionType) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="仓库" align="center" width="160" prop="warehouse" min-width="160" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ getWarehouseLabel(scope.row.warehouse) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="皮重" align="center" width="100" prop="peelWeight" min-width="100"></el-table-column>
          <el-table-column label="计重数量" align="center" width="100" prop="weightQuantity" min-width="100"></el-table-column>
          <el-table-column label="计量单位" align="center" width="100" prop="measurementUnit" min-width="100"></el-table-column>
          <el-table-column label="辅助数量" align="center" width="100" prop="auxiliaryQuantity" min-width="100"></el-table-column>
          <el-table-column label="辅助计量单位" align="center" width="120" prop="auxiliaryMeasurementUnit" min-width="120"></el-table-column>
          <el-table-column label="质检结果" align="center" width="100" prop="qualityInspectionResult" min-width="100">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.qualityInspectionResult === '1'" type="success">合格</el-tag>
              <el-tag v-else-if="scope.row.qualityInspectionResult === '0'" type="danger">不合格</el-tag>
              <span v-else>{{ scope.row.qualityInspectionResult }}</span>
            </template>
          </el-table-column>
        </el-table>
      <div class="bottom-actions">
        <el-button :disabled="!selectedRow" @click="handleModify">修改</el-button>
      </div>

      <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="160" />
          <el-table-column label="生产类型" prop="productionType" align="center" min-width="120">
            <template slot-scope="scope">
              <span>{{ getProductionTypeLabel(scope.row.productionType) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="生产车间" prop="productionPlantName" align="center" min-width="160" show-overflow-tooltip />
        </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>

      <!-- 物料速查弹窗（复用全局 queryMaterial.vue） -->
      <query-material
        ref="queryMaterial"
        :is-multiple="false"
        :exclude-goods-nums="[]"
        @selectList="handleMaterialSelectList"
      />
    </el-card>
  </div>
</template>
<script>
  import { getProductionPlantList } from "../../../api/production/productionPlant";
  import { getPlanList } from "../../../api/production/plan";
  import { getLatestProductionRecordNumber } from "../../../api/production/convention";
  import { addByProduct, editByProduct, getByProductList } from "../../../api/production/byProduct";
  import { getWareHouseList } from "../../../api/inventory/wareHouse";
  import QueryMaterial from "../../components/queryMaterial.vue";

  export default {
    name: 'ByProduct',
    dicts: ['inventory_production_type'],
    components: { QueryMaterial },
    data() {
      return {
        form: {},
        formRules: {},
        /** 下方表格单选：当前选中行 */
        selectedRow: null,
        /** 生产车间下拉（由接口拉取 productionPlantNo / productionPlantName） */
        productionPlantList: [],
        /** 仓库下拉（用于表格 value->label 映射展示） */
        warehouseList: [],
        /** 生产计划单查询弹框 */
        planQueryDialogOpen: false,
        planQueryList: [],
        planQuerySelectedRow: null,
        tableData: []
      }
    },
    created() {
      this.reset();
      this.fetchProductionPlantList();
      this.fetchWarehouseList();
      this.fetchPlanQueryList();
      this.getList();
    },
    watch: {
      /**
       * 计重重量变化时，同步计重数量保持一致。
       * 说明：仅单向同步（totalWeight -> weightQuantity），避免互相覆盖。
       */
      "form.totalWeight": function (val) {
        if (!this.form) return
        if (this.form.weightQuantity === val) return
        this.form.weightQuantity = val
      }
    },
    methods: {
        /** 明天日期 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}`
      },
      getList() {
        let params = {
          productionDate: this.getTomorrowDateString()
        }
        getByProductList(params).then(res => {
          this.tableData = res.data
          // 刷新列表后清空表格选中态，避免误操作修改旧行
          this.selectedRow = null
        })
      },
      /**
       * 下方表格行点击：单选高亮并保存当前行。
       * @param {Object} row 当前点击行
       */
      handleTableRowClick(row) {
        this.selectedRow = row || null
        this.$nextTick(() => {
          if (this.$refs && this.$refs.mainTable && this.$refs.mainTable.setCurrentRow) {
            this.$refs.mainTable.setCurrentRow(row)
          }
        })
      },
      /** 拉取生产车间下拉数据 */
      fetchProductionPlantList() {
        return getProductionPlantList({})
          .then((res) => {
            const data = res && res.data != null ? res.data : res
            this.productionPlantList = Array.isArray(data) ? data : []
          })
          .catch(() => {
            this.productionPlantList = []
          })
      },
      /** 拉取仓库列表，用于 value->label 映射展示 */
      fetchWarehouseList() {
        return getWareHouseList({})
          .then((res) => {
            const data = res && res.data != null ? res.data : res
            this.warehouseList = Array.isArray(data) ? data : []
          })
          .catch(() => {
            this.warehouseList = []
          })
      },
      /** 生产类型 value -> label（字典取值） */
      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 == null || val === '' ? '-' : val)
      },
      /**
       * 生产车间 value -> label（按 productionPlantNo 匹配）
       */
      getProductionWorkshopLabel(val) {
        const list = Array.isArray(this.productionPlantList) ? this.productionPlantList : []
        const hit = list.find(item => String(item.productionPlantNo) === String(val))
        return hit ? (hit.productionPlantName || '-') : (val == null || val === '' ? '-' : val)
      },
      /**
       * 仓库 value -> label（兼容 val 可能已是名称）。
       * 后端字段不统一时，尽量按常见字段名做兜底：warehouseNo/warehouseCode/value/code。
       */
      getWarehouseLabel(val) {
        if (val == null || val === '') return '-'
        const v = String(val)
        const list = Array.isArray(this.warehouseList) ? this.warehouseList : []
        const hit = list.find(item =>
          item &&
          String(item.warehouseNo || item.warehouseCode || item.value || item.code) === v
        )
        const name = hit && (hit.warehouseName || hit.name || hit.label)
        return name ? name : v
      },
      /** 打开生产计划单查询弹框 */
      openPlanQueryDialog() {
        this.planQueryDialogOpen = true
        this.planQuerySelectedRow = null
      },
      /** 弹框关闭：清空当前选择 */
      onPlanQueryDialogClose() {
        this.planQuerySelectedRow = null
      },
      /** 拉取生产计划单列表（用于弹框查询） */
      fetchPlanQueryList() {
        const params = {
          productionType: '4'
        }
        return getPlanList(params)
          .then((res) => {
            const data = res && res.data != null ? 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.form.productionType = row.productionType || null
        this.form.productionWorkshop = row.productionPlantNo || null
        this.form.productionDate = row.orderDate || this.form.productionDate
        getLatestProductionRecordNumber().then(res => {
          this.form.productionRecordNumber = res.msg
        })
        .catch(() => {
          this.form.productionRecordNumber = null
        })
        this.planQueryDialogOpen = false
      },
      /**
       * 打开物料速查弹窗（单选）。
       */
      openQueryMaterial() {
        if (this.$refs.queryMaterial && this.$refs.queryMaterial.open) {
          this.$refs.queryMaterial.open()
        }
      },
      /**
       * 物料速查回填（单选模式下返回数组，取第一项）。
       * @param {Array<Object>} list 选中的物料列表
       */
      handleMaterialSelectList(list) {
        const row = Array.isArray(list) && list.length > 0 ? list[0] : null
        if (!row) return
        if (row.productType !== '003') { this.$message.warning("该物料不是分割品副产品"); return }
        // 物料编号/名称
        this.form.materialCode = row.goodsNum || null
        this.form.materialName = row.goodsName || null
        // 计量单位/辅助计量单位（queryMaterial 字段：unit/assistantUnit）
        this.form.measurementUnit = row.unit || null
        this.form.auxiliaryMeasurementUnit = row.assistantUnit || null
        // 规格型号（queryMaterial 字段：goodsSpec）
        this.form.specificationModel = row.goodsSpec || null
        // 仓库（若需要回填仓库名称，后端通常会返回 warehouseName）
        this.form.warehouse = row.warehouseNo
        // 当选择完物料后，计重数量，辅助数量，皮重，计重重量都为0
        this.$nextTick(() => {    
          this.form.weightQuantity = 0
          this.form.auxiliaryQuantity = 0
          this.form.peelWeight = 0
          this.form.totalWeight = 0
        })
      },
      /**
       * 表格内质检结果展示格式化（保持字段值为后端所需的 0/1）。
       */
      formatQualityInspectionResult(row) {
        if (row.qualityInspectionResult === 1) return '合格';
        if (row.qualityInspectionResult === 0) return '不合格';
        return row.qualityInspectionResult;
      },
      /**
       * 保存成功后清空本次录入的明细字段，便于继续录下一条。
       * 仅清空与“物料 + 计量”相关字段，不影响生产计划等头信息。
       */
      clearMaterialAndMeasureFields() {
        if (!this.form) return
        this.form.id = null
        this.form.materialCode = null
        this.form.materialName = null
        this.form.measurementUnit = null
        this.form.weightQuantity = null
        this.form.peelWeight = null
        this.form.auxiliaryMeasurementUnit = null
        this.form.auxiliaryQuantity = null
        this.form.totalWeight = null
      },
      handleConfirm() {
        this.$refs.form.validate(valid => {
          if (valid) {
            if(this.form.id) {
              editByProduct(this.form).then(res => {
                this.$message.success('修改成功');
                this.getList();
                this.clearMaterialAndMeasureFields();
              })
            } else {
              addByProduct(this.form).then(res => {
                this.$message.success('新增成功');
                this.getList();
                this.clearMaterialAndMeasureFields();
              })
            }
          }
        });
      },
      handleCancel() {
        this.reset();
      },
      handleModify() {
        /**
         * 将表格选中行回填到表单，进入“修改”状态。
         * 说明：保持字段名一致（小驼峰），以便直接调用 editByProduct。
         */
        if (!this.selectedRow) {
          this.$message.warning('请先选择一条数据')
          return
        }
        const r = this.selectedRow
        this.form.id = r.id ?? null
        this.form.productionRecordNumber = r.productionRecordNumber ?? null
        this.form.productionType = r.productionType ?? null
        this.form.productionWorkshop = r.productionWorkshop ?? null
        this.form.productionDate = r.productionDate ?? null
        this.form.productionPlanNumber = r.productionPlanNumber ?? null
        this.form.qualityInspectionResult = r.qualityInspectionResult ?? this.form.qualityInspectionResult
        this.form.pigBatch = r.pigBatch ?? null
        this.form.materialCode = r.materialCode ?? null
        this.form.materialName = r.materialName ?? null
        this.form.measurementUnit = r.measurementUnit ?? null
        this.form.weightQuantity = r.weightQuantity ?? null
        this.form.peelWeight = r.peelWeight ?? null
        this.form.totalWeight = r.totalWeight ?? null
        this.form.auxiliaryMeasurementUnit = r.auxiliaryMeasurementUnit ?? null
        this.form.auxiliaryQuantity = r.auxiliaryQuantity ?? null
        this.form.specificationModel = r.specificationModel ?? null
        this.form.warehouse = r.warehouse ?? null
        this.form.quantity = r.quantity ?? null
      },
      reset() {
        this.form = {
          id: null,
          productionRecordNumber: null,
          productionType: null,
          productionWorkshop: null,
          productionDate: null,
          productionPlanNumber: null,
          qualityInspectionResult: '1',
          pigBatch: null,
          materialCode: null,
          materialName: null,
          measurementUnit: null,
          weightQuantity: null,
          peelWeight: null,
          totalWeight: null,
          auxiliaryMeasurementUnit: null,
          auxiliaryQuantity: null,
          specificationModel: null,
          warehouse: null,
        };
      }
    },
    mounted() {}
  }
</script>

<style scoped lang="scss">
  .page-header {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 20px;
  }
  .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;
  }
  .bottom-actions {
    margin-top: 20px;
    padding-top: 16px;
    border-top: 1px solid #ebeef5;
  }
</style>
