<template>
	<div class="container-fluid">
		<h1>vite-pinia 模板</h1>
		<h1>多语言：{{ t('tip.loading') }}</h1>
		<div class="row">
			<button class="btn btn-primary col-3 me-1" @click="handleI18n('en')">切换英文</button>
			<button class="btn btn-primary col-3 mr-2" @click="handleI18n('zh_cn')">切换中文</button>
			<button class="btn btn-success col-3" @click="fetchMockRequest()">发送请求(没有接口)</button>
		</div>

		<ul>
			<li v-for="(route, index) in routes" :key="index">
				<h5>{{ route.title }}</h5>
				<ul>
					<li v-for="child in route.children" :key="child.path">
						<RouterLink :to="child.path">
							{{ `${child.path}【${String(child.name)}】` }}
						</RouterLink>
					</li>
				</ul>
			</li>
		</ul>

		<Test />
		<RouterView />
	</div>
</template>

<script lang="ts" setup>
import Test from '@/views/test-tsx/index.tsx';
import { pageRoutes } from '@/router/module/pageRoutes';
import { userI18nStore } from '@/store/i18n.ts';
import { useI18n } from 'vue-i18n';
import { fetchTestApi } from '@/api/api-v1/test.ts';
import { onMounted, ref } from 'vue';

const i18nStore = userI18nStore();
const i18n = useI18n();
const { t } = useI18n();
const routes = ref<any>([]);

/**
 * * 切换多语言
 * @param value
 */
const handleI18n = (value: string) => {
	i18n.locale.value = value;
	i18n.mergeLocaleMessage(value, i18nStore.i18n[value]);
};

/**
 * * 模拟简单的请求--做测试用
 */
const fetchMockRequest = async () => {
	const response = await fetchTestApi();
	console.log(response);
};

/**
 * * 整理路由参数
 */
const neatenPageRoutes = () => {
	const tree = pageRoutes.reduce((last, route) => {
		const title = route.path.split('/')[1];
		const data = { name: route.path, path: route.path };

		if (last[title]) {
			last[title].children.push(data);
		} else {
			last[title] = { title, children: [data] };
		}
		return last;
	}, {});

	routes.value = Object.values(tree);
};

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

<style lang="scss" scoped></style>
