// stores/counter.js
import {
	defineStore
} from 'pinia';
import * as menusApi from '@/http/api/menu.js'
import pagesJSON from '@/pages.json'
const allPages = pagesJSON.pages.concat(pagesJSON.subPackages.reduce((prve, cur) => {
	const childPages = cur.pages.map(v => {
		return {
			...v,
			allPath: cur.root + '/' + v.path
		}
	})
	prve.push(...childPages)
	return prve
}, []))

function flattenNestedChildren(data) {
	const result = [];

	function traverse(nodeArray) {
		if (!Array.isArray(nodeArray)) return;

		for (const node of nodeArray) {
			// 复制当前节点（不含children）
			const flatNode = {
				...node
			};
			delete flatNode.children;
			result.push(flatNode);

			// 递归处理子节点
			traverse(node.children);
		}
	}

	traverse(data);
	return result;
}

export const useMenusStore = defineStore('menus', {
	state: () => {
		return {
			originMenus: [],
			menuList: [],
			allPages: allPages, //小程序全部页面
			adminPages: [] //后台返回的全部页面
		};
	},
	actions: {
		async getMenus() {
			const data = await menusApi.getMenus()
			this.originMenus = data;
			const arr = flattenNestedChildren(data).filter(v => {
				return v.miniPath
			})
			this.adminPages = arr;
			this.menuList = this.allPages.filter(v => {
				const findItem = arr.find(item => item.miniPath == v.pageId || item.miniPath
					.replace(/^\/+|\/+$/g, '') == v.allPath)

				if (v.title == '经营工具') {
					console.log('经营工具===', findItem);
				}
				return findItem
			})



			return this.originMenus
		}
	},
	unistorage: true, // 开启后对 state 的数据读写都将持久化
});