<script lang="ts" setup>
import Analyse from '@/components/Analyse/index.vue';
import { onMounted, reactive, ref } from 'vue';
import dayjs from 'dayjs';
import { currentMouth, days } from '@/enums/dateEnums';
import { fetchGetExpendOrIncome } from '@/api/v1/financial/user/billUser';
import { $t } from '@/plugins/i18n';

const title = {
	analyse: $t('expenditureAnalysis'),
	category: $t('paymentLedger'),
	table: $t('dataStatistics'),
	top: $t('rankingList'),
};
// 分析概览
const analyseXAxis = ref([]);
const analyseData = ref([]);
// 分类数据
const categoryList = ref([]);
// 排行榜数据
const topList = ref([]);

const form = reactive({
	type: -1,
	startDate: dayjs(currentMouth[0]).format('YYYY-MM-DD'),
	endDate: dayjs(currentMouth[1]).format('YYYY-MM-DD'),
});

/** 查询账单支出 */
const onSearch = async () => {
	// 格式化请求数据
	form.startDate = dayjs(form.startDate).format('YYYY-MM-DD');
	form.endDate = dayjs(form.endDate).format('YYYY-MM-DD');

	// 获取数据
	const result = await fetchGetExpendOrIncome(form);
	if (result.code !== 200) return;

	// 分析概览
	analyseData.value = [];
	analyseXAxis.value = [];
	result.data.list.forEach(item => {
		const transactionDate = item.transactionDate;
		const date = `${dayjs(transactionDate).format('MM-DD')} ${days[dayjs(transactionDate).day()]}`;
		analyseData.value.push(item.amount);
		analyseXAxis.value.push(date);
	});

	// 分类数据
	categoryList.value = result.data.categoryAmounts.map(categoryAmount => ({
		value: categoryAmount.amount,
		name: categoryAmount.categoryName,
	}));

	// 排行榜
	topList.value = result.data.list.map(item => {
		const transactionDate = item.transactionDate;
		const date = `${dayjs(transactionDate).format('YYYY-MM-DD')} ${days[dayjs(transactionDate).day()]}`;
		return { date, amount: item.amount, name: item.categoryName };
	});
};

/** 选择查询日期 */
const onChangeDateRange = async dateRange => {
	form.startDate = dateRange[0];
	form.endDate = dateRange[1];
	await onSearch();
};

onMounted(() => {
	onSearch();
});
</script>

<template>
	<Analyse
		:analyse-data="analyseData"
		:analyseXAxis="analyseXAxis"
		:category-data="categoryList"
		:color="['#41b6ff', '#F56C6C']"
		:date="[form.startDate, form.endDate]"
		:financialType="form.type"
		:title="title"
		:top-data="topList"
		@emit-date-range="onChangeDateRange"
	/>
</template>
