import { defineStore } from "pinia";
import { AuthState } from "@/stores/interface";
import { getAuthButtonListApi, getAuthMenuListApi } from "@/api/modules/login";
import { getFlatMenuList, getShowMenuList, getAllBreadcrumbList } from "@/utils";
// import { other } from "@/api/interface";

export const useAuthStore = defineStore({
  id: "geeker-auth",
  state: (): AuthState => ({
    // 按钮权限列表
    authButtonList: {},
    // 菜单权限列表
    authMenuList: [],
    // 当前页面的 router name，用来做按钮权限筛选
    routeName: ""
  }),
  getters: {
    // 按钮权限列表
    authButtonListGet: state => state.authButtonList,
    // 菜单权限列表 ==> 这里的菜单没有经过任何处理
    authMenuListGet: state => state.authMenuList,
    // 菜单权限列表 ==> 左侧菜单栏渲染，需要剔除 isHide == true
    showMenuListGet: state => getShowMenuList(state.authMenuList),
    // 菜单权限列表 ==> 扁平化之后的一维数组菜单，主要用来添加动态路由
    flatMenuListGet: state => getFlatMenuList(state.authMenuList),
    // 递归处理后的所有面包屑导航列表
    breadcrumbListGet: state => getAllBreadcrumbList(state.authMenuList)
  },
  actions: {
    // Get AuthButtonList
    async getAuthButtonList() {
      await getAuthButtonListApi();
      // this.authButtonList = data;
    },
    // Get AuthMenuList
    async getAuthMenuList() {
      const { data } = await getAuthMenuListApi();
      // this.authMenuList = data;
      // let obj = [
      //   {
      //     children: [],
      //     id: "1804092280701833211",
      //     parentId: "1803729257055252481",
      //     path: "/Administration/addition",
      //     name: "Administrationadd",
      //     component: "/Administration/addition",
      //     meta: {
      //       activeMenu: "/Administration/index",
      //       icon: "FolderRemove",
      //       title: "电价模板新增",
      //       isLink: "",
      //       isHide: true,
      //       isFull: false,
      //       isAffix: true,
      //       isKeepAlive: true
      //     },
      //     menuType: "F"
      //   },
      //   {
      //     children: [],
      //     id: "18040922807018332111",
      //     parentId: "1803729344133197826",
      //     path: "/powerStation/addition",
      //     name: "powerStationadd",
      //     component: "/powerStation/addition",
      //     meta: {
      //       activeMenu: "/powerStation/index",
      //       icon: "FolderRemove",
      //       title: "电站新增",
      //       isLink: "",
      //       isHide: true,
      //       isFull: false,
      //       isAffix: true,
      //       isKeepAlive: true
      //     },
      //     menuType: "F"
      //   },
      //   {
      //     children: [],
      //     id: "18037320810298040341",
      //     parentId: "1803731342756802561",
      //     path: "/toconfigurevalue/index",
      //     name: "toconfigurevalue",
      //     component: "/toconfigurevalue/index",
      //     meta: {
      //       activeMenu: "",
      //       icon: "Operation",
      //       title: "通信管理",
      //       isLink: "",
      //       isHide: false,
      //       isFull: false,
      //       isAffix: true,
      //       isKeepAlive: true
      //     },
      //     menuType: "C"
      //   }
      // ];
      // for (let index = 0; index < obj.length; index++) {
      //   data.push(obj[index]);
      // }
      this.authMenuList = buildTree(data);
      console.log(this.authMenuList);

      let authButtondata: { [key: string]: string[] } = {};

      for (let index = 0; index < this.authMenuList.length; index++) {
        for (let indexs = 0; indexs < this.authMenuList[index].children.length; indexs++) {
          for (let a = 0; a < this.authMenuList[index].children[indexs].children.length; a++) {
            let names = this.authMenuList[index].children[indexs].name;
            if (this.authMenuList[index].children[indexs].children[a].menuType == "F") {
              let name = this.authMenuList[index].children[indexs].children[a].name;

              // 检查是否已经存在对应的键，如果不存在则初始化为空数组
              if (!authButtondata[names]) {
                authButtondata[names] = [];
              }

              // 将 title 添加到对应键的数组中
              authButtondata[names].push(name);
            }
          }
        }
      }
      this.authButtonList = authButtondata;
    },
    // Set RouteName
    async setRouteName(name: string) {
      this.routeName = name;
    }
  }
});

const buildTree = (data: Menu.MenuOptions[]) => {
  const tree: Menu.MenuOptions[] = [];
  const map: { [key: string]: Menu.MenuOptions } = {};

  // 创建一个map以便快速找到item
  data.forEach((item: Menu.MenuOptions) => {
    map[item.id] = { ...item, children: [] };
  });

  data.forEach((item: { parentId: string; id: string | number }) => {
    if (item.parentId === "0") {
      // 根节点，假设根节点的 pId 是空字符串或者其他标识
      tree.push(map[item.id]);
    } else {
      // 子节点
      if (map[item.parentId]) {
        map[item.parentId].children?.push(map[item.id]);
      }
    }
  });

  return tree;
};
