<template>
  <div class="app-container sale-rebate-page">
    <!-- 查询 -->
    <el-card shadow="never" class="top-card">
      <el-form ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="88px">
        <el-form-item label="日期" prop="dateRange">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 260px"
            clearable
          />
        </el-form-item>
        <el-form-item label="客户" prop="customerNum">
          <el-select v-model="queryParams.customerNum" placeholder="请选择客户" filterable clearable style="width: 200px">
            <el-option v-for="item in customerOptions" :key="item.customerNum" :value="item.customerNum" :label="item.customerName" />
          </el-select>
        </el-form-item>
        <el-form-item label="业务员" prop="employeeNum">
          <el-select v-model="queryParams.employeeNum" placeholder="请选择业务员" filterable clearable style="width: 200px">
            <el-option v-for="item in salespersonOptions" :key="item.employeeNum" :value="item.employeeNum" :label="item.employeeName" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDeleteAll">批量删除</el-button>
        </el-col>
      </el-row>
    </el-card>

    <br />

    <el-card shadow="never" class="bottom-card">
      <el-table border stripe v-loading="loading" ref="multipleTable" :data="list" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="折让日期" align="center" prop="allowanceDate" min-width="110" />
        <el-table-column label="折让编号" align="center" prop="allowanceNum" min-width="140" />
        <el-table-column label="客户名称" align="center" prop="customerName" min-width="140" />
        <el-table-column label="业务员" align="center" prop="employeeName" min-width="120" />
        <el-table-column label="部门" align="center" prop="departmentName" min-width="120" />
        <el-table-column label="备注" align="center" prop="remark" min-width="160" show-overflow-tooltip />
        <el-table-column label="总计金额" align="center" prop="totalAmount" min-width="110" />
        <el-table-column label="操作" align="center" fixed="right" width="200">
          <template slot-scope="scope">
            <el-button type="text" size="mini" icon="el-icon-document" @click="handleDetail(scope.row)">查看详情</el-button>
            <el-button type="text" size="mini" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" size="mini" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 新增 / 编辑 / 查看 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogOpen" fullscreen append-to-body class="sale-rebate-dialog">
      <!-- 查看 -->
      <div v-if="dialogMode === 'view'" class="dialog-detail-body">
        <el-card shadow="never" class="dialog-detail-card">
          <el-descriptions :column="3" border size="small" class="detail-desc">
            <el-descriptions-item label="折让日期">{{ emptyDisplay(form.allowanceDate) }}</el-descriptions-item>
            <el-descriptions-item label="折让编号">{{ emptyDisplay(form.allowanceNum) }}</el-descriptions-item>
            <el-descriptions-item label="客户编号">{{ emptyDisplay(form.customerNum) }}</el-descriptions-item>
            <el-descriptions-item label="客户名称">{{ emptyDisplay(form.customerName) }}</el-descriptions-item>
            <el-descriptions-item label="业务员">{{ emptyDisplay(form.employeeName || form.employeeNum) }}</el-descriptions-item>
            <el-descriptions-item label="部门">{{ emptyDisplay(form.departmentName || form.departmentNum) }}</el-descriptions-item>
            <el-descriptions-item label="备注" :span="3">{{ emptyDisplay(form.remark) }}</el-descriptions-item>
          </el-descriptions>

          <div class="dialog-table-card dialog-table-card--detail">
            <el-table :data="form.items" border stripe height="100%" class="dialog-table" size="small">
              <el-table-column label="销售单号" align="center" min-width="130" show-overflow-tooltip>
                <template slot-scope="{ row }">
                  {{ emptyDisplay(row.deliveryNum) }}
                </template>
              </el-table-column>
              <el-table-column label="销售日期" align="center" prop="salesDate" min-width="110" />
              <el-table-column label="批次" align="center" prop="batchNum" min-width="100" show-overflow-tooltip />
              <el-table-column label="品名" align="center" prop="goodsName" min-width="140" show-overflow-tooltip />
              <el-table-column label="数量" align="center" prop="quantity" min-width="100" />
              <el-table-column label="单位" align="center" prop="unit" min-width="80" />
              <el-table-column label="单价" align="center" prop="unitPrice" min-width="100" />
              <el-table-column label="金额" align="center" prop="amount" min-width="100" /> 
              <el-table-column label="备注" align="center" min-width="120" show-overflow-tooltip>
                <template slot-scope="{ row }">
                  {{ emptyDisplay(row.goodsRemark != null ? row.goodsRemark : row.lineRemark != null ? row.lineRemark : row.remark) }}
                </template>
              </el-table-column>
            </el-table>
          </div>

          <el-descriptions :column="3" border size="small" class="detail-desc detail-desc--foot">
            <el-descriptions-item label="总计金额">{{ emptyDisplay(form.totalAmount) }}</el-descriptions-item>
          </el-descriptions>
        </el-card>
      </div>

      <!-- 新增 / 编辑 -->
      <div v-else class="dialog-body">
        <el-form ref="dialogForm" :model="form" :rules="dialogFormRules" label-width="100px" size="small" class="dialog-main-form">
          <el-card shadow="never" class="dialog-head-card">
            <el-row :gutter="12">
              <el-col :span="6">
                <el-form-item label="折让日期" prop="allowanceDate">
                  <el-date-picker
                    v-model="form.allowanceDate"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="折让日期"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="折让编号" prop="allowanceNum">
                  <el-input v-model="form.allowanceNum" placeholder="折让编号" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="客户编号" prop="customerNum">
                  <el-select
                    v-model="form.customerNum"
                    placeholder="请选择客户"
                    filterable
                    clearable
                    style="width: 100%"
                    @change="onCustomerChange"
                  >
                    <el-option
                      v-for="item in customerOptions"
                      :key="item.customerNum"
                      :value="item.customerNum"
                      :label="`${item.customerName || ''} (${item.customerNum || ''})`"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="客户名称" prop="customerName">
                  <el-input v-model="form.customerName" placeholder="随客户编号带出" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="业务员" prop="employeeNum">
                  <el-select
                    v-model="form.employeeNum"
                    placeholder="与部门二选一"
                    filterable
                    clearable
                    style="width: 100%"
                    @change="onEmployeeNumChange"
                  >
                    <el-option v-for="item in salespersonOptions" :key="item.employeeNum" :value="item.employeeNum" :label="item.employeeName" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="部门" prop="departmentNum">
                  <el-select
                    v-model="form.departmentNum"
                    placeholder="与业务员二选一"
                    filterable
                    clearable
                    style="width: 100%"
                    @change="onDepartmentNumChange"
                  >
                    <el-option
                      v-for="item in departmentOptions"
                      :key="item.departmentNum"
                      :value="item.departmentNum"
                      :label="item.departmentName"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="备注" clearable />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <div class="dialog-detail-toolbar">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddGoodsRow">添加明细</el-button>
          </div>

          <el-card shadow="never" class="dialog-table-card">
            <el-table :data="form.items" border stripe height="100%" class="dialog-table dialog-table--with-form" size="small">
              <el-table-column label="销售单号" align="center" min-width="168">
                <template slot-scope="{ row, $index }">
                  <el-form-item :prop="'items.' + $index + '.deliveryNum'" label-width="0" :rules="detailGoodsFieldRules.deliveryNum" class="dialog-goods-form-item">
                    <el-input v-model="row.deliveryNum" size="mini" placeholder="销售单号" clearable>
                      <template slot="append">
                        <el-tooltip content="查询销售出库单" placement="top">
                          <span class="dialog-sale-out-append">
                            <el-button type="primary" icon="el-icon-search" circle size="mini" @click="openSaleOutPickDialog($index)" />
                          </span>
                        </el-tooltip>
                      </template>
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="销售日期" align="center" min-width="130">
                <template slot-scope="{ row }">
                  <el-date-picker
                    v-model="row.salesDate"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="日期"
                    size="mini"
                    style="width: 100%"
                  />
                </template>
              </el-table-column>
              <el-table-column label="批次" align="center" min-width="100">
                <template slot-scope="{ row }">
                  <el-input v-model="row.batchNum" size="mini" placeholder="批次" clearable />
                </template>
              </el-table-column>
              <el-table-column label="品名" align="center" min-width="140">
                <template slot-scope="{ row }">
                  <el-input v-model="row.goodsName" size="mini" placeholder="品名" clearable />
                </template>
              </el-table-column>
              <el-table-column label="数量" align="center" min-width="110">
                <template slot-scope="{ row, $index }">
                  <decimal-input v-model="row.quantity" size="mini" :precision="2" :min="0" placeholder="数量" @change="() => recalcLineAmount($index)" />
                </template>
              </el-table-column>
              <el-table-column label="单位" align="center" min-width="90">
                <template slot-scope="{ row }">
                  <el-input v-model="row.unit" size="mini" placeholder="单位" clearable />
                </template>
              </el-table-column>
              <el-table-column label="单价" align="center" min-width="110">
                <template slot-scope="{ row, $index }">
                  <decimal-input v-model="row.unitPrice" size="mini" :precision="2" :min="0" placeholder="单价" @change="() => recalcLineAmount($index)" />
                </template>
              </el-table-column>
              <el-table-column label="金额" align="center" min-width="100">
                <template slot-scope="{ row }">
                  <el-input :value="row.amount != null && row.amount !== '' ? row.amount : ''" size="mini" readonly placeholder="自动计算" />
                </template>
              </el-table-column>
              <el-table-column label="备注" align="center" min-width="120">
                <template slot-scope="{ row }">
                  <el-input v-model="row.goodsRemark" size="mini" placeholder="备注" clearable />
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="70" fixed="right">
                <template slot-scope="{ $index }">
                  <el-button
                    type="text"
                    icon="el-icon-delete"
                    :disabled="!form.items || form.items.length <= 1"
                    @click="handleRemoveGoodsRow($index)"
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-card>

          <el-card shadow="never" class="dialog-foot-card">
            <el-row :gutter="12">
              <el-col :span="8">
                <el-form-item label="总计金额" prop="totalAmount">
                  <decimal-input v-model="form.totalAmount" size="mini" :precision="2" :min="0" placeholder="总计金额" disabled />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <template v-if="dialogMode === 'view'">
          <el-button type="primary" @click="dialogOpen = false">关 闭</el-button>
        </template>
        <template v-else>
          <el-button @click="dialogOpen = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </template>
      </div>
    </el-dialog>

    <!-- 销售出库单查询：单选后回填当前明细行（销售单号等） -->
    <el-dialog
      title="销售出库单查询"
      :visible.sync="saleOutPickDialogOpen"
      width="1200px"
      append-to-body
      class="sale-out-pick-dialog"
      @close="onSaleOutPickDialogClose"
    >
      <el-form :model="saleOutPickQueryParams" size="small" :inline="true" label-width="80px" class="sale-out-pick-query-form">
        <el-form-item label="单据编号" prop="deliveryNum">
          <el-input v-model="saleOutPickQueryParams.deliveryNum" placeholder="出库单号" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="日期" prop="dateRange">
          <el-date-picker
            v-model="saleOutPickQueryParams.dateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 260px"
            clearable
          />
        </el-form-item>
        <el-form-item label="客户" prop="customerNum">
          <el-select v-model="saleOutPickQueryParams.customerNum" placeholder="客户" filterable clearable style="width: 200px">
            <el-option v-for="item in customerOptions" :key="item.customerNum" :value="item.customerNum" :label="item.customerName" />
          </el-select>
        </el-form-item>
        <el-form-item label="业务员" prop="employeeNum">
          <el-select v-model="saleOutPickQueryParams.employeeNum" placeholder="业务员" filterable clearable style="width: 200px">
            <el-option v-for="item in salespersonOptions" :key="item.employeeNum" :value="item.employeeNum" :label="item.employeeName" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleSaleOutPickQuery">查询</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetSaleOutPickQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        ref="saleOutPickTable"
        v-loading="saleOutPickLoading"
        :data="saleOutPickList"
        border
        stripe
        highlight-current-row
        height="420"
        class="sale-out-pick-table"
        @row-click="handleSaleOutPickRowClick"
      >
        <el-table-column label="单据日期" align="center" prop="documentDate" min-width="110" />
        <el-table-column label="单据编号" align="center" prop="deliveryNum" min-width="150" />
        <el-table-column label="客户编号" align="center" prop="customerNum" min-width="120" />
        <el-table-column label="客户名称" align="center" prop="customerName" min-width="140" />
        <el-table-column label="业务员" align="center" prop="employeeName" min-width="120" />
        <el-table-column label="总计金额" align="center" prop="totalAmount" min-width="110" />
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmSaleOutPick">确 定</el-button>
        <el-button @click="saleOutPickDialogOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { formatDateYMS } from "@/utils";
import {
  getSaleRebatePage,
  addSaleRebate,
  editSaleRebate,
  delSaleRebate,
  getSaleRebateById,
  getLatestSaleRebateNum,
} from "@/api/sale/saleRebate";
import { getSaleOutList, getSaleOutById } from "@/api/sale/saleOut";
import { getClienteleList } from "@/api/sale/clientele";
import { getStaffList } from "@/api/baseInfo/staff";
import { getDepartmentList } from "@/api/baseInfo/department";
import DecimalInput from "@/views/components/DecimalInput.vue";

export default {
  name: "SaleRebate",
  components: { DecimalInput },
  data() {
    return {
      loading: false,
      list: [],
      total: 0,
      ids: [],
      multiple: true,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dateRange: [],
        customerNum: null,
        employeeNum: null,
        allowanceDateStart: null,
        allowanceDateEnd: null,
      },
      customerOptions: [],
      salespersonOptions: [],
      departmentOptions: [],
      dialogOpen: false,
      dialogTitle: "新增",
      dialogMode: "add",
      /** 弹框主表 + 明细 items */
      form: {
        id: null,
        allowanceDate: null,
        allowanceNum: null,
        customerNum: null,
        customerName: null,
        employeeNum: null,
        employeeName: null,
        departmentNum: null,
        departmentName: null,
        remark: null,
        totalAmount: "0.00",
        items: [],
      },
      /** 销售出库单选择弹框 */
      saleOutPickDialogOpen: false,
      saleOutPickLoading: false,
      saleOutPickList: [],
      saleOutPickSelectedRow: null,
      /** 正在回填的明细行下标 */
      saleOutPickGoodsRowIndex: null,
      saleOutPickQueryParams: {
        deliveryNum: null,
        dateRange: [],
        documentDateStart: null,
        documentDateEnd: null,
        customerNum: null,
        employeeNum: null,
      },
    };
  },
  computed: {
    dialogFormRules() {
      return {
        allowanceDate: [{ required: true, message: "请选择折让日期", trigger: "change" }],
        allowanceNum: [{ required: true, message: "请输入折让编号", trigger: "blur" }],
        customerNum: [{ required: true, message: "请选择客户编号", trigger: "change" }],
        customerName: [{ required: true, message: "客户名称不能为空", trigger: "blur" }],
        employeeNum: [{ validator: this.validateEmployeeDeptRule, trigger: "change" }],
        departmentNum: [{ validator: this.validateEmployeeDeptRule, trigger: "change" }],
      };
    },
    /** 折让明细：销售单号必填（可手输或选销售出库单带入） */
    detailGoodsFieldRules() {
      return {
        deliveryNum: [{ required: true, message: "销售单号不能为空", trigger: "blur" }],
      };
    },
  },
  watch: {
    "queryParams.dateRange": {
      handler(newVal) {
        if (newVal && newVal.length === 2) {
          this.queryParams.allowanceDateStart = newVal[0];
          this.queryParams.allowanceDateEnd = newVal[1];
        }
      },
      deep: true,
      immediate: true,
    },
    "saleOutPickQueryParams.dateRange": {
      handler(newVal) {
        if (newVal && newVal.length === 2) {
          this.saleOutPickQueryParams.documentDateStart = newVal[0];
          this.saleOutPickQueryParams.documentDateEnd = newVal[1];
        } else {
          this.saleOutPickQueryParams.documentDateStart = null;
          this.saleOutPickQueryParams.documentDateEnd = null;
        }
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    const today = formatDateYMS(new Date().getTime());
    this.queryParams.dateRange = [today, today];
    this.queryParams.allowanceDateStart = today;
    this.queryParams.allowanceDateEnd = today;
    this.fetchCustomerOptions();
    this.fetchSalespersonOptions();
    this.fetchDepartmentOptions();
    this.getList();
  },
  methods: {
    /**
     * 空值展示
     * @param {*} val
     * @returns {string}
     */
    emptyDisplay(val) {
      if (val === null || val === undefined) return "—";
      const s = String(val).trim();
      return s === "" ? "—" : s;
    },
    /**
     * 业务员与部门二选一：不能同时有值（与 saleBack 互斥思路一致）
     */
    validateEmployeeDeptRule(rule, value, callback) {
      const hasEmp = this.form.employeeNum != null && String(this.form.employeeNum).trim() !== "";
      const hasDept = this.form.departmentNum != null && String(this.form.departmentNum).trim() !== "";
      if (hasEmp && hasDept) {
        callback(new Error("业务员与部门只能填写其中一项"));
        return;
      }
      callback();
    },
    /** 选客户：带出名称 */
    onCustomerChange(customerNum) {
      const hit = (this.customerOptions || []).find((x) => String(x.customerNum) === String(customerNum));
      this.form.customerName = hit ? hit.customerName : null;
      this.$nextTick(() => {
        if (this.$refs.dialogForm) {
          this.$refs.dialogForm.validateField("customerName");
          this.$refs.dialogForm.validateField("employeeNum");
          this.$refs.dialogForm.validateField("departmentNum");
        }
      });
    },
    /** 选业务员：清空部门 */
    onEmployeeNumChange(val) {
      if (val != null && String(val).trim() !== "") {
        this.form.departmentNum = null;
        this.form.departmentName = null;
        const hit = (this.salespersonOptions || []).find((x) => String(x.employeeNum) === String(val));
        this.form.employeeName = hit ? hit.employeeName : null;
      } else {
        this.form.employeeName = null;
      }
      this.$nextTick(() => {
        if (this.$refs.dialogForm) {
          this.$refs.dialogForm.validateField("departmentNum");
          this.$refs.dialogForm.validateField("employeeNum");
        }
      });
    },
    /** 选部门：清空业务员 */
    onDepartmentNumChange(val) {
      if (val != null && String(val).trim() !== "") {
        this.form.employeeNum = null;
        this.form.employeeName = null;
        const hit = (this.departmentOptions || []).find((x) => String(x.departmentNum) === String(val));
        this.form.departmentName = hit ? hit.departmentName : null;
      } else {
        this.form.departmentName = null;
      }
      this.$nextTick(() => {
        if (this.$refs.dialogForm) {
          this.$refs.dialogForm.validateField("employeeNum");
          this.$refs.dialogForm.validateField("departmentNum");
        }
      });
    },
    createEmptyGoodsRow() {
      return {
        deliveryNum: null,
        salesDate: null,
        batchNum: null,
        goodsName: null,
        quantity: null,
        unit: null,
        unitPrice: null,
        amount: null,
        goodsRemark: null,
      };
    },
    /**
     * 从接口主表解析明细数组（优先 items，兼容旧字段 goods）
     * @param {Object} row 接口主表
     * @returns {Array<Object>}
     */
    resolveItemsFromRow(row) {
      const list = row && (Array.isArray(row.items) ? row.items : Array.isArray(row.goods) ? row.goods : null);
      if (Array.isArray(list) && list.length) {
        return list.map((x) => ({
          ...x,
          goodsRemark: x.goodsRemark != null ? x.goodsRemark : x.remark != null ? x.remark : null,
        }));
      }
      return [this.createEmptyGoodsRow()];
    },
    /**
     * 打开销售出库单查询：默认带主表客户、日期区间
     * @param {number} rowIndex 当前明细行下标
     */
    openSaleOutPickDialog(rowIndex) {
      this.saleOutPickGoodsRowIndex = rowIndex;
      const today = formatDateYMS(new Date().getTime());
      if (!this.saleOutPickQueryParams.dateRange || this.saleOutPickQueryParams.dateRange.length !== 2) {
        this.saleOutPickQueryParams.dateRange = [today, today];
        this.saleOutPickQueryParams.documentDateStart = today;
        this.saleOutPickQueryParams.documentDateEnd = today;
      }
      this.saleOutPickQueryParams.customerNum = this.form.customerNum != null ? this.form.customerNum : null;
      this.saleOutPickQueryParams.employeeNum = this.form.employeeNum != null ? this.form.employeeNum : null;
      this.saleOutPickQueryParams.deliveryNum = null;
      this.saleOutPickSelectedRow = null;
      this.saleOutPickDialogOpen = true;
      this.$nextTick(() => {
        if (this.$refs.saleOutPickTable) this.$refs.saleOutPickTable.setCurrentRow(null);
      });
      this.fetchSaleOutPickList();
    },
    /** 关闭出库单弹框时清理选中 */
    onSaleOutPickDialogClose() {
      this.saleOutPickSelectedRow = null;
      this.$nextTick(() => {
        if (this.$refs.saleOutPickTable) this.$refs.saleOutPickTable.setCurrentRow(null);
      });
    },
    /** POST getSaleOutList，兼容 data 为数组或分页 records */
    fetchSaleOutPickList() {
      this.saleOutPickLoading = true;
      const p = { ...this.saleOutPickQueryParams };
      delete p.dateRange;
      getSaleOutList(p)
        .then((res) => {
          const raw = res && res.data !== undefined ? res.data : res;
          let list = [];
          if (Array.isArray(raw)) list = raw;
          else if (raw && Array.isArray(raw.records)) list = raw.records;
          else if (raw && Array.isArray(raw.list)) list = raw.list;
          this.saleOutPickList = list;
        })
        .catch(() => {
          this.saleOutPickList = [];
        })
        .finally(() => {
          this.saleOutPickLoading = false;
          this.saleOutPickSelectedRow = null;
          this.$nextTick(() => {
            if (this.$refs.saleOutPickTable) this.$refs.saleOutPickTable.setCurrentRow(null);
          });
        });
    },
    handleSaleOutPickQuery() {
      this.fetchSaleOutPickList();
    },
    resetSaleOutPickQuery() {
      const today = formatDateYMS(new Date().getTime());
      this.saleOutPickQueryParams = {
        deliveryNum: null,
        dateRange: [today, today],
        documentDateStart: today,
        documentDateEnd: today,
        customerNum: this.form.customerNum != null ? this.form.customerNum : null,
        employeeNum: this.form.employeeNum != null ? this.form.employeeNum : null,
      };
      this.fetchSaleOutPickList();
    },
    /** 单选高亮 */
    handleSaleOutPickRowClick(row) {
      if (!row) return;
      this.saleOutPickSelectedRow = row;
      this.$nextTick(() => {
        if (this.$refs.saleOutPickTable) this.$refs.saleOutPickTable.setCurrentRow(row);
      });
    },
    /**
     * 确定：按 id 拉出库单详情，将首行货品与表头写入当前折让明细行
     */
    confirmSaleOutPick() {
      const pick = this.saleOutPickSelectedRow;
      if (!pick) {
        this.$message.warning("请先选择一条销售出库单");
        return;
      }
      const idx = this.saleOutPickGoodsRowIndex;
      if (idx == null || !(this.form.items || [])[idx]) {
        this.saleOutPickDialogOpen = false;
        return;
      }
      const applyHeaderAndFirstGoods = (detail) => {
        const row = this.form.items[idx];
        const header = detail && typeof detail === "object" ? detail : pick;
        this.$set(row, "deliveryNum", header.deliveryNum != null ? header.deliveryNum : pick.deliveryNum);
        this.$set(row, "salesDate", header.documentDate != null ? header.documentDate : pick.documentDate);
        const goodsArr = header.goods;
        const g = Array.isArray(goodsArr) && goodsArr.length ? goodsArr[0] : {};
        this.$set(row, "batchNum", g.batchNum != null ? g.batchNum : null);
        this.$set(row, "goodsNum", g.goodsNum != null ? g.goodsNum : null);
        this.$set(row, "goodsName", g.goodsName != null ? g.goodsName : null);
        this.$set(
          row,
          "quantity",
          g.baseNum != null ? g.baseNum : g.quantity != null ? g.quantity : null
        );
        this.$set(row, "unit", g.baseUnit != null ? g.baseUnit : g.unit != null ? g.unit : null);
        this.$set(row, "unitPrice", g.unitPrice != null ? g.unitPrice : null);
        /** 有数量与单价则统一按乘积重算金额，否则用接口金额 */
        const q = Number(row.quantity);
        const p = Number(row.unitPrice);
        if (Number.isFinite(q) && Number.isFinite(p)) {
          this.recalcLineAmount(idx);
        } else if (g.amount != null && g.amount !== "") {
          this.$set(row, "amount", g.amount);
          this.recalcTotalAmount();
        } else {
          this.recalcLineAmount(idx);
        }
        this.$set(
          row,
          "goodsRemark",
          g.goodsRemark != null ? g.goodsRemark : g.remark != null ? g.remark : null
        );
        this.saleOutPickDialogOpen = false;
        this.$nextTick(() => {
          const formRef = this.$refs.dialogForm;
          if (formRef) formRef.validateField(`items.${idx}.deliveryNum`);
        });
      };

      if (pick.id != null && pick.id !== "") {
        getSaleOutById({ id: pick.id })
          .then((res) => {
            const data = res && res.data ? res.data : res;
            applyHeaderAndFirstGoods(data);
          })
          .catch(() => {
            applyHeaderAndFirstGoods(pick);
          });
      } else {
        applyHeaderAndFirstGoods(pick);
      }
    },
    handleAddGoodsRow() {
      if (!Array.isArray(this.form.items)) this.$set(this.form, "items", []);
      this.form.items.push(this.createEmptyGoodsRow());
    },
    handleRemoveGoodsRow(index) {
      const g = this.form.items || [];
      if (g.length <= 1) return;
      g.splice(index, 1);
      this.recalcTotalAmount();
    },
    recalcLineAmount(index) {
      const row = (this.form.items || [])[index];
      if (!row) return;
      const q = Number(row.quantity);
      const p = Number(row.unitPrice);
      const amt = Number.isFinite(q) && Number.isFinite(p) ? (q * p).toFixed(2) : null;
      this.$set(row, "amount", amt);
      this.recalcTotalAmount();
    },
    recalcTotalAmount() {
      let sum = 0;
      (this.form.items || []).forEach((r) => {
        const v = Number(r && r.amount);
        if (Number.isFinite(v)) sum += v;
      });
      this.form.totalAmount = sum.toFixed(2);
    },
    fetchCustomerOptions() {
      getClienteleList({}).then((res) => {
        this.customerOptions = (res && res.data) || [];
      });
    },
    fetchSalespersonOptions() {
      getStaffList({}).then((res) => {
        const list = (res && res.data) || [];
        this.salespersonOptions = (list || []).filter((item) => String(item.employeeType) === "3");
      });
    },
    /** 部门下拉 */
    fetchDepartmentOptions() {
      getDepartmentList({}).then((res) => {
        this.departmentOptions = (res && res.data) || [];
      });
    },
    getList() {
      this.loading = true;
      getSaleRebatePage(this.queryParams)
        .then((res) => {
          const data = (res && res.data) || {};
          this.list = data.records || [];
          this.total = data.total != null ? data.total : 0;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleSelectionChange(selection) {
      this.ids = (selection || []).map((r) => r.id);
      this.multiple = this.ids.length === 0;
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      const today = formatDateYMS(new Date().getTime());
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        dateRange: [today, today],
        customerNum: null,
        employeeNum: null,
        allowanceDateStart: today,
        allowanceDateEnd: today,
      };
      this.handleQuery();
    },
    handleAdd() {
      const today = formatDateYMS(new Date().getTime());
      this.dialogTitle = "新增";
      this.dialogMode = "add";
      this.form = {
        id: null,
        allowanceDate: today,
        allowanceNum: null,
        customerNum: null,
        customerName: null,
        employeeNum: null,
        employeeName: null,
        departmentNum: null,
        departmentName: null,
        remark: null,
        totalAmount: "0.00",
        items: [],
      };
      getLatestSaleRebateNum({}).then((res) => {
        this.form.allowanceNum = (res && res.msg) || "";
      });
      this.form.items = [this.createEmptyGoodsRow()];
      this.dialogOpen = true;
      this.$nextTick(() => this.$refs.dialogForm && this.$refs.dialogForm.clearValidate());
    },
    handleDetail(row) {
      this.dialogTitle = "查看详情";
      this.dialogMode = "view";
      getSaleRebateById({ id: row.id }).then((res) => {
        const data = res.data || {};
        const { goods: _legacyGoods, items: _rawItems, ...rest } = data;
        this.form = { ...rest, items: this.resolveItemsFromRow(data) };
        this.dialogOpen = true;
      });
    },
    handleEdit(row) {
      this.dialogTitle = "编辑";
      this.dialogMode = "edit";
      getSaleRebateById({ id: row.id }).then((res) => {
        const data = res.data || {};
        const { goods: _legacyGoods, items: _rawItems, ...rest } = data;
        this.form = { ...rest, items: this.resolveItemsFromRow(data) };
        this.dialogOpen = true;
        this.$nextTick(() => this.$refs.dialogForm && this.$refs.dialogForm.clearValidate());
      });
    },
    submitForm() {
      if (this.dialogMode === "view") return;
      this.$refs.dialogForm.validate((valid) => {
        if (!valid) return;
        /** 提交明细 items；去掉可能残留的 goods 字段 */
        const { goods: _dropGoods, items: _dropItems, ...formRest } = this.form;
        const payload = {
          ...formRest,
          items: (this.form.items || []).map((r) => ({
            ...r,
            remark: r.goodsRemark != null ? r.goodsRemark : r.remark,
          })),
        };
        if (this.dialogMode === "add") {
          addSaleRebate(payload).then(() => {
            this.$message.success("保存成功");
            this.dialogOpen = false;
            this.getList();
          });
        } else {
          editSaleRebate(payload).then(() => {
            this.$message.success("保存成功");
            this.dialogOpen = false;
            this.getList();
          });
        }
      });
    },
    handleDeleteAll() {
      if (!this.ids.length) return;
      this.$confirm("确定删除选中的数据吗？", "提示", { type: "warning" })
        .then(() => {
          delSaleRebate({ ids: this.ids.join(",") }).then(() => {
            this.$message.success("删除成功");
            this.getList();
          });
        })
        .catch(() => {});
    },
    handleDelete(row) {
      this.$confirm("确定要删除这条数据吗？", "提示", { type: "warning" })
        .then(() => {
          delSaleRebate({ ids: row.id }).then(() => {
            this.$message.success("删除成功");
            this.getList();
          });
        })
        .catch(() => {});
    },
  },
};
</script>

<style scoped lang="scss">
.sale-rebate-page {
  display: flex;
  flex-direction: column;
}

.mb8 {
  margin-bottom: 8px;
}

.dialog-detail-body {
  height: calc(100vh - 140px);
  display: flex;
  flex-direction: column;
}

.dialog-detail-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

::v-deep .dialog-detail-card > .el-card__body {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
}

.detail-desc {
  flex-shrink: 0;
}

.detail-desc--foot {
  margin-top: 12px;
}

.dialog-table-card--detail {
  flex: 1;
  min-height: 0;
  margin-top: 12px;
}

.dialog-body {
  height: calc(100vh - 140px);
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.dialog-main-form {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  gap: 12px;
  overflow: hidden;
}

.dialog-head-card {
  flex-shrink: 0;
}

.dialog-detail-toolbar {
  flex-shrink: 0;
}

.dialog-table-card {
  flex: 1;
  min-height: 0;
  overflow: hidden;
}

::v-deep .dialog-table-card > .el-card__body {
  height: 100%;
  min-height: 0;
  overflow: hidden;
}

.dialog-foot-card {
  flex-shrink: 0;
}

/** 销售单号旁搜索按钮与 tooltip */
.dialog-sale-out-append {
  display: inline-block;
  vertical-align: middle;
  line-height: 1;
}

::v-deep .dialog-goods-form-item {
  margin-bottom: 0;
}

::v-deep .dialog-table--with-form .el-table__cell {
  overflow: visible !important;
  vertical-align: top;
}

::v-deep .dialog-table--with-form .el-form-item__error {
  position: static !important;
  white-space: nowrap;
  line-height: 1.2;
  padding-top: 2px;
}

.sale-out-pick-query-form {
  margin-bottom: 12px;
}

::v-deep .sale-out-pick-dialog .sale-out-pick-table .el-table__body tr.current-row > td {
  background-color: #d9ecff !important;
}
</style>
