import { ref } from 'vue';
import { days } from '@/enums/dateEnums';
import { fetchHomeDatalist } from '@/api/v1/system/system';
import { default as dayjs } from 'dayjs';
import { $t } from '@/plugins/i18n';

// 支出百分比
export const expendPercent = ref(0);
// 顶部图表数据
export const chartData = ref([]);
// 收入支出排行榜
export const homeRanks = ref([]);
// 分析概览x轴
export const xAxis = ref([]);
// 分析概览收入
export const incomeData = ref([]);
// 分析概览支出
export const expendData = ref([]);

export const onSearch = async () => {
	const result = await fetchHomeDatalist();
	if (result.code !== 200) {
		return;
	}
	chartData.value = [];

	// 顶部数据
	const homeCard = result.data?.homeCard;
	const income = homeCard?.income?.amount;
	const expend = homeCard?.expend?.amount;

	/* 支出百分比 */
	expendPercent.value = Number((expend / (income + expend)).toFixed(2)) * 100;

	// 收入和支出分析概览
	xAxis.value = result.data.homeOverview
		.filter(item => item.type === 1)
		.map(item => {
			const transactionDate = item.transactionDate;
			return `${dayjs(transactionDate).format('DD')} ${days[dayjs(transactionDate).day()]}`;
		});
	incomeData.value = result.data.homeOverview.filter(item => item.type === 1).map(item => item.amount);
	expendData.value = result.data.homeOverview.filter(item => item.type === -1).map(item => item.amount);

	// 收入和支出排行榜
	homeRanks.value = result.data.homeRanks.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, type: item.type };
	});

	homeCardFun(income, expend);
};

/**
 * 顶部卡片初始化数据
 * @param income 收入
 * @param expend 支出
 */
function homeCardFun(income, expend) {
	/* 收入金额 */
	let data = {
		icon: 'icon-park-outline:income',
		bgColor: '#effaff',
		color: '#67C23A',
		duration: 2200,
		name: $t('totalIncomeOfTheMonth'),
		value: income,
		percent: <p class='font-medium text-green-500'>{`+ ${income} ￥`}</p>,
		data: incomeData.value,
	};
	chartData.value.push(data);

	/* 支出金额 */
	data = {
		icon: 'icon-park-outline:expenses',
		bgColor: '#fff5f4',
		color: '#F56C6C',
		duration: 2200,
		name: $t('totalExpendituresOfTheMonth'),
		value: expend,
		percent: <p class='font-medium text-red-500'>{`- ${expend} ￥`}</p>,
		data: expendData.value,
	};
	chartData.value.push(data);

	/* 盈利金额 */
	const profit = incomeData.value.map((value, index) => {
		const number = value - expendData.value[index];
		return isNaN(number) ? 0 : number;
	});
	const profitValue = (income - expend).toFixed(2);
	data = {
		icon: 'hugeicons:profit',
		bgColor: '#fff5f4',
		color: '#409EFF',
		duration: 2200,
		name: $t('amountOfProfit'),
		value: Number(profitValue),
		percent: <p class='font-medium text-blue-500'>{`${profitValue} ￥`}</p>,
		data: profit,
	};
	chartData.value.push(data);
}
