<template>
  <div class="app-container production-divided-page">
    <el-row :gutter="12" class="main-row">
      <el-col :span="8" class="main-col">
        <div class="left-wrap">
          <el-card class="inner-card manual-card" shadow="never" header="手工分配">
            <el-form :model="manualQuery" size="small" label-width="90px">
              <el-row :gutter="12">
                <el-col :span="12">
                  <el-form-item label="生产日期" prop="productionDate">
                    <el-date-picker
                      v-model="manualQuery.productionDate"
                      type="date"
                      value-format="yyyy-MM-dd"
                      placeholder="请选择生产日期"
                      clearable
                      style="width: 100%;"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="发货日期" prop="shipDate">
                    <el-date-picker
                      v-model="manualQuery.shipDate"
                      type="date"
                      value-format="yyyy-MM-dd"
                      placeholder="请选择发货日期"
                      clearable
                      style="width: 100%;"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="12">
                <el-col :span="24">
                  <el-form-item label="产品类型" prop="productTypes">
                    <div class="product-type-row">
                      <el-checkbox-group v-model="manualQuery.productTypes">
                        <el-checkbox
                          v-for="opt in productTypeOptions"
                          :key="opt.typeNum"
                          :label="opt.typeNum"
                        >{{ opt.typeName }}</el-checkbox>
                      </el-checkbox-group>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="12">
                <el-col :span="12">
                  <div class="product-type-actions">
                    <el-button size="mini" @click="handleProductTypeAll">全选</el-button>
                    <el-button size="mini" @click="handleProductTypeClear">全清</el-button>
                  </div>
                </el-col>
                <el-col :span="12" style="text-align: right;">
                  <el-button type="primary" icon="el-icon-search" size="mini" @click="handleManualQuery">查询</el-button>
                </el-col>
              </el-row>
            </el-form>
          </el-card>

          <el-card class="inner-card bottom-card" shadow="never">
            <div class="card-body">
               <el-tree
                  ref="dividedOrderTree"
                  style="margin-top: 8px; height: calc(100% - 32px); overflow: auto;"
                  :data="dividedOrderTreeData"
                  :props="dividedTreeProps"
                  node-key="id"
                  highlight-current
                  default-expand-all
                  :expand-on-click-node="false"
                  @node-click="handleDividedTreeNodeClick"
                />
            </div>
          </el-card>
        </div>
      </el-col>
      <el-col :span="16" class="main-col">
        <el-card class="section-card" shadow="never">
          <div class="card-body right-wrap">
            <!-- 上：查询 + 按钮 -->
            <el-card class="inner-card right-top" shadow="never">
              <el-form ref="rightForm" :model="rightQuery" :rules="rightRules" size="small" label-width="100px">
                <el-row :gutter="12">
                  <el-col :span="8">
                    <el-form-item label="物料名称" prop="materialName">
                      <el-input v-model="rightQuery.materialName" placeholder="请输入物料名称" clearable>
                        <template slot="append">
                          <el-button type="primary" icon="el-icon-search" @click="openQueryMaterial" />
                        </template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="皮重" prop="tare">
                      <decimal-input v-model="rightQuery.tare" :precision="2" :min="0" placeholder="皮重" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="数量" prop="baseNum">
                      <decimal-input v-model="rightQuery.baseNum" :precision="2" :min="0" placeholder="数量" />
                    </el-form-item>
                  </el-col>
                  
                </el-row>

                <el-row :gutter="12">
                    <el-col :span="8">
                    <el-form-item label="辅助数量" prop="assNum">
                      <decimal-input v-model="rightQuery.assNum" :precision="2" :min="0" placeholder="辅助数量" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item prop="useScale">
                      <el-checkbox v-model="rightQuery.useScale">电子秤</el-checkbox>
                    </el-form-item>
                  </el-col>
                   <el-col :span="8">
                    <el-form-item label="电子秤数量kg" prop="scaleKg">
                      <decimal-input
                        v-model="rightQuery.scaleKg"
                        :precision="2"
                        :min="0"
                        placeholder="电子秤数量kg"
                        :disabled="!rightQuery.useScale"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="12">
                   
                  <el-col :span="4">
                    <el-form-item label-width="0" prop="shipByOrder">
                      <el-checkbox v-model="rightQuery.shipByOrder" @change="handleShipByOrderChange">按实际订单发货</el-checkbox>
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item label-width="0" prop="directPrint">
                      <el-checkbox v-model="rightQuery.directPrint">直接打印</el-checkbox>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8" style="text-align: right;">
                    <el-button type="primary" size="mini" @click="handleRightConfirm">确认</el-button>
                    <el-button type="success" plain size="mini" @click="handleRightFinishAlloc">完成分配</el-button>
                    <el-button type="info" plain size="mini" @click="handleRightPrint">打印</el-button>
                  </el-col>
                </el-row>
              </el-form>
            </el-card>
            <!-- 中：订单信息汇总（同 allocation） -->
            <el-card class="inner-card right-middle" shadow="never" header="订单信息汇总">
              <div class="table-panel">
                <div class="table-panel-body">
                  <el-table
                    ref="orderSummaryTable"
                    border
                    stripe
                    highlight-current-row
                    height="100%"
                    :data="orderSummaryList"
                    @row-click="handleOrderSummaryRowClick"
                    style="width: 100%;"
                  >
                    <el-table-column label="市场名称" min-width="120">
                       <template slot-scope="scope">
                              <span>{{ getBazaarLabel(scope.row.market_num) }}</span>
                            </template>
                    </el-table-column>
                    <el-table-column label="发货客户" prop="customer_name" min-width="140" />
                    <el-table-column label="物料名称" prop="goods_name" min-width="140" />
                    <el-table-column label="数量" prop="base_num" min-width="90" />
                    <el-table-column label="单位" prop="base_unit" min-width="90" />
                    <el-table-column label="辅助数量" prop="ass_num" min-width="110" />
                    <el-table-column label="辅助单位" prop="ass_unit" min-width="100" />
                    <el-table-column label="发货日期" prop="delivery_date" min-width="120" />
                    <el-table-column label="物料编码" prop="goods_num" min-width="120" />
                    <el-table-column label="备注" prop="remark" min-width="160" />
                  </el-table>
                </div>
              </div>
            </el-card>
            <!-- 下：分配结果（同 allocation） -->
            <el-card class="inner-card right-bottom" shadow="never" header="分配结果">
              <div class="table-panel">
                <div class="table-panel-body">
                  <el-table border stripe height="100%" :data="allocationResultList" style="width: 100%;">
                    <el-table-column label="销售订单号" prop="saleNum" min-width="160" />
                    <el-table-column label="物料编码" prop="materialCode" min-width="120" />
                    <el-table-column label="物料名称" min-width="160" >
                      <template slot-scope="scope">
                        <span>{{ getMaterialLabel(scope.row.materialCode, 'goodsName') }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="数量" prop="baseNum" min-width="90" />
                    <el-table-column label="单位" min-width="100">
                      <template slot-scope="scope">
                        <span>{{ getMaterialLabel(scope.row.materialCode, 'unit') }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="辅助数量" prop="assNum" min-width="110" />
                    <el-table-column label="辅助单位" min-width="100" >
                      <template slot-scope="scope">
                        <span>{{ getMaterialLabel(scope.row.materialCode, 'assUnit') }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="仓库" min-width="120" >
                      <template slot-scope="scope">
                        <span>{{ getMaterialLabel(scope.row.materialCode, 'warehouseNo') }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="完成分配" prop="completionStatus" min-width="120" >
                            <template slot-scope="scope">
                              <span>{{ scope.row.completionStatus === 1 ? 'Y' : 'N' }}</span>
                            </template>
                          </el-table-column>
                  </el-table>
                </div>
              </div>
            </el-card>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 物料速查弹窗（单选，确定回传） -->
    <query-material ref="queryMaterial" :isMultiple="false" @selectList="handleMaterialSelected" />
  </div>
</template>

<script>
import { formatDateYMS, getFindByKey } from "@/utils";
import { getProduceTypeList } from "@/api/baseInfo/produceType";
import { getSegmentedTree, getSegmentedDetail } from "@/api/sale/saleOrder";
import { getBazaarList } from "@/api/baseInfo/bazaar";
import { addAllocation, getAllocationList, editAllocationStatus } from '@/api/production/allocation'
import { getMaterialList } from '@/api/baseInfo/material'
import QueryMaterial from "@/views/components/queryMaterial.vue";
export default {
  name: "Divided",
  components: { QueryMaterial },
  data() {
    return {
      manualQuery: {
        productionDate: null,
        shipDate: null,
        productTypes: [],
      },
      productTypeOptions: [],
      rightQuery: {
        materialName: null,
        /** 选中物料的编码（queryMaterial 字段：goodsNum） */
        materialCode: null,
        tare: null,
        qty: null,
        auxQty: null,
        /** 来自订单汇总选中行 base_num */
        baseNum: null,
        /** 来自订单汇总选中行 ass_num */
        assNum: null,
        useScale: false,
        scaleKg: null,
        shipByOrder: false,
        directPrint: false,
        warehouseNo: null

      },
      /** 右侧录入表单校验规则 */
      rightRules: {
        materialName: [{ required: true, message: "请选择物料名称", trigger: "change" }],
        baseNum: [{ required: true, message: "请输入数量", trigger: "blur" }],
        assNum: [{ required: true, message: "请输入辅助数量", trigger: "blur" }],
      },
      orderSummaryList: [],
      /** 当前高亮的订单汇总行（与表格 current-row 同步；再点同一行可取消选中） */
      selectedOrderSummaryRow: null,
      /** 左侧分货树当前节点 */
      selectedDividedTreeNode: null,
      allocationResultList: [],
      dividedOrderTreeData: [],
      dividedTreeProps: {
        children: "children",
        label: "label",
      },
      bazaarList: [],
      /** 物料速查弹窗选择结果（单选取第 0 项） */
      selectedMaterial: null,
      materialList: [],
    };
  },
  created() {
    const tomorrow = formatDateYMS(new Date().getTime() + 24 * 60 * 60 * 1000);
    this.manualQuery.productionDate = tomorrow;
    this.manualQuery.shipDate = tomorrow;
    this.getProductType();
    this.getBazaar();
    this.getMaterial();
  },
  methods: {
    getMaterial() {
      getMaterialList({}).then((res) => {
        this.materialList = res.data || [];
      });
    },
    getMaterialLabel(val, key) {
      const item = getFindByKey(this.materialList, val, 'goodsNum')
      if(key === 'goodsName') {
        return item ? item.goodsName : (val ?? '-')
      } else if(key === 'unit') {
        return item ? item.unit : (val ?? '-')
      } else if(key === 'warehouseNo') {
        return item ? item.warehouseName : (val ?? '-')
      } else if(key === 'assUnit') {
        return item ? item.assistantUnit : (val ?? '-')
      } else {
        return val ?? '-'
      }
      
    },
    /**
     * 打开物料速查弹窗（单选）
     */
    openQueryMaterial() {
      if (this.$refs.queryMaterial && this.$refs.queryMaterial.open) {
        this.$refs.queryMaterial.open();
      }
    },
    /**
     * 物料速查：点击确定回传选中数据
     * @param {Array} list 选中的物料列表（单选时长度为 1）
     */
    handleMaterialSelected(list) {
      const row = Array.isArray(list) && list.length > 0 ? list[0] : null;
      this.selectedMaterial = row;
      this.rightQuery.materialName = row ? row.goodsName : null;
      this.rightQuery.materialCode = row ? row.goodsNum : null;
      this.rightQuery.warehouseNo = row ? row.warehouseNo : null;
    },
     getBazaar() {
      getBazaarList({}).then((res) => {
        this.bazaarList = res.data || [];
      });
    },
    getBazaarLabel(val) {
      const item = getFindByKey(this.bazaarList, val, 'marketNum')
      return item ? item.marketName : (val ?? '-')
    },
    /**
     * 拉取产品类型：剔除 typeNum 为 001、002 的项；其余默认全部勾选
     */
    getProductType() {
      const excluded = new Set(["001", "002"]);
      getProduceTypeList().then((res) => {
        const list = (res && res.data) || [];
        const filtered = list.filter(
          (x) =>
            x &&
            !excluded.has(String(x.typeNum != null ? x.typeNum : "").trim())
        );
        this.productTypeOptions = filtered;
        /** 与 el-checkbox-group 的 label 一致，默认全选过滤后的 typeNum */
        this.manualQuery.productTypes = filtered.map((x) => x.typeNum);
      });
    },
    /** 全选当前可选的产品类型（不含已剔除的 001/002） */
    handleProductTypeAll() {
      this.manualQuery.productTypes = this.productTypeOptions.map((x) => x.typeNum);
    },
    handleProductTypeClear() {
      this.manualQuery.productTypes = [];
    },
    handleManualQuery() {
      let params = {
        productionDate: this.manualQuery.productionDate,
        productTypes: this.manualQuery.productTypes.join(','),
      }
      getSegmentedTree(params).then((res) => {
        this.dividedOrderTreeData = res.data || [];
        this.$nextTick(() => {
          const first = this.findFirstTreeNodeWithId(this.dividedOrderTreeData);
          if (first && first.id != null && this.$refs.dividedOrderTree) {
            this.$refs.dividedOrderTree.setCurrentKey(first.id);
          }
          if (first) {
            this.handleDividedTreeNodeClick(first);
          }
        });
      });
    },
    findFirstTreeNodeWithId(nodes) {
      if (!nodes || !nodes.length) return null;
      for (let i = 0; i < nodes.length; i++) {
        const n = nodes[i];
        if (!n) continue;
        if (n.id != null) return n;
        if (n.children && n.children.length) {
          const hit = this.findFirstTreeNodeWithId(n.children);
          if (hit) return hit;
        }
      }
      return null;
    },
    getDividedTreeNodeLabel(node) {
      const label = node && node.label != null ? String(node.label) : "-";
      return label;
    },
    handleDividedTreeNodeClick(data) {
      if (!data) return;
      this.selectedDividedTreeNode = data;
      this.$nextTick(() => {
        if (this.$refs.dividedOrderTree && data.id != null) {
          this.$refs.dividedOrderTree.setCurrentKey(data.id);
        }
      });
      const params = {
        lineNum: data.type === 'line' ? data.lineNum : null,
        marketNum: data.type === 'market' ? data.marketNum : null,
        customerNum: data.type === 'customer' ? data.customerNum : null,
        productionDate: this.manualQuery.productionDate,
        deliveryDate: this.manualQuery.shipDate,
        productTypes: this.manualQuery.productTypes.join(','),
      };
      getSegmentedDetail(params).then((res) => {
        this.orderSummaryList = (res && res.data) || [];
        /** 默认高亮第一行；无数据时清空选中 */
        this.$nextTick(() => {
          const t = this.$refs.orderSummaryTable;
          if (!t) return;
          if (this.orderSummaryList.length > 0) {
            const first = this.orderSummaryList[0];
            this.selectedOrderSummaryRow = first;
            t.setCurrentRow(first);
            /** 默认选中第一行时同步数量到右侧录入区 */
            this.syncRightQueryFromOrderSummaryRow(first);
            /** 订单汇总默认选中时，联动刷新分配结果 */
            this.fetchAllocationResultAllList();
          } else {
            this.selectedOrderSummaryRow = null;
            t.setCurrentRow(null);
            this.syncRightQueryFromOrderSummaryRow(null);
            this.allocationResultList = [];
          }
        });
      });
    },
    /**
     * 订单汇总选中行 → 右侧表单：base_num / ass_num → rightQuery.baseNum / auxNum
     * @param {Object|null} row
     */
    syncRightQueryFromOrderSummaryRow(row) {
      if (!row) {
        this.rightQuery.baseNum = null;
        this.rightQuery.assNum = null;
        return;
      }
      const toNum = (v) => {
        if (v == null || v === "") return null;
        const n = Number(v);
        return Number.isNaN(n) ? v : n;
      };
      this.rightQuery.baseNum = toNum(row.base_num);
      this.rightQuery.assNum = toNum(row.ass_num);
    },
    /**
     * 按实际订单发货切换：
     * 勾选时，将当前选中的订单汇总数量同步到右侧录入区；
     * 取消时不清空，保留用户当前录入值。
     * @param {boolean} checked 是否勾选
     */
    handleShipByOrderChange(checked) {
      if (!checked) return;
      this.syncRightQueryFromOrderSummaryRow(this.selectedOrderSummaryRow);
    },
    /**
     * 订单汇总：单行高亮；再次点击同一行则取消选中（蓝色高亮消失）
     * @param {Object} row
     */
    handleOrderSummaryRowClick(row) {
      const t = this.$refs.orderSummaryTable;
      if (!t || !row) return;
      const cur = this.selectedOrderSummaryRow;
      const same =
        cur &&
        (cur === row ||
          (cur.id != null && row.id != null && String(cur.id) === String(row.id)));
      if (same) {
        this.selectedOrderSummaryRow = null;
        t.setCurrentRow(null);
        if (this.rightQuery.shipByOrder) {
          this.syncRightQueryFromOrderSummaryRow(null);
        }
        /** 取消选中时清空分配结果，避免展示上一单数据 */
        this.allocationResultList = [];
      } else {
        this.selectedOrderSummaryRow = row;
        t.setCurrentRow(row);
        if (this.rightQuery.shipByOrder) {
          this.syncRightQueryFromOrderSummaryRow(row);
        }
        /** 订单汇总选中时，联动刷新分配结果 */
        this.fetchAllocationResultAllList();
      }
    },
    handleRightConfirm() {
      if(!this.selectedOrderSummaryRow) {
        this.$message.waning('请先选中订单！')
      }
      let params = {
        saleId: this.selectedOrderSummaryRow.id,
        saleNum: this.selectedOrderSummaryRow.order_num,
        deliveryCustomer:  this.selectedOrderSummaryRow.customer_num,
        lockedLogisticsLine:  this.selectedOrderSummaryRow.line_num,
        market:  this.selectedOrderSummaryRow.market_num,
        customer:  this.selectedOrderSummaryRow.customer_num,
        productionDate: this.manualQuery.productionDate,
        deliveryDate: this.manualQuery.shipDate,
        materialCode: this.rightQuery.materialCode,
        baseNum: this.rightQuery.baseNum,
        assNum: this.rightQuery.assNum,
        peelWeight: this.rightQuery.tare,
        warehouseNo: this.rightQuery.warehouseNo
      }
      addAllocation(params).then(res => {
         if (res.code !== 200) {
            this.$message.error(res.msg || "分配失败");
            return Promise.reject(new Error("BIZ_FAIL"));
          }
          this.$message.success("分配成功");
          this.fetchAllocationResultAllList()
      })
    },
    handleRightFinishAlloc() {
       if (this.allocationResultList.length <= 0) {
        this.$message.warning("没有可分配的分割品副产品");
        return;
      }
      this.$modal.confirm("确定要完成分配吗？").then(() => {
        const params = {
          ids: this.allocationResultList
            .map((r) => r.id ?? r.allocationId)
            .filter((v) => v != null && v !== "")
            .join(","),
        };
        editAllocationStatus(params)
          .then((res) => {
            this.$message.success("完成分配成功");
            this.fetchAllocationResultAllList();
          })
          .catch((err) => {});
      });
    },
    handleRightPrint() {
      console.log("print");
    },
     /**
     * 查询分配结果（全量）：getAllocationList → allocationResultAllList → syncAllocationResultList → allocationResultList
     * @param {Object} [params] 查询参数；不传则 {@link buildAllocationListQueryParams}
     * @returns {Promise<void>}
     */
    fetchAllocationResultAllList() {
      let row = this.selectedOrderSummaryRow
      if(!row) return;
      let p = {
        saleId: row.id,
      }
      return getAllocationList(p).then((res) => {
        this.allocationResultList = res.data || []
      });
    },
  },
};
</script>

<style scoped>
.production-divided-page {
  height: calc(100vh - 90px);
  overflow: hidden;
}

.main-row {
  height: 100%;
  margin-left: 0 !important;
  margin-right: 0 !important;
}

.main-col {
  height: 100%;
}

.section-card {
  height: 100%;
}

.card-body {
  height: 100%;
}

/* 让 el-card 的 body 真正撑满高度，否则中/下拿不到剩余高度 */
::v-deep .section-card > .el-card__body {
  height: 100%;
  min-height: 0;
  display: flex;
  flex-direction: column;
}

.left-wrap {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.inner-card {
  flex: 1 1 0;
  min-height: 0;
}

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

.bottom-card {
  flex: 1 1 0;
  min-height: 0;
}

.product-type-row {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.product-type-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-start;
}

.right-wrap {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 12px;
  min-height: 0;
}

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

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

.right-bottom {
  flex: 1 1 0;
  min-height: 0;
}

::v-deep .right-middle > .el-card__body,
::v-deep .right-bottom > .el-card__body {
  height: 100%;
  display: flex;
  flex-direction: column;
}

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

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

/* 订单汇总：当前行蓝色高亮（与 highlight-current-row 配合） */
::v-deep .right-middle .el-table__body tr.current-row > td {
  background-color: #ecf5ff !important;
}
</style>
