<script lang="ts" setup>
import { onMounted } from 'vue';

import { statisticsApi } from '#/api/statistics';
import MonthReportView from '#/views/statistics/common/MonthReportView.vue';

import { useMonthReport } from '../common/useMonthReport';

interface IncomeItem {
  fee: number;
  point: number;
}

interface Report {
  incomes: Record<string, IncomeItem>;
  consumes: Record<string, number>;
  surplus: number;
}

interface ReportItem {
  type: string;
  fee: number;
  point: number;
}

const { year, disabledDate, list, loading, getList, downloadReport, downloadAllReport } =
  useMonthReport<Report>({
    fetchMonth: (p) => statisticsApi.getReportTianyibi(p),
    downloadFile: (p) => statisticsApi.downloadReportTianyibi(p),
    fileNameBuilder: (y, m) => `天医币报表_${y}年${m}月_文件.xlsx`,
    normalize: (data) => ({
      incomes: {
        微信: { fee: 0, point: 0 },
        支付宝: { fee: 0, point: 0 },
        银行: { fee: 0, point: 0 },
        ...Object.fromEntries(
          data.map.incomes.map((item: ReportItem) => [
            item.type,
            { fee: item.fee, point: item.point },
          ]),
        ),
      },
      consumes: {
        实物: 0,
        培训班: 0,
        vip: 0,
        课程: 0,
        ...Object.fromEntries(data.map.consumes.map((item: ReportItem) => [item.type, item.fee])),
      },
      surplus: data.map.surplus,
    }),
  });

const onUpdateYear = (v: any) => {
  year.value = v;
};
onMounted(() => {
  getList();
});
</script>

<template>
  <MonthReportView
    :year="year"
    :disabled-date="disabledDate"
    :loading="loading"
    :list="list"
    :download-all="downloadAllReport"
    :download-month="downloadReport"
    content-item-class="h-[180px]"
    @update:year="onUpdateYear"
    @query="getList"
  >
    <template #default="{ item }">
      <div class="-m-2 text-[16px]">
        <div class="flex">
          <div class="min-w-[50%] bg-[#F6FFF5] px-2 pb-1">
            <div class="p-1 text-center font-bold">进项</div>
            <div v-for="(value, type) in item.incomes" :key="type" class="p-1">
              <span class="text-gray-500">{{ type }}：</span>
              <span class="text-black">{{
                `￥${value.fee}${!value.point || value.fee === value.point ? '' : `（天医币${value.point}）`}`
              }}</span>
            </div>
          </div>
          <div class="flex-1 bg-[#FFFBF0] px-2 pb-1">
            <div class="p-1 text-center font-bold">出项</div>
            <div v-for="(fee, type) in item.consumes" :key="type" class="p-1">
              <span class="text-gray-500">{{ type }}：</span>
              <span class="text-black">{{ fee }}</span>
            </div>
          </div>
        </div>
        <div class="px-2">APP用户剩余天医币 : {{ item.surplus }}</div>
      </div>
    </template>
  </MonthReportView>
</template>
<style scoped lang="scss"></style>
