<template>
  <div class="app-container">
    <el-card>
      <div class="page-header">分割生产白条领料</div>
      <el-form ref="queryForm" :model="queryForm" label-width="120px" class="query-form">
        <el-row :gutter="16">
          <el-col :span="6">
            <el-form-item label="生产记录单日期" prop="recordDateRange">
              <el-date-picker
                v-model="queryForm.startDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="开始日期"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="至">
              <el-date-picker
                v-model="queryForm.endDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="结束日期"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产计划单日期" prop="whiteStripDate">
              <el-date-picker
                v-model="queryForm.whiteStripDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="6">
            <el-form-item label="生产类型" prop="productionType">
              <el-select v-model="queryForm.productionType" placeholder="生产类型" style="width: 100%">
                <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="6">
            <el-form-item label="品种" prop="varietyRange">
              <el-select v-model="queryForm.variety" placeholder="品种" style="width: 100%">
                <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-col :span="6">
            <el-form-item label="动物标识" prop="animalIdentification">
              <el-input v-model="queryForm.animalIdentification" placeholder="动物标识"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="6">
            <el-form-item label="级别" prop="startGrade">
              <el-select v-model="queryForm.startGrade" placeholder="级别" style="width: 100%">
                <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="6">
            <el-form-item label="至">
              <el-select v-model="queryForm.endGrade" placeholder="级别" style="width: 100%">
                <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="6">
            <el-form-item label="质检结果" prop="qualityInspectionResult">
              <el-select v-model="queryForm.qualityInspectionResult" placeholder="质检结果" style="width: 100%">
                <el-option :value="1" label="合格"></el-option>
                <el-option :value="0" label="不合格"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="6">
            <el-form-item label="白条编号" prop="startWhiteStripNum">
              <el-input v-model="queryForm.startWhiteStripNum" placeholder="白条编号" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="至" prop="endWhiteStripNum">
              <el-input v-model="queryForm.endWhiteStripNum" placeholder="白条编号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" class="query-buttons">
            <el-form-item>
              <el-button type="primary" :disabled="allocationQueryDisabled" @click="handleQuery">查询</el-button>
              <el-button @click="handleClose">关闭</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div class="table-section">
        <el-row :gutter="16">
          <el-col :span="3">
            <div class="table-title">生产计划单</div>
          </el-col>
          <el-col :span="21">
            <div class="table-title">可领用白条</div>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="3">
            <div class="box_item plan-list">
              <div
                v-for="(item, idx) in planList"
                :key="getPlanKey(item) || idx"
                class="plan-item"
                :class="getPlanKey(item) === selectedPlanKey ? 'is-active' : ''"
                @click="handlePlanSelect(item)"
              >
                {{ getPlanDisplayText(item) }}
              </div>
            </div>
          </el-col>
          <el-col :span="21">
            <el-table
              ref="availableTable"
              size="mini"
              :data="availableList"
              style="width: 100%;"
              border
              stripe
              height="280"
              @row-click="handleAvailableRowClick"
            >
              <el-table-column label="白条编号" align="center" width="120" prop="whiteStripNumber" min-width="120"></el-table-column>
              <el-table-column label="品种" align="center" width="100" min-width="100">
                <template slot-scope="scope">
                  <span>{{ getRowVarietyLabel(scope.row.variety) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="级别" align="center" width="100" min-width="100">
                <template slot-scope="scope">
                  <span>{{ getRowLevelLabel(scope.row.grade) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="生产类型" align="center" width="100" min-width="100">
                <template slot-scope="scope">
                  <span>{{ getRowProductionTypeLabel(scope.row.productionType) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="加工类型" align="center" width="100" min-width="100">
                <template slot-scope="scope">
                  <span>{{ getRowProcessingTypeLabel(scope.row.processingType) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="重量" align="center" width="100" prop="currentWeightKg" min-width="100"></el-table-column>
              <el-table-column label="物料编码" align="center" width="120" prop="goodsNum" min-width="120"></el-table-column>
              <el-table-column label="物料名称" align="center" width="120" min-width="120">
                <template slot-scope="scope">
                  <span>{{ getRowMaterialNameLabel(scope.row.goodsNum) }}</span>
                </template>
              </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="120" prop="animalIdentification" min-width="120"></el-table-column>
              <el-table-column label="采购品种" align="center" width="120" min-width="120">
                <template slot-scope="scope">
                  <span>{{ getRowVarietyLabel(scope.row.procurementVariety) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="采购级别" align="center" width="100" min-width="100">
                <template slot-scope="scope">
                  <span>{{ getRowLevelLabel(scope.row.procurementGrade) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="扣重前重量" align="center" width="120" prop="preDeductionWeight" min-width="120"></el-table-column>
              <el-table-column label="扣重比例%" align="center" width="100" prop="deductionRatio" min-width="100"></el-table-column>
            </el-table>
            <br>
            <div class="table-section">
              <div class="table-title">领料结果</div>
              <el-table
                ref="resultTable"
                size="mini"
                :data="resultList"
                style="width: 100%;"
                border
                stripe
                max-height="280"
                @row-click="handleResultRowClick"
              >
                 <el-table-column label="白条编号" align="center" width="120" prop="whiteStripNumber" min-width="120"></el-table-column>
              <el-table-column label="品种" align="center" width="100" min-width="100">
                <template slot-scope="scope">
                  <span>{{ getRowVarietyLabel(scope.row.variety) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="级别" align="center" width="100" min-width="100">
                <template slot-scope="scope">
                  <span>{{ getRowLevelLabel(scope.row.grade) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="生产类型" align="center" width="100" min-width="100">
                <template slot-scope="scope">
                  <span>{{ getRowProductionTypeLabel(scope.row.productionType) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="加工类型" align="center" width="100" min-width="100">
                <template slot-scope="scope">
                  <span>{{ getRowProcessingTypeLabel(scope.row.processingType) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="重量" align="center" width="100" prop="currentWeightKg" min-width="100"></el-table-column>
              <el-table-column label="物料编码" align="center" width="120" prop="goodsNum" min-width="120"></el-table-column>
              <el-table-column label="物料名称" align="center" width="120" min-width="120">
                <template slot-scope="scope">
                  <span>{{ getRowMaterialNameLabel(scope.row.goodsNum) }}</span>
                </template>
              </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="120" prop="animalIdentification" min-width="120"></el-table-column>
              <el-table-column label="采购品种" align="center" width="120" min-width="120">
                <template slot-scope="scope">
                  <span>{{ getRowVarietyLabel(scope.row.procurementVariety) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="采购级别" align="center" width="100" min-width="100">
                <template slot-scope="scope">
                  <span>{{ getRowLevelLabel(scope.row.procurementGrade) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="扣重前重量" align="center" width="120" prop="preDeductionWeight" min-width="120"></el-table-column>
              <el-table-column label="扣重比例%" align="center" width="100" prop="deductionRatio" min-width="100"></el-table-column>
              </el-table>
            </div>
          </el-col>
        </el-row>
      </div>


      <div class="bottom-actions">
        <el-button :disabled="allocationStartDisabled" @click="handleStartAllocate">开始分配</el-button>
        <el-button :disabled="allocationCancelDisabled" @click="handleCancelAllocate">取消分配</el-button>
        <el-button type="primary" :disabled="allocationCompleteDisabled" @click="handleCompleteAllocate">完成分配</el-button>
      </div>
    </el-card>
  </div>
</template>
<script>
  import { getPlanList } from "../../../api/production/plan";
  import { getSegmentationWhiteList, addSegmentationWhite } from "../../../api/production/segmentation";
  import { getVarietyList } from "../../../api/baseInfo/variety";
  import { getLevelList } from "../../../api/baseInfo/level";
  import { getMaterialList } from "../../../api/baseInfo/material";
  export default {
    name: 'Segmentation',
    dicts: ["inventory_production_type"],
    data() {
      return {
        queryForm: {
          startDate: null,
          endDate: null,
          productionType: null,
          variety: null,
          animalIdentification: null,
          startGrade: null,
          endGrade: null,
          inspectResult: null,
          startWhiteStripNum: null,
          endWhiteStripNum: null,
          qualityInspectionResult: null,
          processingType: '4'
        },
        availableList: [],
        resultList: [],
        planList: [],
        varietyList: [],
        levelList: [],
        materialList: [],
        /** 左侧选中的生产计划 key（用于行高亮） */
      selectedPlanKey: null,
      /** 分配流程状态位：控制查询/开始/取消/完成按钮 */
      allocationQueryDisabled: false,
      allocationStartDisabled: false,
      allocationCancelDisabled: true,
        allocationCompleteDisabled: true,
        /** 分配取消时的原始快照（用于恢复左右两表） */
        allocationAvailableSnapshot: null,
        allocationResultSnapshot: null,
      }
    },
    created() {
      this.resetQuery()
      this.getPlan()
      this.getVariety()
      this.getLevel()
      this.getMaterial()
    },
    methods: {
      /** 品种 **/
      getVariety() {
        getVarietyList().then(res => {
          this.varietyList = res.data || []
        })
      },
      /** 级别 **/
      getLevel() {
        getLevelList().then(res => {
          this.levelList = res.data || []
        })
      },
      /** 物料基础数据：goodsNum -> goodsName（用于表格“物料名称”） */
      getMaterial() {
        getMaterialList({}).then(res => {
          const data = res && res.data != null ? res.data : res
          this.materialList = Array.isArray(data) ? data : []
        }).catch(() => {
          this.materialList = []
        })
      },
      /**
       * 品种 value -> label（供可领用白条表格使用）
       * @param {string|number|null} val 品种编码
       */
      getRowVarietyLabel(val) {
        if (val === null || val === undefined || val === '') return '-'
        const hit = (this.varietyList || []).find((v) => v && String(v.varietyNo) === String(val))
        return hit ? (hit.varietyName || '-') : String(val)
      },
      /**
       * 级别 value -> label（供可领用白条表格使用）
       * @param {string|number|null} val 级别编码
       */
      getRowLevelLabel(val) {
        if (val === null || val === undefined || val === '') return '-'
        const hit = (this.levelList || []).find((l) => l && String(l.levelNo) === String(val))
        return hit ? (hit.levelName || '-') : String(val)
      },
      /**
       * 生产类型 value -> label（字典 inventory_production_type）
       * @param {string|number|null} val 生产类型 value
       */
      getRowProductionTypeLabel(val) {
        if (val === null || val === undefined || val === '') return '-'
        const list = (this.dict && this.dict.type && this.dict.type.inventory_production_type) ? this.dict.type.inventory_production_type : []
        const hit = list.find((item) => item && String(item.value) === String(val))
        return hit ? (hit.label || '-') : String(val)
      },
      /**
       * 加工类型 value -> label
       * 当前页面 processingType：2 精修、3 预冷、4 分割
       * @param {string|number|null} val 加工类型 value
       */
      getRowProcessingTypeLabel(val) {
        if (val === null || val === undefined || val === '') return '-'
        const map = { 1: '常规', 2: '精修', 3: '预冷', 4: '分割' }
        const key = String(val)
        return map[key] || String(val)
      },
      /**
       * 物料名称 goodsNum -> goodsName
       * @param {string|number|null} goodsNum 物料编码
       */
      getRowMaterialNameLabel(goodsNum) {
        if (goodsNum === null || goodsNum === undefined || goodsNum === '') return '-'
        const key = String(goodsNum).trim()
        const hit = (this.materialList || []).find((m) => m && String(m.goodsNum) === key)
        return hit ? (hit.goodsName || '-') : key
      },
      /** 明天日期 yyyy-MM-dd，与 el-date-picker 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}`
      },
      /** 生产计划单号 **/
      getPlan() {
        let params = {
          startDate: this.getTomorrowDateString(),
          endDate: this.getTomorrowDateString(),
          productionType: '5',
        
        }
        getPlanList(params).then(res => {
          this.planList = Array.isArray(res && res.data) ? res.data : []
          // 首次加载默认选中第一条
          if (!this.selectedPlanKey && this.planList.length > 0) {
            this.selectedPlanKey = this.getPlanKey(this.planList[0])
          }
        })
      },
      /**
       * 获取生产计划唯一 key（优先 id，其次 orderNum）
       * @param {Object} item 生产计划项
       */
      getPlanKey(item) {
        if (!item || typeof item !== 'object') return null
        if (item.orderNum != null) return item.orderNum
        return null
      },
      /**
       * 左侧列表展示文本（优先 orderNum）
       * @param {Object} item 生产计划项
       */
      getPlanDisplayText(item) {
        if (!item || typeof item !== 'object') return '-'
        return item.orderNum || item.productionPlanNumber || item.planNum || item.id || '-'
      },
      /**
       * 左侧生产计划点击：设置当前选中，用于高亮
       * @param {Object} item 生产计划项
       */
      handlePlanSelect(item) {
        const key = this.getPlanKey(item)
        // 同一项再次点击：取消选中（高亮消失）
        if (this.selectedPlanKey != null && String(this.selectedPlanKey) === String(key)) {
          this.selectedPlanKey = null
          return
        }
        this.selectedPlanKey = key
        // TODO：若后续要联动筛选可领用白条/结果表，可在此处接入对应接口调用
      },
      handleQuery() {
        // TODO: 调用查询接口，刷新可领用白条列表
        getSegmentationWhiteList(this.queryForm).then(res => {
          this.availableList = res.data || []
        })
      },
      handleClose() {
        this.$router.go(-1);
      },
      handleStartAllocate() {
        // TODO: 接入“开始分配”接口/逻辑
        if (!Array.isArray(this.availableList) || this.availableList.length <= 0) {
          this.$message.warning('没有可领用的白条')
          return
        }
        // 记录分配前快照：取消分配时恢复
        this.allocationAvailableSnapshot = this.cloneList(this.availableList)
        this.allocationResultSnapshot = this.cloneList(this.resultList)

        // 开始分配时，领料结果表用于操作：默认以当前状态为准（不强制清空）
        this.allocationQueryDisabled = true
        this.allocationStartDisabled = true
        this.allocationCancelDisabled = false
        this.allocationCompleteDisabled = false
      },
      handleCompleteAllocate() {
        if(!this.selectedPlanKey){
          this.$message.warning('请先选择生产计划单')
          return
        }
        if(this.resultList.length <= 0){
          this.$message.warning('没有可领用的白条')
          return
        }
        let params = {
          productionPlanNum: this.selectedPlanKey,
          goods: this.resultList
        }
        addSegmentationWhite(params).then(res => {
          this.$message.success('完成分配成功')
           // TODO: 接入“完成分配”接口/逻辑
          this.allocationQueryDisabled = false
          this.allocationStartDisabled = false
          this.allocationCancelDisabled = true
          this.allocationCompleteDisabled = true
          
          // 完成后快照可清理
          this.availableList = []
          this.resultList = []
          this.handleQuery()
          this.allocationAvailableSnapshot = null
          this.allocationResultSnapshot = null
        })
       
      },
      /**
       * 取消分配：切换按钮状态回到初始
       * TODO：若后端需要回滚分配结果，可在此处接入取消接口。
       */
      handleCancelAllocate() {
        // TODO: 接入“取消分配”接口/逻辑
        this.allocationQueryDisabled = false
        this.allocationStartDisabled = false
        this.allocationCancelDisabled = true
        this.allocationCompleteDisabled = true
        // 恢复左右两表原样
        this.availableList = this.cloneList(this.allocationAvailableSnapshot || [])
        this.resultList = this.cloneList(this.allocationResultSnapshot || [])
        this.allocationAvailableSnapshot = null
        this.allocationResultSnapshot = null
        this.$message.warning('已取消分配')
      },
      /**
       * 深拷贝列表（用于取消分配恢复）
       * @param {any[]} list
       * @returns {any[]}
       */
      cloneList(list) {
        return JSON.parse(JSON.stringify(list || []))
      },
      /**
       * 获取白条唯一标识（兼容 availableTable: whiteStripNumber / resultTable: whiteNo）
       * @param {Object} row
       * @returns {string|number|null}
       */
      getWhiteKey(row) {
        if (!row || typeof row !== 'object') return null
        return row.whiteNo ?? row.whiteStripNumber ?? row.id ?? null
      },
      /**
       * 左右两表互转：从 fromArr 移到 toArr（通过白条 key 去重）
       * @param {Object[]} fromArr
       * @param {Object[]} toArr
       * @param {Object} row 被点击的行
       */
      moveWhiteBetweenTables(fromArr, toArr, row) {
        if (this.allocationCancelDisabled) return
        const fromList = Array.isArray(fromArr) ? fromArr : []
        const toList = Array.isArray(toArr) ? toArr : []
        const key = this.getWhiteKey(row)
        if (key == null) return

        const fromIdx = fromList.findIndex((x) => {
          const k = this.getWhiteKey(x)
          return k != null && String(k) === String(key)
        })
        if (fromIdx < 0) return

        const [item] = fromList.splice(fromIdx, 1)

        // 去掉 toArr 中可能存在的同 key
        const existedIdx = toList.findIndex((x) => {
          const k = this.getWhiteKey(x)
          return k != null && String(k) === String(key)
        })
        if (existedIdx >= 0) toList.splice(existedIdx, 1)

        toList.push(item)
      },
      /** 点击可领用白条：移到领料结果 */
      handleAvailableRowClick(row) {
        this.moveWhiteBetweenTables(this.availableList, this.resultList, row)
      },
      /** 点击领料结果：移回可领用白条 */
      handleResultRowClick(row) {
        this.moveWhiteBetweenTables(this.resultList, this.availableList, row)
      },
      resetQuery() {
        const tomorrow = this.getTomorrowDateString()
        this.queryForm = {
          startDate: tomorrow,
          endDate: tomorrow,
          whiteStripDate: null,
          productionType: null,
          variety: null,
          animalIdentification: null,
          startGrade: null,
          endGrade: null,
          inspectResult: null,
          startWhiteStripNum: null,
          endWhiteStripNum: null,
          qualityInspectionResult: null,
          processingType: '4'
        };
      }
    },
    mounted() {}
  }
</script>

<style scoped lang="scss">
  .page-header {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 20px;
    text-align: center;
  }
  .query-form {
    margin-bottom: 20px;
  }
  .query-form .el-form-item {
    margin-bottom: 18px;
  }
  .range-to {
    margin: 0 8px;
    color: #606266;
  }
  .query-buttons {
    text-align: right;
    padding-right: 20px;
  }
  .table-section {
    margin-bottom: 24px;
  }
  .table-title {
    margin-bottom: 10px;
    font-size: 14px;
  }
  .table-label {
    margin-right: 16px;
    color: #606266;
  }
  .table-label-main {
    font-weight: 500;
  }
  .bottom-actions {
    margin-top: 20px;
    padding-top: 16px;
    border-top: 1px solid #ebeef5;
    text-align: right;
  }
  .box_item {
    width: 100%;
    height: 428px;
    border: 1px solid #ddd;
  }
  .plan-list {
    overflow-y: auto;
  }
  .plan-item {
    padding: 10px 12px;
    cursor: pointer;
    border-bottom: 1px solid #ebeef5;
    font-size: 13px;
  }
  .plan-item.is-active {
    background-color: #d9ecff;
    color: #303133;
    font-weight: 600;
  }
</style>
