<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="payeeName">
                <el-input v-model="queryParams.payeeName" clearable placeholder="请输入收款人名称" @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="付款人银行账号" prop="bankAccount">
                <el-input v-model="queryParams.bankAccount" clearable placeholder="请输入付款人银行账号" @keyup.enter="handleQuery" />
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="实收实付号码" prop="recPayNo">
                <el-input v-model="queryParams.recPayNo" clearable placeholder="请输入实收实付号码" @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="保单号" prop="policyNumber">
                <el-input v-model="queryParams.policyNumber" clearable placeholder="请输入保单号" @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="业务号码" prop="businessNo">
                <el-input v-model="queryParams.businessNo" clearable placeholder="请输入业务号码" @keyup.enter="handleQuery" />
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="数据来源" prop="fromSystem">
                <el-select v-model="queryParams.fromSystem" clearable placeholder="请输入数据来源">
                  <el-option v-for="dict in sys_from_system" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="付费方式" prop="paymentMethod">
                <el-select v-model="queryParams.paymentMethod" clearable placeholder="请输入付费方式">
                  <el-option v-for="dict in sys_pay_method" :key="dict.value" :label="dict.value + '-' + dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="付费状态" prop="transState">
                <el-select v-model="queryParams.transState" clearable placeholder="请输入付费状态">
                  <el-option v-for="dict in bls_transfer_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="应收日期">
                <el-date-picker
                  v-model="dateRangeRece"
                  end-placeholder="结束日期"
                  range-separator="-"
                  start-placeholder="开始日期"
                  type="daterange"
                  value-format="YYYY-MM-DD"
                >
                </el-date-picker>
              </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="180" />
        <el-table-column align="center" label="应付日期" prop="payableDate" width="180" />
        <el-table-column align="center" label="到账日期" prop="PayDate" width="180" />
        <el-table-column align="center" label="实收实付号码" prop="recPayNo" width="180" />
        <el-table-column align="center" label="批次号" prop="transferBatchNumber" width="180"> </el-table-column>
        <el-table-column align="center" label="实付号码" prop="recPayNo" width="180"> </el-table-column>
        <el-table-column align="center" label="业务号码" prop="businessNumber" width="180"> </el-table-column>
        <el-table-column align="center" label="收款人名称" prop="payeeName" width="180"> </el-table-column>
        <el-table-column align="center" label="收款银行" prop="corpBank" width="180"> </el-table-column>
        <el-table-column align="center" label="收款人银行账号" prop="payerBankAccount" width="180"> </el-table-column>
        <el-table-column align="center" label="付费方式" prop="paymentMethod" width="180"> </el-table-column>
        <el-table-column align="center" label="金额" prop="amount" width="180"> </el-table-column>
        <el-table-column align="center" label="支出户" prop="corpAct" width="180"> </el-table-column>
        <el-table-column align="center" label="凭证号" prop="belnrSap" width="180"> </el-table-column>
        <el-table-column align="center" label="银行记账码" prop="reconciliationCode" width="180"> </el-table-column>
        <el-table-column align="center" label="备注" prop="virtualAccount" width="180"> </el-table-column>
      </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 { listPayablesDetailDetail } from '@/api/bls/payablesDetail';
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 dateRangeRece = ref<[string, string]>(['', '']);
const dateRangeChar = ref<[string, string]>(['', '']);
const dateRangeSend = ref<[string, string]>(['', '']); // 制盘时间
const amountBigen = ref<number | null>(null);
const amountEnd = ref<number | null>(null);
const amountRange = ref<[number | null, number | null]>([null, null]);

// 字典数据（保留原有逻辑）
const { sys_managecom } = toRefs<any>(proxy?.useDict('sys_managecom'));
const { sys_pay_method } = toRefs<any>(proxy?.useDict('sys_pay_method'));
const { sys_from_system } = toRefs<any>(proxy?.useDict('sys_from_system'));
const { bls_transfer_status } = toRefs<any>(proxy?.useDict('bls_transfer_status'));

const likeName = ref('');
const filteredManagecom = ref([]);
const sys_managecomCache = ref([]);

// 查询参数（结构不变）
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  manageCom: undefined,
  payeeName: undefined,
  bankAccount: undefined,
  recPayNo: undefined,
  policyNumber: undefined,
  businessNo: undefined,
  fromSystem: undefined,
  paymentMethod: undefined,
  transState: undefined,
  params: {}
});

/** 获取收费明细列表 */
const getList = async () => {
  loading.value = true;
  try {
    // 日期范围处理（保留原有逻辑）
    queryParams.params = {};
    if (dateRangeRece.value?.length === 2) {
      queryParams.params.beginRece = dateRangeRece.value[0];
      queryParams.params.endRece = dateRangeRece.value[1];
    }
    if (dateRangeChar.value?.length === 2) {
      queryParams.params.beginChar = dateRangeChar.value[0];
      queryParams.params.endChar = dateRangeChar.value[1];
    }

    // 调用收费明细专用接口
    const res = await listPayablesDetailDetail(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 (dateRangeRece.value?.length === 2) {
    exportParams.params.beginRece = dateRangeRece.value[0];
    exportParams.params.endRece = dateRangeRece.value[1];
  } else {
    delete exportParams.params.beginRece;
    delete exportParams.params.endRece;
  }
  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
    },
    `payablesDetails_${new Date().getTime()}.xlsx`
  );
};
/** 管理机构模糊查询（保留原有逻辑） */
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 getCache = async () => {
  const res = await queryManageCom();
  if (res.code == 200) {
    sys_managecomCache.value = res.data;
    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();
};

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