<script lang="ts" setup>
import Analyse from '@/components/Analyse/index.vue';
import { onMounted, reactive, ref } from 'vue';
import { $t } from '@/plugins/i18n';
import LoadingSvg from '@/assets/svg/loading.svg';
import { useAdminUserStore } from '@/store/system/adminUser';
import dayjs from 'dayjs';
import { currentMouth, days } from '@/enums/dateEnums';
import { fetchGetExpendOrIncome } from '@/api/v1/financial/user/billUser';
import { fetchGetBillList } from '@/api/v1/financial/admin/bill';

const title = {
	analyse: $t('revenueAnalysis'),
	category: $t('incomeBrackets'),
	table: $t('dataStatistics'),
	top: $t('rankingList'),
};

const adminUserStore = useAdminUserStore();
const loading = ref(false);
// 用户信息列表
const userDataList = ref();

// 分析概览
const analyseXAxis = ref([]);
const analyseData = ref([]);
// 分类数据
const categoryList = ref([]);
// 排行榜数据
const topList = ref([]);
const dataList = ref([]);
// 总金额
const count = ref(0);

// 查询表单
const form = reactive({
	userId: undefined,
	type: 1,
	startDate: dayjs(currentMouth[0]).format('YYYY-MM-DD'),
	endDate: dayjs(currentMouth[1]).format('YYYY-MM-DD'),
	pagination: {
		pageSize: 10,
		currentPage: 1,
		layout: 'prev, pager, next',
		total: 1,
		align: 'center',
		hideOnSinglePage: false,
	},
	loading: false,
});

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

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

	// 分析概览
	analyseData.value = [];
	analyseXAxis.value = [];
	result.data.chartList.forEach(item => {
		const transactionDate = item.transactionDate;
		const date = `${dayjs(transactionDate).format('MM-DD')} ${days[dayjs(transactionDate).day()]}`;
		// 计算总和
		count.value += Number(item.amount);

		// 设置坐标数据
		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 };
	});
};

/* 查询表格数据 */
async function onTableSearch() {
	form.loading = true;

	// 获取账单数据
	const result = await fetchGetBillList({ ...form, ...form.pagination });
	dataList.value = result.data.list;
	form.pagination.currentPage = result.data.pageNo;
	form.pagination.pageSize = result.data.pageSize;
	form.pagination.total = result.data.total;

	form.loading = false;
}

/* 修改分页 */
async function onCurrentChange(page: number) {
	form.pagination.currentPage = page;
	await onSearch();
}

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

/** 查询用户数据 */
const onSearchUserinfo = async (keyword: string) => {
	loading.value = true;
	userDataList.value = await adminUserStore.queryUser({ keyword });
	loading.value = false;
};

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

<template>
	<Analyse
		:analyse-data="analyseData"
		:analyseXAxis="analyseXAxis"
		:category-data="categoryList"
		:color="['#41b6ff', '#67C23A']"
		:count="count"
		:data-list="dataList"
		:date="[form.startDate, form.endDate]"
		:financialType="form.type"
		:form="form"
		:on-current-change="onCurrentChange"
		:title="title"
		:top-data="topList"
		@emit-date-range="onChangeDateRange"
	>
		<template #formBefore>
			<el-select
				v-model="form.userId"
				:loading="loading"
				:placeholder="$t('user')"
				:remote-method="onSearchUserinfo"
				class="!w-[180px]"
				clearable
				filterable
				remote
				remote-show-suffix
				@change="onSearch"
			>
				<el-option v-for="item in userDataList" :key="item.id" :label="item.username" :value="item.id" />
				<template #loading>
					<el-icon class="is-loading">
						<LoadingSvg />
					</el-icon>
				</template>
			</el-select>
		</template>
	</Analyse>
</template>
