<template>
  <div class="p-2 h-full flex flex-col">
    <pageHeader></pageHeader>
    <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" :model="queryParams" @submit.prevent="handleQuery" :inline="true">
            <div class="flex justify-between">
              <div>
                <el-form-item label="项目" prop="chargeItemId">
                  <el-select v-model="queryParams.villageId" placeholder="请选择">
                    <el-option v-for="item in villageList" :key="item.villageId" :label="item.villageName" :value="item.villageId" />
                  </el-select>
                </el-form-item>
                <el-form-item label="房屋类型" prop="houseUseTypeId">
                  <el-select v-model="queryParams.houseUseTypeId" placeholder="请选择">
                    <el-option v-for="item in houseUseList" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
                <el-form-item label="收费项目" prop="chargeTypeId">
                  <el-select v-model="queryParams.chargeTypeId" placeholder="请选择">
                    <el-option v-for="item in chargeTypesList" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
              </div>
              <div>
                <el-button type="primary" @click="handleQuery">查询</el-button>
                <el-button @click="resetQuery">重置</el-button>
              </div>
            </div>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never" class="flex-1">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="5">
            <span> 预收费用余额汇总 </span>
          </el-col>
          <el-col :span="18"></el-col>
          <el-col :span="1">
            <el-button type="primary" @click="handleExport">导出</el-button>
          </el-col>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="ArrearsDetailList">
        <el-table-column label="小区名称" align="center" prop="villageName" />
        <el-table-column label="房屋类型" align="center" prop="houseTypeName" />
        <el-table-column label="收费项目" align="center" prop="chargeItemAmounts">
          <template #default>
            <el-table-column :label="item.chargeItemName" align="center" v-for="item in rowChargeTypesList" :key="item">
              <template #default="scope">
                {{ scope.row.chargeItemAmounts[item.chargeItemName] }}
              </template>
            </el-table-column>
          </template>
        </el-table-column>
        <el-table-column label="合计" align="center" prop="totalAmount" />
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
  </div>
</template>
账龄
<script setup lang="ts">
import pagination from '@/components/Pagination/index.vue';
import pageHeader from '@/components/Pageheader/index.vue';
import { getCommunitylistAPI } from '@/api/system/community';
import { validator } from '@/utils/Reg';
import { listChargeType } from '@/api/system/ChargeType';
import { ColumnConfig, exportToExcel } from '@/utils/xlsx';
import { getPrepaidBalanceList } from '@/api/system/report/prepaidBalance';
import { listHouseUseType } from '@/api/system/houseUse';
import { Row } from '@/api/system/report/prepaidBalance/type';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// ╬╬╬2╬╬
const ArrearsDetailList = ref<Row[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    villageId: '',
    houseUseTypeId: '',
    chargeTypeId: ''
  }
});

const { queryParams } = toRefs(data);

// 查询小区
const villageList = ref([]);
function getAllVillage() {
  getCommunitylistAPI().then((res) => {
    villageList.value = [...res.rows];
  });
}

// 收费类型
const houseUseList = ref([]);
function getHouseUseList() {
  listHouseUseType().then((res) => {
    houseUseList.value = [...res.rows];
  });
}
// 收费类型
const chargeTypesList = ref([]);
function getChargeTypeList() {
  listChargeType().then((res) => {
    chargeTypesList.value = [...res.rows];
  });
}

const rowChargeTypesList = ref([]);

/** 查询电抄记录列表 */
const getList = async () => {
  loading.value = true;
  const search = { ...queryParams.value };
  // 移除空字符串字段
  Object.keys(search).forEach((key) => {
    if (search[key] === '-1') {
      search[key] = undefined;
    }
  });
  getPrepaidBalanceList(search)
    .then((res) => {
      ArrearsDetailList.value = [...res.rows];
      rowChargeTypesList.value = res.chargeItems;
      total.value = res.total;
    })
    .finally(() => {
      loading.value = false;
    });
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    villageId: '-1',
    houseUseTypeId: '',
    chargeTypeId: '-1'
  };
  handleQuery();
};
/** 导出Excel */
const handleExport = () => {
  if (ArrearsDetailList.value.length === 0) {
    proxy?.$modal.msgWarning('没有可导出的数据');
    return;
  }

  // 显示加载提示
  loading.value = true;
  // 使用 setTimeout 让出主线程，避免阻塞UI
  setTimeout(() => {
    try {
      const columns: ColumnConfig[] = [
        { label: '小区名称', prop: 'villageName' },
        { label: '房屋类型', prop: 'houseTypeName' },
        {
          label: '收费项目',
          prop: 'chargeItemAmounts',
          children: [
            ...rowChargeTypesList.value.map((item) => {
              return {
                label: item.chargeItemName,
                prop: `chargeItemAmounts.${item.chargeItemName}`
              };
            })
          ]
        },
        {
          label: '合计',
          prop: 'totalAmount'
        }
      ];
      exportToExcel(ArrearsDetailList.value, columns, `预收费用余额汇总_${new Date().getTime()}`);
    } catch (error) {
      proxy?.$modal.msgError('导出失败，请重试');
      console.error('导出错误:', error);
    } finally {
      loading.value = false;
    }
  }, 100);
};
onMounted(() => {
  getList();
  getChargeTypeList();
  getHouseUseList();
  getAllVillage();
});
</script>

<style lang="scss" scoped>
.el-table {
  height: calc(100% - 80px);
}
</style>
