<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="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>
                <el-form-item label="查询日期" prop="villageId">
                  <el-date-picker
                    v-model="queryTime"
                    type="daterange"
                    @update:model-value="handleQueryTime"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                  />
                </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="name" />
        <el-table-column label="序号" align="center" prop="sequence" />
        <template v-for="item in rowChargeTypesList" :key="item">
          {{ item }}
          <el-table-column :label="item" align="center">
            <template #default="scope">
              {{ scope.row.amounts[item] }}
            </template>
          </el-table-column>
        </template>
        <el-table-column label="合计" align="center" prop="total" />
      </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 { getPaidInExpensesReceivableList } from '@/api/system/report/paidInExpensesReceivable';
import { Detail } from '@/api/system/report/paidInExpensesReceivable/type';
import { listChargeType } from '@/api/system/ChargeType';
import { ColumnConfig, exportToExcel } from '@/utils/xlsx';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const ArrearsDetailList = ref<Detail[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const queryTime = ref([]);
function handleQueryTime(val: string[]) {
  queryParams.value.startDate = val[0];
  queryParams.value.endDate = val[1];
}
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    villageId: '-1',
    startDate: '',
    endDate: '',
    chargeTypeId: '-1'
  }
});

const { queryParams } = toRefs(data);

// 查询小区
const villageList = ref([]);
function getAllVillage() {
  getCommunitylistAPI().then((res) => {
    villageList.value = [
      {
        villageId: '-1',
        villageName: '全部区域'
      },
      ...res.rows
    ];
  });
}

// 忽略的收费项目id， 水费，电费，燃气费，上线前手工导入
const ignoreChargeItemList = ['2049026503017136129', '2064181187503652865', '2091072780916981761', '2049026540430327809'];
// 收费类型
const chargeTypesList = ref([]);
function getChargeTypeList() {
  listChargeType().then((res) => {
    chargeTypesList.value = [
      {
        name: '全部类型',
        id: '-1'
      },
      ...res.rows.filter((item) => !ignoreChargeItemList.includes(item.id))
    ];
  });
}

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;
    }
  });
  getPaidInExpensesReceivableList(search)
    .then((res) => {
      console.log(res);
      ArrearsDetailList.value = [res.data.total, ...res.data.details];
      rowChargeTypesList.value = res.data.chargeTypes;
    })
    .finally(() => {
      loading.value = false;
    });
};

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  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: 'name'
        },
        {
          label: '序号',
          prop: 'sequence'
        },
        ...rowChargeTypesList.value.map((item) => {
          return {
            label: item,
            prop: `amounts.${item}`
          };
        }),
        {
          label: '合计',
          prop: 'total'
        }
      ];
      exportToExcel(ArrearsDetailList.value, columns, `应收物业费详情_${new Date().getTime()}`);
    } catch (error) {
      proxy?.$modal.msgError('导出失败，请重试');
      console.error('导出错误:', error);
    } finally {
      loading.value = false;
    }
  }, 100);
};
onMounted(() => {
  getList();
  getChargeTypeList();
  getAllVillage();
});
</script>

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