<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="customerName">
                  <el-input v-model.trim="queryParams.customerName"></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 shadow="never" class="flex-1">
      <template #header>
        <el-row :gutter="10">
          <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 :row-class-name="handleRowClass" v-loading="loading" border :data="ArrearsDetailList">
        <el-table-column label="日期" width="100" align="center" fixed="left" prop="payTime" />
        <el-table-column label="房屋信息" align="center" fixed="left">
          <template #default>
            <el-table-column label="户主" align="center" width="100" prop="residentName"></el-table-column>
            <el-table-column label="房号" align="center" width="100" prop="houseName"></el-table-column>
          </template>
        </el-table-column>
        <el-table-column label="支付方式" align="center">
          <template #default>
            <el-table-column label="现金类" align="center" prop="cashAmount">
              <template #default>
                <el-table-column label="现金" align="center" prop="cashAmount"></el-table-column>
                <el-table-column label="银联" align="center" prop="unionPayAmount"></el-table-column>
                <el-table-column label="转账" align="center" prop="transferAmount"></el-table-column>
                <el-table-column label="微信商户" align="center" prop="wechatAmount"></el-table-column>
              </template>
            </el-table-column>
            <el-table-column label="顶账类" align="center" prop="deposit">
              <template #default>
                <el-table-column label="押金抵顶" align="center" prop="depositAmount"></el-table-column>
                <el-table-column label="减免优惠" align="center" prop="discountAmount"></el-table-column>
              </template>
            </el-table-column>
          </template>
        </el-table-column>
        <el-table-column label="水费" align="center" prop="waterFee" />
        <el-table-column label="电费" align="center" prop="electricFee" />
        <el-table-column label="押金" align="center" prop="deposit" />
        <el-table-column label="收费项目" align="center" prop="chargeTypeAmounts">
          <template #default>
            <el-table-column v-for="(item, index) in rowChargeTypesList" :key="index" :label="item" align="center">
              <template #default="scope">
                <el-table-column label="金额" align="center" v-if="item !== '卡表' && item !== '其他'">
                  <template #default="scope">
                    {{ scope.row.chargeTypeAmounts[item].amount }}
                  </template>
                </el-table-column>
                <el-table-column label="开始时间" width="100" align="center" v-if="item !== '卡表' && item !== '其他'">
                  <template #default="scope">
                    {{ scope.row.chargeTypeAmounts[item].startDate }}
                  </template>
                </el-table-column>
                <el-table-column label="结束时间" width="100" align="center" v-if="item !== '卡表' && item !== '其他'">
                  <template #default="scope">
                    {{ scope.row.chargeTypeAmounts[item].endDate }}
                  </template>
                </el-table-column>
                <span v-if="item == '卡表' || item == '其他'">{{ scope.row.chargeTypeAmounts[item].amount }}</span>
              </template>
            </el-table-column>
          </template>
        </el-table-column>
        <el-table-column label="经办人" align="center" prop="handler" />
        <el-table-column show-overflow-tooltip width="250" label="备注" align="center" prop="remark" />
      </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 { ColumnConfig, exportToExcel } from '@/utils/xlsx';
import { listHouseUseType } from '@/api/system/houseUse';
import { getDailyFeeReportList } from '@/api/system/report/dailyFeeReport';
import { Datum } from '@/api/system/report/dailyFeeReport/type';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const ArrearsDetailList = ref<Datum[]>([]);
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;
    }
  });
  getDailyFeeReportList(search)
    .then((res) => {
      ArrearsDetailList.value = [...res.rows];
      rowChargeTypesList.value = Object.keys(res.rows[0].chargeTypeAmounts);
      total.value = res.total;
    })
    .finally(() => {
      loading.value = false;
    });
};
function handleRowClass({ row }) {
  if (row.residentName === '当日合计') {
    // 示例1：收费项目等于物业费的行加深色
    return 'bg-dark';
  }
  return '';
}

/** 搜索按钮操作 */
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 = () => {
  if (ArrearsDetailList.value.length === 0) {
    proxy?.$modal.msgWarning('没有可导出的数据');
    return;
  }

  // 显示加载提示
  loading.value = true;
  // 使用 setTimeout 让出主线程，避免阻塞UI
  setTimeout(() => {
    try {
      const columns: ColumnConfig[] = [
        { label: '日期', prop: 'payTime' },
        {
          label: '房屋信息',
          prop: 'houseName',
          children: [
            { label: '户主', prop: 'residentName' },
            { label: '户号', prop: 'houseName' }
          ]
        },
        {
          label: '支付方式',
          prop: 'paymentMethod',
          children: [
            {
              label: '现金类',
              children: [
                { label: '现金', prop: 'cashAmount' },
                { label: '银联', prop: 'unionPayAmount' },
                { label: '转账', prop: 'transferAmount' },
                { label: '微信商户', prop: 'wechatAmount' }
              ]
            },
            {
              label: '顶账类',
              children: [
                { label: '押金抵顶', prop: 'depositAmount' },
                { label: '减免优惠', prop: 'discountAmount' }
              ]
            }
          ]
        },
        { label: '水费', prop: 'waterFee' },
        { label: '电费', prop: 'electricFee' },
        { label: '押金', prop: 'deposit' },
        {
          label: '收费项目',
          prop: 'chargeTypeAmounts',
          children: [
            ...rowChargeTypesList.value.map((item) => {
              return {
                label: item,
                children: ['其他', '卡表'].includes(item)
                  ? []
                  : [
                      { label: '金额', prop: `chargeTypeAmounts.${item}.amount` },
                      { label: '开始时间', prop: `chargeTypeAmounts.${item}.startTime` },
                      { label: '截止时间', prop: `chargeTypeAmounts.${item}.endTime` }
                    ]
              };
            })
          ]
        },
        { label: '经办人', prop: 'inspectorName' },
        { label: '备注', prop: 'remark' }
      ];
      console.log(columns);
      exportToExcel(ArrearsDetailList.value, columns, `日报_${new Date().getTime()}`);
    } catch (error) {
      proxy?.$modal.msgError('导出失败，请重试');
      console.error('导出错误:', error);
    } finally {
      loading.value = false;
    }
  }, 100);
};
onMounted(() => {
  getList();
  getHouseUseList();
  getAllVillage();
});
</script>

<style lang="scss" scoped>
.el-table {
  height: calc(100% - 80px);
}
/* 深度穿透修改表格行背景 */
:deep(.bg-dark td) {
  background-color: #f5f7fa !important;
}
</style>
