<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :inline="true" :model="queryParams" label-position="left" label-width="130px">
            <el-row>
              <el-form-item label="管理机构" prop="manageCom">
                <el-select v-model="queryParams.manageCom" clearable placeholder="请输入管理机构">
                  <template #header>
                    <el-input v-model="likeName" placeholder="可根据机构编码或名称模糊查询" @input="filterByManageCom"></el-input>
                  </template>
                  <el-option
                    v-for="dict in filteredManagecom"
                    :key="dict.dictValue"
                    :label="dict.dictValue + '-' + dict.dictLabel"
                    :value="dict.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="暂缴费号" prop="businessReceiptNumber">
                <el-input v-model="queryParams.businessReceiptNumber" clearable placeholder="请输入暂缴费号" @keyup.enter="handleQuery" />
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="付款人姓名" prop="payerName">
                <el-input v-model="queryParams.payerName" clearable placeholder="请输入付款人姓名" @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="付款人开户行" prop="payerBank">
                <el-select v-model="queryParams.payerBank" placeholder="请输入付款人开户行">
                  <el-option v-for="dict in sys_bank_code" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="付款人银行账号" prop="payerBankAccount">
                <el-input v-model="queryParams.payerBankAccount" clearable placeholder="请输入付款人银行账号" @keyup.enter="handleQuery" />
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="收费类型" prop="paymentMethod">
                <el-select v-model="queryParams.paymentMethod" clearable placeholder="请输入收费类型">
                  <el-option v-for="dict in sys_rec_method" :key="dict.value" :label="dict.value + '-' + dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="收费日期">
                <el-date-picker
                  v-model="dateRangeChar"
                  end-placeholder="结束日期"
                  range-separator="-"
                  start-placeholder="开始日期"
                  type="daterange"
                  value-format="YYYY-MM-DD"
                >
                </el-date-picker>
              </el-form-item>
            </el-row>
            <el-form-item>
              <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>
      <!-- 表格字段调整为收费明细专用 -->
      <el-table v-loading="loading" :data="detailList">
        <el-table-column
          align="center"
          label="管理机构"
          prop="manageCom"
          width="100"
          :formatter="(row) => formatDictLabel(sys_managecom, row.manageCom)"
        />
        <el-table-column align="center" label="应收日期" prop="payableDate" width="150" />
        <el-table-column align="center" label="批次号" prop="ReqSeqID" width="150" />
        <el-table-column align="center" label="暂缴费号" prop="businessReceiptNumber" width="150" />

        <el-table-column align="center" label="保单号" prop="policyNumber" width="150" />
        <el-table-column align="center" label="业务号码" prop="businessNumber" width="150" />
        <el-table-column align="center" label="付款人名称" prop="payerName" width="150" />
        <el-table-column
          align="center"
          label="付款人开户行"
          prop="payerBank"
          width="150"
          :formatter="(row) => formatDictLabel(sys_bank_code, row.payerBank)"
        />
        <el-table-column align="center" label="付款人银行账号" prop="payerBankAccount" width="150" />
        <el-table-column align="center" label="收费方式" prop="paymentMethod" width="150" />
        <el-table-column align="center" label="金额" prop="amount" width="150" />
        <el-table-column align="center" label="收入户" prop="corpAct" width="150" />
        <el-table-column align="center" label="凭证号" prop="belnrSap" width="150" />
        <el-table-column align="center" label="银行记账码" prop="reconciliationCode" width="150" />
        <el-table-column align="center" label="备注" prop="virtualAccount" width="150" />
      </el-table>

      <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum" :total="total" @pagination="getList" />

      <!-- 权限标识更新为明细专用 -->
      <el-row>
        <el-button v-hasPermi="['bls:receivablesDetail:export']" icon="Download" type="success" @click="handleExport"> 导出明细 </el-button>
      </el-row>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
// 接口路径更新为明细专用
import { listReceivablesDetail, exportReceivablesDetail } from '@/api/bls/receivablesDetail';
import { parseTime } from '@/utils/ruoyi';
import {queryManageCom} from "@/api/bls/cache";

const { proxy } = getCurrentInstance() as any;
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const detailList = ref([]); // 数据变量重命名

// 日期范围参数（保留原有逻辑）

const dateRangeChar = ref<[string, string]>(['', '']);
// 字典数据（保留原有逻辑）
const { sys_managecom } = toRefs<any>(proxy?.useDict('sys_managecom'));
const { sys_rec_method } = toRefs<any>(proxy?.useDict('sys_rec_method'));
const { sys_from_system } = toRefs<any>(proxy?.useDict('sys_from_system'));
const { bls_transfer_status } = toRefs<any>(proxy?.useDict('bls_transfer_status'));
const { sys_bank_code } = toRefs<any>(proxy?.useDict('sys_bank_code'));
const likeName = ref('');
const filteredManagecom = ref([]);
const sys_managecomCache = ref([]);

// 查询参数（结构不变）
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  manageCom: undefined,
  businessReceiptNumber: undefined,
  payerName: undefined,
  payerBank: undefined,
  payerBankAccount: undefined,
  paymentMethod: undefined,
  params: {}
});
// 使用可选链避免报错 + 添加回退显示
const formatDictLabel = (dictRef, value) => {
  if (!value) return '—';
  const dictItems = dictRef?.value ?? [];
  const dictItem = dictItems.find((item) => item.value === value);
  return dictItem?.label ?? value;
};

/** 获取收费明细列表 */
const getList = async () => {
  loading.value = true;
  try {
    if (dateRangeChar.value?.length === 2) {
      queryParams.params.beginChar = dateRangeChar.value[0];
      queryParams.params.endChar = dateRangeChar.value[1];
    } else {
      // 清除未选择的日期参数
      delete queryParams.params.beginChar;
      delete queryParams.params.endChar;
    }

    // 调用收费明细专用接口
    const res = await listReceivablesDetail(queryParams);
    detailList.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};
// /** 导出明细 */
const handleExport = () => {
  // proxy?.$modal.confirm('确认导出收费明细数据?');
  // 创建导出专用参数对象
  const exportParams = {
    ...queryParams,
    pageNum: undefined, // 清除分页参数
    pageSize: undefined,
    // 直接添加日期参数到顶层
    params: { ...queryParams.params } // 保持嵌套结构一致性
  };
  // 日期处理与getList完全一致
  if (dateRangeChar.value?.length === 2) {
    exportParams.params.beginChar = dateRangeChar.value[0];
    exportParams.params.endChar = dateRangeChar.value[1];
  } else {
    delete exportParams.params.beginChar;
    delete exportParams.params.endChar;
  }
  proxy?.download(
    '/bls/blsQury/charge/export',
    {
      ...exportParams
    },
    `payablesDetail_${new Date().getTime()}.xlsx`
  );
};

/** 金额校验（保留原有逻辑） */
const checkAmount = () => {
  const regex = /^\d+(\.\d{1,2})?$/;
  if (amountBigen.value && !regex.test(String(amountBigen.value))) {
    proxy?.$modal.msgError('开始金额格式错误（最多2位小数）');
    return false;
  }
  if (amountEnd.value && !regex.test(String(amountEnd.value))) {
    proxy?.$modal.msgError('结束金额格式错误（最多2位小数）');
    return false;
  }
  if (amountBigen.value && amountEnd.value && amountBigen.value > amountEnd.value) {
    proxy?.$modal.msgError('开始金额不能大于结束金额');
    return false;
  }
  return true;
};

/** 管理机构模糊查询（保留原有逻辑） */
const filterByManageCom = () => {
  if (likeName.value) {
    filteredManagecom.value = sys_managecomCache.value.filter((item) => {
      return item.dictLabel.includes(likeName.value) || item.dictValue.includes(likeName.value);
    });
  } else {
    filteredManagecom.value = sys_managecomCache.value;
  }
};

/** 搜索与重置（保留原有逻辑） */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};
const resetQuery = () => {
  dateRangeRece.value = ['', ''];
  dateRangeChar.value = ['', ''];
  dateRangeSend.value = ['', ''];
  amountBigen.value = null;
  amountEnd.value = null;
  proxy?.resetForm('queryFormRef');
  handleQuery();
};

const getCache = async () => {
  const res = await queryManageCom();
  if (res.code == 200) {
    sys_managecomCache.value = res.data;
    filteredManagecom.value = sys_managecomCache.value;
  }
};

onMounted(() => {
  getList();
  getCache();
});
</script>
