<template>
	<div v-loading.fullscreen.lock="fullscreenLoading">
		<div class="tool-list">
			<ToolList :list="categoryList" @tool-selected="scrollToTool"></ToolList>
		</div>
		<div class="line">
		</div>
		<div class="toolbar" v-for="tool in processedToolsGroup" :key="tool.categoryId">
			<Toolbar :tool="tool" :id="`tool-${tool.categoryName}`" :category-slug="tool.categorySlug || ''"></Toolbar>
		</div>
	</div>
</template>

<script>
import Toolbar from "../components/Toolbar.vue";
import ToolList from "../components/ToolList.vue";

export default {
	components: {ToolList, Toolbar},
	data() {
		return {
			fullscreenLoading: false,
			categoryList: [],
			toolsGroup: [],
			processedToolsGroup: [] // 处理后的工具列表
		}
	},
	computed: {
		// 计算属性，用于获取处理后的工具列表
		getProcessedTools() {
			this.processData();
			return this.processedToolsGroup;
		}
	},
	methods: {
		scrollToTool(toolName) {
			const target = document.getElementById(`tool-${toolName}`)
			if (target) {
				target.scrollIntoView({
					behavior: 'smooth',
					block: 'start'
				})
			}
		},
		// 获取分类列表
		async getCategoryAsyncData() {
			const {data: res} = await this.$api.tool.getCategoryList();
			const {code, data} = res;
			if (code === 0 && data.list) {
				this.categoryList = data.list;
			}
		},
		// 获取分类分组的工具列表
		async getToolsGroupAsyncData() {
			const {data: res} = await this.$api.tool.getToolByCategory({limit: 8});
			const {code, data} = res;
			if (code === 0 && data.list) {
				this.toolsGroup = data.list;
				// 数据获取完成后处理数据
				this.processData();
			}
		},
		async onLoad() {
			this.fullscreenLoading = true;
			await this.getCategoryAsyncData();
			await this.getToolsGroupAsyncData();
			this.fullscreenLoading = false;
		},
		// 处理数据的核心逻辑
		processData() {
			// 确保工具列表已加载
			if (!this.toolsGroup.length) {
				return;
			}

			// 1. 分离一级分类（parentId === 0）和二级分类（parentId !== 0）
			const mainTools = this.toolsGroup.filter(tool => tool.parentId === 0);
			const subTools = this.toolsGroup.filter(tool => tool.parentId !== 0);

			// 2. 创建一个映射，方便快速查找一级分类
			const mainToolMap = {};
			mainTools.forEach(tool => {
				// 去除tools属性，添加tagList属性
				mainToolMap[tool.categoryId] = {
					...tool,
					tagList: [] // 初始化空的tagList
				};
			});

			// 3. 将二级分类添加到对应的一级分类的tagList中
			subTools.forEach(subTool => {
				const parentTool = mainToolMap[subTool.parentId];
				if (parentTool) {
					parentTool.tagList.push(subTool);
				}
			});

			// 4. 获取处理后的工具列表（值的数组）
			this.processedToolsGroup = Object.values(mainToolMap);
		}
	},
	created() {
		this.onLoad();
	}
}
</script>

<style scoped lang="scss">
.tool-list {
	margin: 60px 0;
}
</style>
