<template>
  <div class="app-container production-shipment-page">
    <el-row :gutter="12" class="main-row">
      <el-col :span="6" class="main-col">
        <el-card class="section-card left-card" shadow="never">
          <div slot="header" class="card-header">
            <span>查询条件</span>
          </div>
          <div class="left-wrap">
            <!-- 上：查询 -->
            <el-card class="inner-card left-top" shadow="never">
              <el-form :model="queryParams" size="small" label-width="68px">
                <el-form-item label="发货日期" prop="shipDate">
                  <el-date-picker
                    v-model="queryParams.shipDate"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="请选择发货日期"
                    clearable
                    style="width: 100%"
                  />
                </el-form-item>
                <el-form-item label="产品类型" prop="productTypes">
                  <el-checkbox-group
                    v-model="queryParams.productTypes"
                    @change="onProductTypesChange"
                  >
                    <el-checkbox
                      v-for="opt in productTypeOptions"
                      :key="opt.typeNum"
                      :label="opt.typeNum"
                      >{{ opt.typeName }}</el-checkbox
                    >
                  </el-checkbox-group>
                </el-form-item>
                <el-form-item label-width="0">
                  <div class="query-actions">
                    <el-button size="mini" @click="handleProductTypeAll"
                      >全选</el-button
                    >
                    <el-button size="mini" @click="handleProductTypeClear"
                      >全清</el-button
                    >
                    <el-button
                      type="primary"
                      icon="el-icon-search"
                      size="mini"
                      @click="handleQuery"
                      >查询</el-button
                    >
                  </div>
                </el-form-item>
              </el-form>
            </el-card>
            <!-- 中 -->
            <el-card class="inner-card left-middle" shadow="never">
              <div class="placeholder">
                <el-tree
                  ref="shipmentOrderTree"
                  style="
                    margin-top: 8px;
                    height: calc(100% - 32px);
                    overflow: auto;
                  "
                  :data="shipmentOrderTreeData"
                  :props="shipmentTreeProps"
                  node-key="num"
                  highlight-current
                  default-expand-all
                  :expand-on-click-node="false"
                  @node-click="handleShipmentTreeNodeClick"
                />
              </div>
            </el-card>
            <!-- 下：按钮组 -->
            <el-card class="inner-card left-bottom" shadow="never">
              <div class="btn-group-row">
                <el-button
                  size="mini"
                  type="danger"
                  plain
                  @click="handleBatchDelete"
                  >批量删除</el-button
                >
                <el-button
                  size="mini"
                  type="primary"
                  plain
                  icon="el-icon-download"
                  @click="handleExportShipData"
                  >导出发货数据</el-button
                >
              </div>
            </el-card>
          </div>
        </el-card>
      </el-col>
      <el-col :span="18" class="main-col">
        <el-card class="section-card right-card" shadow="never">
          <div slot="header" class="card-header">
            <span>出货明细</span>
          </div>
          <div class="right-wrap">
            <!-- 上：表格 -->
            <div class="right-top table-panel">
              <div class="table-panel-body">
                <el-table
                  ref="shipTable"
                  border
                  stripe
                  height="100%"
                  :data="shipDetailList"
                  @selection-change="handleShipDetailSelectionChange"
                  style="width: 100%"
                >
                  <el-table-column
                    label="发货日期"
                    prop="deliveryDate"
                    min-width="110"
                  />
                  <el-table-column
                    label="客户名称"
                    prop="customer"
                    min-width="120"
                  />
                  <el-table-column
                    label="物料名称"
                    prop="materialName"
                    min-width="120"
                  />
                  <el-table-column
                    label="白条编号"
                    prop="whiteStripNumber"
                    min-width="130"
                  />
                  <el-table-column label="数量" prop="baseNum" min-width="90" />
                  <el-table-column label="单位" prop="unit" min-width="70" />
                  <el-table-column
                    label="辅助数量"
                    prop="assNum"
                    min-width="95"
                  />
                  <el-table-column
                    label="辅助单位"
                    prop="auxiliaryUnit"
                    min-width="90"
                  />
                  <el-table-column label="单价" prop="unitPrice" min-width="90" />
                  <el-table-column label="金额" prop="amount" min-width="100" />
                  <el-table-column
                    label="转销售出库单"
                    prop="transferToSalesDeliveryNote"
                    min-width="130"
                  >
                    <template slot-scope="{ row }">
                      <span>{{ row.transferToSalesDeliveryNote ? 'Y' : 'N'}}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="应收客户名称"
                    prop="receivableCustomer"
                    min-width="130"
                  />
                  <el-table-column
                    label="扣分合计"
                    prop="deductionTotal"
                    min-width="95"
                  />
                  <el-table-column
                    label="客户渠道"
                    prop="customerChannel"
                    min-width="100"
                  />
                  <el-table-column
                    label="仓库"
                    prop="warehouse"
                    min-width="90"
                  />
                  <el-table-column
                    label="客户编号"
                    prop="customerNumber"
                    min-width="100"
                  />
                  <el-table-column
                    label="应收客户"
                    prop="receivableCustomerName"
                    min-width="110"
                  />
                  <el-table-column
                    label="销售重量"
                    prop="salesWeight"
                    min-width="95"
                  />
                  <el-table-column
                    label="销售水分%"
                    prop="saleMoisture"
                    min-width="110"
                  />
                </el-table>
                <div class="pagination-container">
                  <pagination
                    v-show="total > 0"
                    :total="total"
                    :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize"
                    @pagination="getList"
                  />
                </div>
              </div>
            </div>
            <!-- 下：按钮组 -->
            <div class="right-bottom btn-group-wrap">
              <el-button size="mini" type="danger" plain @click="handleDelete"
                >删除</el-button
              >
              <el-button
                size="mini"
                type="primary"
                plain
                @click="handleToSaleOut"
                >转销售出库单</el-button
              >
              <el-button size="mini" plain @click="handlePreview"
                >预览</el-button
              >
              <el-button
                size="mini"
                plain
                icon="el-icon-printer"
                @click="handlePrint"
                >打印</el-button
              >
              <el-button size="mini" plain @click="handleCustomerWhiteSummary"
                >客户白条汇总单</el-button
              >
              <el-button size="mini" plain @click="handleWholesaleSummary"
                >批发客户汇总单</el-button
              >
              <el-button size="mini" plain @click="handleCertPrint"
                >合格证打印</el-button
              >
              <el-button size="mini" plain @click="handleWhiteMoveMeat"
                >白条搬肉单</el-button
              >
              <el-button size="mini" plain @click="handleByProductMoveMeat"
                >副产品搬肉单</el-button
              >
              <el-button size="mini" plain @click="handleCertSetting"
                >合格证设置</el-button
              >
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { formatDateYMS } from "@/utils";
import { getProduceTypeList } from "@/api/baseInfo/produceType";
import {
  getShipmentOrderTree,
  getShipmentPage,
} from "@/api/production/shipment";

export default {
  name: "ProductionShipment",
  data() {
    return {
      queryParams: {
        shipDate: null,
        productTypes: [],
        customerNums: null,
        pageNum: 1,
        pageSize: 20,
      },
      productTypeOptions: [],
      /** 记录上一次产品类型勾选值，用于判断本次是“新增勾选”了哪个类型 */
      lastProductTypes: [],
      shipDetailList: [],
      total: 0,
      shipDetailSelection: [],
      shipmentOrderTreeData: [],
      shipmentTreeProps: {
        children: "children",
        label: "name",
      },
    };
  },
  /** 初始化默认发货日期并拉取产品类型 */
  created() {
    const tomorrow = formatDateYMS(new Date().getTime() + 24 * 60 * 60 * 1000);
    this.queryParams.shipDate = tomorrow;
    this.getProductType();
  },
  methods: {
    /**
     * 拉取产品类型列表，剔除 typeNum 为 001；默认勾选其余类型
     *
     * 约定：typeNum = '002' 与其它类型互斥（只能单独勾选）
     */
    getProductType() {
      const excluded = new Set(["001"]);
      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 一致，默认全选（排除互斥项 002） */
        const defaultTypes = filtered
          .map((x) => x.typeNum)
          .filter((t) => String(t) !== "002");
        this.queryParams.productTypes = defaultTypes;
        this.lastProductTypes = [...defaultTypes];
      });
    },
    /**
     * 计算产品类型互斥结果：typeNum = '002' 与其它值互斥
     * - 若本次新增勾选了 '002'：只保留 '002'
     * - 若本次新增勾选了其它值且包含 '002'：移除 '002'
     * @param {Array} next 本次勾选结果（el-checkbox-group 返回）
     * @param {Array} prev 上一次勾选结果
     * @returns {Array} 处理后的勾选结果
     */
    calcMutexProductTypes(next, prev) {
      const nextArr = Array.isArray(next) ? next.map((x) => String(x)) : [];
      const prevArr = Array.isArray(prev) ? prev.map((x) => String(x)) : [];

      const nextSet = new Set(nextArr);
      const prevSet = new Set(prevArr);
      const added = nextArr.filter((x) => !prevSet.has(x));

      // 勾选了 002，则只保留 002（与任何其它值互斥）
      if (added.includes("002")) return ["002"];

      // 勾选了其它值，如果此时含 002，则移除 002
      if (added.length > 0 && nextSet.has("002")) {
        return nextArr.filter((x) => x !== "002");
      }

      return nextArr;
    },
    /**
     * 产品类型勾选变化：处理 typeNum='002' 与其它值互斥
     * @param {Array} val 当前勾选值
     */
    onProductTypesChange(val) {
      const normalized = this.calcMutexProductTypes(val, this.lastProductTypes);
      this.queryParams.productTypes = normalized;
      this.lastProductTypes = [...normalized];
    },
    /**
     * 产品类型全选，并取消白条勾选
     */
    handleProductTypeAll() {
      // 全选时排除互斥项 002，避免与其它类型同时勾选
      const all = this.productTypeOptions.map((o) => String(o.typeNum));
      const normalized = all.filter((t) => t !== "002");
      this.queryParams.productTypes = normalized;
      this.lastProductTypes = [...normalized];
    },
    /**
     * 产品类型全清
     */
    handleProductTypeClear() {
      this.queryParams.productTypes = [];
      this.lastProductTypes = [];
    },
    /**
     * 按查询条件拉树/出货明细（预留：对接接口）
     */
    handleQuery() {
      let params = {
        deliveryDate: this.queryParams.shipDate,
        productTypes: this.queryParams.productTypes.join(","),
      };
      getShipmentOrderTree(params).then((res) => {
        this.shipmentOrderTreeData = res.data || [];
      });
    },
    /**
     * 左侧树节点点击（预留：按节点维度刷新出货明细）
     * @param {Object} data 树节点数据
     */
    handleShipmentTreeNodeClick(data) {
        if(data.nodeType !== 'CUSTOMER') return;
        this.queryParams.customerNums = data.allCustomerNums.join(",");
        this.getList();
    },
    getList(){
      let params = {
        deliveryDate: this.queryParams.shipDate,
        productionTypes: this.queryParams.productTypes.join(","),
        customerNums: this.queryParams.customerNums,
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
      };
      getShipmentPage(params).then((res) => {
        this.shipDetailList = res.data.records || [];
        this.total = res.data.total;
      });
    },
    /**
     * 批量删除选中出货明细（预留：对接接口）
     */
    handleBatchDelete() {
      console.log("批量删除");
    },
    /**
     * 导出发货数据（预留：对接导出接口）
     */
    handleExportShipData() {
      console.log("导出发货数据");
    },
    /**
     * 出货明细表格多选变化
     * @param {Array} rows 当前勾选的行
     */
    handleShipDetailSelectionChange(rows) {
      this.shipDetailSelection = rows || [];
    },
    /**
     * 删除当前表格勾选的出货明细（预留：对接接口）
     */
    handleDelete() {
      console.log("删除", this.shipDetailSelection);
    },
    /**
     * 转销售出库单（预留：对接接口）
     */
    handleToSaleOut() {
      console.log("转销售出库单");
    },
    /**
     * 预览（预留：对接预览逻辑）
     */
    handlePreview() {
      console.log("预览");
    },
    /**
     * 打印（预留：对接打印）
     */
    handlePrint() {
      console.log("打印");
    },
    /**
     * 客户白条汇总单（预留：对接报表/打印）
     */
    handleCustomerWhiteSummary() {
      console.log("客户白条汇总单");
    },
    /**
     * 批发客户汇总单（预留：对接报表/打印）
     */
    handleWholesaleSummary() {
      console.log("批发客户汇总单");
    },
    /**
     * 合格证打印（预留：对接打印）
     */
    handleCertPrint() {
      console.log("合格证打印");
    },
    /**
     * 白条搬肉单（预留：对接单据）
     */
    handleWhiteMoveMeat() {
      console.log("白条搬肉单");
    },
    /**
     * 副产品搬肉单（预留：对接单据）
     */
    handleByProductMoveMeat() {
      console.log("副产品搬肉单");
    },
    /**
     * 合格证设置（预留：打开设置弹窗或跳转）
     */
    handleCertSetting() {
      console.log("合格证设置");
    },
  },
};
</script>

<style scoped>
.production-shipment-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-header {
  font-weight: 500;
  color: #303133;
}

.card-body {
  height: 100%;
}

.left-card ::v-deep .el-card__body {
  height: calc(100% - 57px);
  padding: 12px;
  display: flex;
  flex-direction: column;
}

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

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

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

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

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

.query-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.placeholder {
  width: 100%;
  height: 100%;
  /* display: flex; */
  /* align-items: center; */
  /* justify-content: center; */
  color: #909399;
  font-size: 12px;
}

/* 右侧：上表格 + 下按钮 */
.right-card ::v-deep .el-card__body {
  height: calc(100% - 57px);
  padding: 12px;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

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

.right-top {
  flex: 1 1 0;
  min-height: 0;
  display: flex;
  flex-direction: column;
}

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

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

.btn-group-wrap {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}
</style>
