<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" :inline="true" :model="queryParams" @submit.prevent="handleQuery">
            <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="customerName">
                  <el-input v-model.trim="queryParams.customerName" placeholder="请输入客户姓名"></el-input>
                </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 class="flex-1" shadow="never">
      <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" :data="ArrearsDetailList" border>
        <el-table-column align="center" label="区域" prop="villageName" />
        <el-table-column align="center" label="房屋类型" prop="houseTypeName" />
        <el-table-column align="center" label="户号" prop="houseNo" />
        <el-table-column align="center" label="客户" prop="customerName" />
        <el-table-column align="center" label="预收账期" prop="prepaidPeriod" />
        <el-table-column align="center" label="预收月份" prop="prepaidMonths" />
        <el-table-column align="center" label="收费项目" prop="chargeItemAmounts">
          <template #default>
            <el-table-column v-for="item in rowChargeTypesList" :key="item" :label="item.chargeItemName" align="center">
              <template #default="scope">
                {{ scope.row.chargeItemAmounts[item.chargeItemName] }}
              </template>
            </el-table-column>
          </template>
        </el-table-column>
        <el-table-column align="center" label="合计" prop="totalAmount" />
      </el-table>
      <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum" :total="total" @pagination="getList" />
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import pagination from '@/components/Pagination/index.vue';
import pageHeader from '@/components/Pageheader/index.vue';
import { getCommunitylistAPI } from '@/api/system/community';
import { ColumnConfig, exportToExcel } from '@/utils/xlsx';
import { listHouseUseType } from '@/api/system/houseUse';
import { Row } from '@/api/system/report/prepaidBalance/type';
import { getPrepaidBalanceDetailList } from '@/api/system/report/prepaidBalanceDetail';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
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: '',
    customerName: ''
  }
});

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 rowChargeTypesList = ref([]);

/** 查询电抄记录列表 */
const getList = async () => {
  loading.value = true;
  const search = { ...queryParams.value };
  // 移除空字符串字段
  Object.keys(search).forEach((key) => {
    if (search[key] === '-1') {
      search[key] = undefined;
    }
  });
  getPrepaidBalanceDetailList(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: '',
    customerName: ''
  };
  handleQuery();
};
/** 导出Excel */
const handleExport = async () => {
  if (ArrearsDetailList.value.length === 0) {
    proxy?.$modal.msgWarning('没有可导出的数据');
    return;
  }
  const search = { ...queryParams.value, pageNum: undefined, pageSize: undefined };
  // 移除空字符串字段
  Object.keys(search).forEach((key) => {
    if (search[key] === '-1') {
      search[key] = undefined;
    }
  });
  loading.value = true;
  try {
    // const res = await getPrepaidBalanceDetailList(search);
    // ArrearsDetailList.value = [...res.rows];
    // 显示加载提示
    // 使用 setTimeout 让出主线程，避免阻塞UI
    setTimeout(() => {
      try {
        const columns: ColumnConfig[] = [
          { label: '小区名称', prop: 'villageName' },
          { label: '房屋类型', prop: 'houseTypeName' },
          { label: '户号', prop: 'houseNo' },
          { label: '客户', prop: 'customerName' },
          { label: '预收账期', prop: 'prepaidPeriod' },
          { label: '预收月份', prop: 'prepaidMonths' },
          {
            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);
  } catch (error) {
    loading.value = false;
    proxy?.$modal.msgError('导出失败，请重试');
  }
};
onMounted(() => {
  getList();
  getHouseUseList();
  getAllVillage();
});
</script>

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