<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="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>
                <el-form-item label="区域" prop="chargeItemId">
                  <el-select @change="handleVillageChange" 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="houseNo">
                  <el-input v-model.trim="queryParams.houseNo" placeholder="请输入房号" />
                </el-form-item>
                <el-form-item label="欠费月数" prop="month">
                  <el-select v-model="queryParams.month" placeholder="请选择">
                    <el-option v-for="item in MonthList" :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="15"></el-col>
          <el-col :span="3">
            <el-button type="primary" @click="handleExport">导出本页</el-button>
            <el-button type="primary" @click="handleExportAll">导出全部</el-button>
          </el-col>
        </el-row>
      </template>

      <el-table :span-method="mergeSpanMethod" v-loading="loading" border :data="ArrearsDetailList">
        <el-table-column label="序号" width="80" align="center" prop="serialNumber" />
        <el-table-column label="区域" align="center" prop="area" />
        <el-table-column label="房号" align="center" prop="houseNo" />
        <el-table-column label="客户" align="center" prop="customerName" />
        <el-table-column label="联系电话" align="center" prop="phone" />
        <el-table-column label="欠费月数" width="80" align="center" prop="arrearsMonths" />
        <el-table-column label="应收账期" align="center" prop="billPeriod" />
        <el-table-column label="欠费项目" align="center">
          <template #default>
            <template v-for="(item, index) in dynamicColumns" :key="index">
              <el-table-column :label="item" align="center">
                <template #default="scope">
                  {{ scope.row.chargeItemAmounts?.[item] || 0 }}
                </template>
              </el-table-column>
            </template>
            <el-table-column label="金额合计" align="center" prop="totalAmount">
              <template #default="scope">
                <span style="color: red">{{ scope.row.totalAmount }}</span>
              </template>
            </el-table-column>
          </template>
        </el-table-column>
      </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 name="Arrears" lang="ts">
import pagination from '@/components/Pagination/index.vue';
import pageHeader from '@/components/Pageheader/index.vue';
import { getArrearsDetails } from '@/api/system/report/arrears/arrears';
import { getCommunitylistAPI } from '@/api/system/community';
import { OwnerArrearsDetailVo } from '@/api/system/report/arrears/type';
import { validator } from '@/utils/Reg';
import { ColumnConfig, exportToExcel } from '@/utils/xlsx';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const ArrearsDetailList = ref<OwnerArrearsDetailVo[]>([]);
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.startTime = val[0];
  queryParams.value.endTime = val[1];
}
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    villageId: '-1',
    startTime: '',
    endTime: '',
    houseNo: '',
    month: '-1'
  },
  rule: [
    {
      validator: (_: any, value: string, callback: (arg0?: Error) => any) => {
        if (value === '' || value === undefined || value === null) {
          return callback();
        }
        if (!validator(value, 'fullFilterReg')) {
          return callback(new Error('请输入正确的房号'));
        }
      }
    }
  ]
});

const { queryParams } = toRefs(data);

// 查询小区
const villageList = ref([]);
function getAllVillage() {
  getCommunitylistAPI().then((res) => {
    villageList.value = [
      {
        villageId: '-1',
        villageName: '全部区域'
      },
      ...res.rows
    ];
  });
}
// 区域改变时，查询收费项目
function handleVillageChange(val: string) {
  queryParams.value.villageId = val;
  queryParams.value.houseNo = '-1';
}
// 月份
const MonthList = ref([]);
function getMonthList() {
  const arr = Array.from({ length: 12 }).fill((i) => {
    return {
      id: `${i + 1}`,
      name: `${i + 1}月`
    };
  });
  MonthList.value = [];
  MonthList.value = [
    {
      id: '-1',
      name: '全部月数'
    },
    ...arr
  ];
}
// 动态列名列表▐╬ .3╬
const dynamicColumns = ref<string[]>([]);

// 在获取数据后更新动态列
const updateDynamicColumns = (list: any[]) => {
  const columns = new Set<string>();
  list.forEach((row) => {
    if (row.chargeItemAmounts) {
      Object.keys(row.chargeItemAmounts).forEach((key) => columns.add(key));
    }
  });
  return Array.from(columns);
};

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

      ArrearsDetailList.value[ArrearsDetailList.value.length - 1].serialNumber = '合计';
    })
    .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: 'serialNumber' },
        { label: '区域', prop: 'area' },
        { label: '房号', prop: 'houseNo' },
        { label: '客户', prop: 'customerName' },
        { label: '联系方式', prop: 'phone' },
        { label: '欠费月数', prop: 'arrearsMonths' },
        { label: '应收账期', prop: 'billPeriod' },
        {
          label: '欠费项目',
          children: [
            ...dynamicColumns.value.map((item) => {
              return { label: item, prop: `chargeItemAmounts.${item}` };
            })
          ]
        }
      ];
      exportToExcel(ArrearsDetailList.value, columns, `应收欠费明细表_${new Date().getTime()}`, mergeSpanMethod);
    } catch (error) {
      proxy?.$modal.msgError('导出失败，请重试');
      console.error('导出错误:', error);
    } finally {
      loading.value = false;
    }
  }, 100);
};

const handleExportAll = () => {
  loading.value = true;
  let reportAllList: OwnerArrearsDetailVo[] = [];
  // 移除空字符串字段
  getArrearsDetails()
    .then((res) => {
      reportAllList = res.rows;
      total.value = res.total;
      reportAllList[reportAllList.length - 1].serialNumber = '合计';
      if (reportAllList.length === 0) {
        proxy?.$modal.msgWarning('没有可导出的数据');
        return;
      }
      // 显示加载提示
      const list = updateDynamicColumns(res.rows);
      loading.value = true;
      // 使用 setTimeout 让出主线程，避免阻塞UI
      setTimeout(() => {
        try {
          const columns: ColumnConfig[] = [
            { label: '序号', prop: 'serialNumber' },
            { label: '区域', prop: 'area' },
            { label: '房号', prop: 'houseNo' },
            { label: '客户', prop: 'customerName' },
            { label: '联系方式', prop: 'phone' },
            { label: '欠费月数', prop: 'arrearsMonths' },
            { label: '应收账期', prop: 'billPeriod' },
            {
              label: '欠费项目',
              children: [
                ...list.map((item) => {
                  return { label: item, prop: `chargeItemAmounts.${item}` };
                })
              ]
            }
          ];
          const mergeSpanMethod2 = ({ columnIndex, rowIndex }) => {
            if (rowIndex === reportAllList.length - 1) {
              const rowspan = 6;
              if (columnIndex === 0) {
                return { rowspan: 1, colspan: 1 };
              }
              if (columnIndex === 1) {
                return { rowspan: 1, colspan: rowspan };
              }
              if (columnIndex < rowspan + 1) {
                return { rowspan: 0, colspan: 0 };
              }
            }
            // 普通行不合并
            return { rowspan: 1, colspan: 1 };
          };
          exportToExcel(reportAllList, columns, `应收欠费明细表_${new Date().getTime()}`, mergeSpanMethod2);
        } catch (error) {
          proxy?.$modal.msgError('导出失败，请重试');
          console.error('导出错误:', error);
        } finally {
          loading.value = false;
        }
      }, 100);
    })
    .finally(() => {
      loading.value = false;
    });
};

const mergeSpanMethod = ({ columnIndex, rowIndex }) => {
  if (rowIndex === ArrearsDetailList.value.length - 1) {
    const rowspan = 6;
    if (columnIndex === 0) {
      return { rowspan: 1, colspan: 1 };
    }
    if (columnIndex === 1) {
      return { rowspan: 1, colspan: rowspan };
    }
    if (columnIndex < rowspan + 1) {
      return { rowspan: 0, colspan: 0 };
    }
  }
  // 普通行不合并
  return { rowspan: 1, colspan: 1 };
};

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

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