<template>
  <div class="app-container production-process-page">
    <!-- 上：查询 -->
    <el-card class="section-card section-top" shadow="never">
      <el-divider content-position="left">生产记录检索</el-divider>
      <el-form ref="queryForm" :model="queryParams" :rules="queryRules" size="small" label-width="140px" class="query-form">
        <el-row :gutter="12">
          <el-col :span="6">
            <el-form-item label="生产日期" prop="productionDate">
              <el-date-picker
                v-model="queryParams.productionDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择生产日期"
                clearable
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产类型" prop="productionType">
              <el-select
                v-model="queryParams.productionType"
                placeholder="请选择生产类型"
                clearable
                filterable
                style="width: 100%;"
              >
                <el-option
                  v-for="item in dict.type.inventory_production_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="加工类型" prop="processType">
              <el-select
                v-model="queryParams.processType"
                placeholder="请选择加工类型"
                clearable
                style="width: 100%;"
              >
                <el-option
                  v-for="opt in processTypeOptions"
                  :key="opt.value"
                  :label="opt.label"
                  :value="opt.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="品种" prop="variety">
              <el-select
                v-model="queryParams.variety"
                placeholder="请选择品种"
                clearable
                filterable
                style="width: 100%;"
              >
                <el-option
                  v-for="item in varietyList"
                  :key="item.varietyNo"
                  :label="item.varietyName"
                  :value="item.varietyNo"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="12">
          <el-col :span="6">
            <el-form-item label="级别" prop="grade">
              <el-select
                v-model="queryParams.grade"
                placeholder="请选择级别"
                clearable
                filterable
                style="width: 100%;"
              >
                <el-option
                  v-for="item in levelList"
                  :key="item.levelNo"
                  :label="item.levelName"
                  :value="item.levelNo"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="白条编号区段" prop="whiteNoRange">
              <div class="white-no-range">
                <el-input
                  v-model="queryParams.whiteNoStart"
                  placeholder="起始"
                  clearable
                  size="small"
                  style="width: 140px;"
                />
                <span class="range-sep">到</span>
                <el-input
                  v-model="queryParams.whiteNoEnd"
                  placeholder="结束"
                  clearable
                  size="small"
                  style="width: 140px;"
                />
              </div>
            </el-form-item>
          </el-col> -->
          <el-col :span="6">
            <el-form-item label="动物标识" prop="animalIdentification">
              <el-input
                v-model="queryParams.animalIdentification"
                placeholder="请输入动物标识"
                clearable
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4" :offset="1">
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="12">
          <el-col :span="18">
            <el-form-item label="白条编号检索(以,分割)" label-width="160px" prop="whiteNoSearch">
              <el-input
                v-model="queryParams.whiteNoSearch"
                placeholder="多个白条编号以英文逗号分隔"
                clearable
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4" :offset="1">
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
          </el-col>
        </el-row> -->
      </el-form>
    </el-card>

    <!-- 中 -->
    <el-card class="section-card section-middle" shadow="never">
      <div class="table-panel">
        <el-divider content-position="left">可选白条</el-divider>
        <div class="table-panel-body">
          <el-table
            ref="whiteTable"
            border
            stripe
            height="100%"
            :data="whiteList"
            @selection-change="handleWhiteSelectionChange"
            style="width: 100%;"
          >
            <el-table-column type="selection" width="55" align="center" />
            <!-- whiteList 字段对齐 convention/index.vue 的 tableData（仅使用相同字段） -->
            <el-table-column label="白条编号" prop="whiteStripNumber" min-width="140" />
            <el-table-column label="生产类型" prop="productionType" min-width="100">
              <template slot-scope="scope">
                <span>{{ getProductionTypeLabel(scope.row.productionType) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="加工类型" prop="processingType" min-width="90">
              <template slot-scope="scope">
                <span>{{ getProcessingTypeLabel(scope.row.processingType) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="生猪批次" prop="pigBatch" min-width="120" />
            <el-table-column label="品种" prop="variety" min-width="90">
              <template slot-scope="scope">
                <span>{{ getVarietyLabel(scope.row.variety) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="级别" prop="grade" min-width="80">
              <template slot-scope="scope">
                <span>{{ getLevelLabel(scope.row.grade) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="毛色" prop="coatColor" min-width="80">
              <template slot-scope="scope">
                <span>{{ getCoatLabel(scope.row.coatColor) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="动物标识" prop="animalIdentification" min-width="120" />
            <el-table-column label="生产日期" prop="productionDate" min-width="120" />
            <el-table-column label="生产计划单号" prop="productionPlanNumber" min-width="140" />
            <el-table-column label="生产记录单号" prop="productionRecordNumber" min-width="140" />
            <el-table-column label="生产车间" prop="productionWorkshop" min-width="120">
              <template slot-scope="scope">
                <span>{{ getProductionWorkshopLabel(scope.row.productionWorkshop) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="质量扣分" prop="qualityDeduction" min-width="90" />
            <el-table-column label="采购扣分" prop="procurementDeduction" min-width="90" />
            <el-table-column label="重量" prop="currentWeightKg" min-width="80" />
          </el-table>
        </div>
      </div>
    </el-card>

    <!-- 下：按钮组 -->
    <el-card class="section-card section-bottom" shadow="never">
      <el-divider content-position="left">加工类型转换</el-divider>
      <div class="btn-group-row">
        <el-button size="mini" @click="handleSelectAll">全选</el-button>
        <el-button size="mini" @click="handleSelectNone">全不选</el-button>
        <el-button size="mini" @click="handleSelectInvert">反选</el-button>
        <el-button size="mini" type="primary" plain :disabled="isConvertDisabled('1')" @click="handleConvertTo('1')">将选中白条转成常规</el-button>
        <el-button size="mini" type="primary" plain :disabled="isConvertDisabled('2')" @click="handleConvertTo('2')">将选中白条转成精修</el-button>
        <el-button size="mini" type="primary" plain :disabled="isConvertDisabled('3')" @click="handleConvertTo('3')">将选中白条转成预冷</el-button>
        <el-button size="mini" type="primary" plain :disabled="isConvertDisabled('4')" @click="handleConvertTo('4')">将选中白条转成分割</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getVarietyList } from "@/api/baseInfo/variety";
import { getLevelList } from "@/api/baseInfo/level";
import { getCoatList } from "@/api/baseInfo/coat";
import { batchUpdateProcessingType, getConventionList } from "@/api/production/convention";
import { getProductionPlantList } from "@/api/production/productionPlant";
import { formatDateYMS } from "@/utils";

export default {
  name: "ProductionProcess",
  dicts: ["inventory_production_type"],
  data() {
    return {
      queryParams: {
        productionDate: null,
        productionType: null,
        processType: null,
        variety: null,
        animalIdentification: null,
        grade: null
      },
      /** 查询条件校验：生产日期/生产类型/加工类型必选 */
      queryRules: {
        productionDate: [{ required: true, message: "请选择生产日期", trigger: ["change", "blur"] }],
        productionType: [{ required: true, message: "请选择生产类型", trigger: "change" }],
        processType: [{ required: true, message: "请选择加工类型", trigger: "change" }],
      },
      processTypeOptions: [
        { label: "常规", value: "1" },
        { label: "精修", value: "2" },
        { label: "预冷", value: "3" },
        { label: "分割", value: "4" },
      ],
      varietyList: [],
      levelList: [],
      coatList: [],
      /** 生产车间下拉（productionPlantNo -> productionPlantName） */
      productionPlantList: [],
      whiteList: [],
      whiteSelection: [],
    };
  },
  created() {
    const tomorrow = formatDateYMS(new Date().getTime() + 24 * 60 * 60 * 1000);
    this.queryParams.productionDate = tomorrow;
    this.getVariety();
    this.getLevel();
    this.getCoat();
    this.fetchProductionPlantList();
  },
  methods: {
    /**
     * 生产类型 value -> label（字典取值）
     * @param {string|number} 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 == null || val === "" ? "-" : val)
    },
    getVariety() {
      getVarietyList({}).then((res) => {
        this.varietyList = res.data || [];
      });
    },
    /**
     * 品种 value -> label
     * @param {string|number} val 品种编码
     */
    getVarietyLabel(val) {
      const list = Array.isArray(this.varietyList) ? this.varietyList : []
      const hit = list.find(item => String(item.varietyNo) === String(val))
      return hit ? (hit.varietyName || "-") : (val == null || val === "" ? "-" : val)
    },
    getLevel() {
      getLevelList({}).then((res) => {
        this.levelList = res.data || [];
      });
    },
    /**
     * 级别 value -> label
     * @param {string|number} val 级别编码
     */
    getLevelLabel(val) {
      const list = Array.isArray(this.levelList) ? this.levelList : []
      const hit = list.find(item => String(item.levelNo) === String(val))
      return hit ? (hit.levelName || "-") : (val == null || val === "" ? "-" : val)
    },
    /** 获取毛色下拉数据 */
    getCoat() {
      getCoatList({}).then((res) => {
        this.coatList = res.data || [];
      });
    },
    /**
     * 毛色 value -> label
     * @param {string|number} val 毛色编码
     */
    getCoatLabel(val) {
      const list = Array.isArray(this.coatList) ? this.coatList : []
      const hit = list.find(item => String(item.coatNum) === String(val))
      return hit ? (hit.coatName || "-") : (val == null || val === "" ? "-" : val)
    },
    /** 获取生产车间下拉数据 */
    fetchProductionPlantList() {
      return getProductionPlantList({})
        .then((res) => {
          this.productionPlantList = res.data || [];
        })
        .catch(() => {
          this.productionPlantList = [];
        });
    },
    /**
     * 生产车间 value -> label（按 productionPlantNo 匹配）
     * @param {string|number} val 车间编码
     */
    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（1常规 2精修 3预冷 4分割）
     * @param {string|number} val 加工类型值
     */
    getProcessingTypeLabel(val) {
      const list = Array.isArray(this.processTypeOptions) ? this.processTypeOptions : []
      const hit = list.find(item => String(item.value) === String(val))
      return hit ? hit.label : (val == null || val === "" ? "-" : val)
    },
    handleQuery() {
      this.$refs.queryForm.validate((valid) => {
        if (!valid) return
        getConventionList(this.queryParams).then((res) => {
          this.whiteList = res.data || [];
        });
      })
    },
    handleWhiteSelectionChange(rows) {
      this.whiteSelection = rows || [];
    },
    handleSelectAll() {
      this.$nextTick(() => {
        this.whiteList.forEach((row) => this.$refs.whiteTable.toggleRowSelection(row, true));
      });
    },
    handleSelectNone() {
      this.$refs.whiteTable.clearSelection();
    },
    handleSelectInvert() {
      this.$nextTick(() => {
        this.whiteList.forEach((row) => {
          const selected = this.whiteSelection.some((s) => s.id === row.id);
          this.$refs.whiteTable.toggleRowSelection(row, !selected);
        });
      });
    },
    /**
     * 当查询条件“加工类型 processType”与目标转换类型一致时，禁用对应按钮。
     * @param {string} targetProcessingType 目标加工类型（1常规 2精修 3预冷 4分割）
     */
    isConvertDisabled(targetProcessingType) {
      const current = this.queryParams && this.queryParams.processType != null ? String(this.queryParams.processType) : ""
      const target = targetProcessingType != null ? String(targetProcessingType) : ""
      return !!current && !!target && current === target
    },
    handleConvertTo(type) {
      if (!this.whiteSelection.length) {
        this.$message.warning("请先选择要转换的白条");
        return;
      }
      // 兜底：禁止转换为当前查询的加工类型
      if (this.isConvertDisabled(type)) {
        this.$message.warning("当前已是该加工类型，无需转换")
        return
      }
      /**
       * 转换前二次确认，避免误操作。
       */
      this.$confirm('确定要转化吗？', '提示', { type: 'warning' })
        .then(() => {
          let params = {
            ids: this.whiteSelection.map(item => item.id).join(","),
            processingType: type
          }
          return batchUpdateProcessingType(params)
        })
        .then(() => {
          this.$message.success("转换成功");
          this.handleQuery();
        })
        .catch(() => {})
      
    },
  },
};
</script>

<style scoped>
.production-process-page {
  height: calc(100vh - 90px);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.section-card {
  flex: 0 0 auto;
}

.section-top {
  flex: 0 0 auto;
}

.section-middle {
  flex: 1 1 0;
  min-height: 0;
}

.section-bottom {
  flex: 0 0 auto;
}

.btn-group-row {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.query-form {
  margin-bottom: 0;
}

.white-no-range {
  display: flex;
  align-items: center;
  gap: 8px;
}

.range-sep {
  color: #909399;
  flex-shrink: 0;
}

.table-panel {
  height: 100%;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.table-panel-body {
  flex: 1 1 0;
  min-height: 0;
}

::v-deep .section-middle > .el-card__body {
  height: 100%;
  display: flex;
  flex-direction: column;
}
</style>
