
// import { getList } from '/@/api/index'
import { authentication, rolesControl } from '/@/config'
import { myMenu } from '/@/api/index'
import { constantRoutes, resetRouter } from '/@/router'
import { asyncRoutes } from '/@/router/menu'
import { convertRouter, filterRoutes } from '/@/utils/routes'
import { useUserStore } from '/@/store/modules/user'
import { isArray } from '/@/utils/validate'
import Layout from '/@vab/layouts/index.vue'

const filterHidden = (data: any) => {
  return data.reduce((acc: any, item: any) => {
    if (item.meta && item.meta.hidden) return acc
    const newItem = { ...item }
    if (item.children && item.children.length > 0) newItem.children = filterHidden(item.children)
    return [...acc, newItem]
  }, [])
}

const filterBreadcrumb = (data: any) => {
  return data.reduce((acc: any, item: any) => {
    const newItem = { ...item }
    if (item.children && item.children.length > 0) newItem.children = filterBreadcrumb(item.children)
    return [...acc, newItem]
  }, [])
}

export const useRoutesStore = defineStore('routes', {
  state: (): RoutesModuleType => ({
    tab: {
      data: undefined,
    },
    tabMenu: undefined,
    activeMenu: {
      data: undefined,
    },
    routes: [],
    allRoutes: [],
    breadcrumbRoutes: [],
  }),
  getters: {
    getTab: (state) => state.tab,
    getTabMenu: (state) => (state.tab.data ? state.routes.find((route) => route.name === state.tab.data) : { meta: { title: '' } }),
    getActiveMenu: (state) => state.activeMenu,
    getRoutes: (state) => state.routes.filter((_route) => _route.meta && _route.meta.hidden !== true),
    getAllRoutes: (state) => state.allRoutes.filter((_route) => _route.meta && _route.meta.hidden !== true),
    getBreadcrumbRoutes: (state) => state.breadcrumbRoutes.filter((_route) => _route.meta && _route.meta.hidden !== true),
    getPartialRoutes: (state) =>
      state.tab.data
        ? state.routes.find((route) => route.name === state.tab.data) &&
          state.routes.find((route) => route.name === state.tab.data).children
        : [],
  },
  actions: {
    /**
     * @description 多模式设置路由
     * @param mode
     * @returns
     */
    async setRoutes(mode = 'none') {
      // console.log(storeToRefs(useUserStore()), 'asdasdas')
      // 默认前端路由
      console.log(asyncRoutes, 'asyncRoutes')
      let routes = convertRouter([...asyncRoutes])
      const control = mode === 'visit' ? false : rolesControl
      // if (authentication === 'all') {
        // const data = await myMenu({})
        // // console.log(data)
        // let noColumnList = ['index']
        // let noClosableList = ['index']
        // let myMenuData = data.data
        // function createMenu(item:any) {
        //   const { buttonPermissions } = storeToRefs(useUserStore())
        //   let obj = buttonPermissions
        //   if (item.menuType == 2 && item.items && item  .items.length) {
        //     obj[item.name] = {
        //       list: item.items.map((list:any) => { return list.name }),
        //       obj: item.items.map((list:any) => { return list })
        //     }
        //   } else {
        //     obj[item.name] = { list: [], obj: [] }
        //   }
        //   useUserStore().setButtonPermissions(obj)
        //   return {
        //     path: `/${item.name}`, 
        //     name: item.name,
        //     component: item.route,
        //     Sequence: item.sequence || 0,
        //     meta: {
        //       title: item.title || '', 
        //       icon: item.icon || '',
        //       // breadcrumbHidden: item.name == '/' ? false : true, 
        //       // guard: item.permission || item.permission == '0' ? item.permission.split(',') : ['0'],  
        //       // badge: '0',
        //       // dot: item.dot || '',
        //       // hidden: item.visible ? false : true,
        //       noColumn: noColumnList.includes(item.name) ? true : false,
        //       noClosable: noClosableList.includes(item.name) ? true : false,
        //     },
        //     children: item.items && item.menuType < 2 ? item.items.map(createMenu).sort((a:any, b:any) => a.sequence - b.sequence) : []
        //   }
        // }
        // let list = myMenuData.map(createMenu).sort((a:any, b:any) => a.sequence - b.sequence)

        // if (isArray(list) && list.length) {
        //   if (list[list.length - 1].path !== '*') {
        //     list.push({ path: '/:pathMatch(.*)*', redirect: '/404', name: 'NotFound', meta: { title: '404', hidden: true } })
        //   }
        // }
        // routes = convertRouter(list)
        // routes = list
      // }
      // 根据权限和rolesControl过滤路由
      const accessRoutes = filterRoutes([...constantRoutes, ...routes], control)
      // 设置菜单所需路由
      this.routes = filterHidden(accessRoutes)
      this.allRoutes = accessRoutes
      this.breadcrumbRoutes = filterBreadcrumb(accessRoutes)
      // 根据可访问路由重置Vue Router
      await resetRouter(accessRoutes)
    },
    changeMenuMeta(options: any) {
      function handleRoutes(routes: any[]) {
        return routes.map((route) => {
          if (route.name === options.name) Object.assign(route.meta, options.meta)
          if (route.children && route.children.length > 0) route.children = handleRoutes(route.children)
          return route
        })
      }

      this.routes = handleRoutes(this.routes)
    },
    /**
     * @description 修改 activeName
     * @param activeMenu 当前激活菜单
     */
    changeActiveMenu(activeMenu: string) {
      this.activeMenu.data = activeMenu
    },
  },
})
