import auth from '@/plugins/auth'
import router, { constantRoutes, dynamicRoutes } from '@/router'
import { getMenu } from '@/api/menu'
import Layout from '@/layout/index'
import ParentView from '@/components/ParentView'
import InnerLink from '@/layout/components/InnerLink'

// 匹配views里面所有的.vue文件
const modules = import.meta.glob('./../../views/**/*.vue')

const usePermissionStore = defineStore(
  'permission',
  {
    state: () => ({
      routes: [],
      addRoutes: [],
      defaultRoutes: [],
      topbarRouters: [],
      sidebarRouters: [],
      powerList: []
    }),
    actions: {
      setRoutes(routes) {
        this.addRoutes = routes
        this.routes = constantRoutes.concat(routes)
      },
      setDefaultRoutes(routes) {
        this.defaultRoutes = constantRoutes.concat(routes)
      },
      setTopbarRoutes(routes) {
        this.topbarRouters = routes
      },
      setSidebarRouters(routes) {
        this.sidebarRouters = routes
      },
      generateRoutes(roles) {
        return new Promise(resolve => {
          // 向后端请求路由数据
          getMenu().then(res => {
            let menuList = [
              {
                "rank": 1,
                "path": "/index",
                "hidden": false,
                "redirect": "noRedirect",
                "component": "Layout",
                "children": [
                  {
                    "path": '',
                    "component": "account/index",
                    "name": 'Index',
                    "meta": {
                      "titleCode": 'menu.menu1',
                      "icon": "menu1",
                      "iconActive": "menu1_1",
                      "noCache": false,
                      "link": null,
                      "activeMenu": '/index'
                    }
                  },
                  {
                    "path": '/tradeList',
                    "component": "account/tradeList",
                    "name": 'TradeList',
                    "hidden": true,
                    "meta": {
                      "title": "交易记录",
                      "noCache": false,
                      "link": null,
                      "activeMenu": '/index'
                    }
                  },
                  {
                    "path": '/openAccount',
                    "component": "account/openAccount",
                    "name": 'OpenAccount',
                    "hidden": true,
                    "meta": {
                      "title": "新建账户",
                      "noCache": false,
                      "link": null,
                      "activeMenu": '/index'
                    }
                  },
                  {
                    "path": '/account/applyMt/:id',
                    "component": "account/applyMt",
                    "name": 'ApplyMt',
                    "hidden": true,
                    "meta": {
                      "title": "创建新账户",
                      "noCache": false,
                      "link": null,
                      "activeMenu": '/index'
                    }
                  }
                ]
              }
            ]
            let keyTmp = []
            res.data.menuList.filter(v => v.children.length).map(i => i.children.map(ii => keyTmp.push(ii.route_key)))
            this.powerList = keyTmp
            if (res.data.menuList && res.data.menuList.length) {
              for (let index = 0; index < res.data.menuList.length; index++) {
                const module = res.data.menuList[index];
                if (module.route_key == 'capital') {
                  menuList.push({
                    "rank": 2,
                    "path": "/capital",
                    "hidden": false,
                    "redirect": "noRedirect",
                    "component": "Layout",
                    "children": [
                      {
                        "path": "",
                        "name": "Capital",
                        "component": "capital/index",
                        "meta": {
                          "titleCode": 'menu.menu2',
                          "icon": "menu2",
                          "iconActive": "menu2_1",
                          "noCache": false,
                          "link": null,
                          "activeMenu": '/capital'
                        }
                      },
                      {
                        "path": ":type",
                        "hidden": true,
                        "name": "CapitalType",
                        "component": "capital/index",
                        "meta": {
                          "title": "",
                          "noCache": false,
                          "link": null,
                          "activeMenu": '/capital'
                        }
                      },
                      {
                        "path": ":type/:actId",
                        "hidden": true,
                        "name": "CapitalTypeAct",
                        "component": "capital/index",
                        "meta": {
                          "title": "活动入金",
                          "noCache": false,
                          "link": null,
                          "activeMenu": '/capital'
                        }
                      },
                      {
                        "path": ":type/:serverId/:mtLogin",
                        "hidden": true,
                        "name": "CapitalTypeMt",
                        "component": "capital/index",
                        "meta": {
                          "title": "mt资金",
                          "noCache": false,
                          "link": null,
                          "activeMenu": '/capital'
                        }
                      }
                    ]
                  })
                } else if (module.route_key == 'partner') {
                  menuList.push({
                    "rank": 3,
                    "path": "/partner",
                    "hidden": false,
                    "redirect": "noRedirect",
                    "component": "Layout",
                    "children": [
                      {
                        "path": "",
                        "name": "Partner",
                        "component": "partner/index",
                        "meta": {
                            "titleCode": 'menu.menu3',
                            "icon": "menu3",
                          "iconActive": "menu3_1",
                            "noCache": false,
                            "link": null,
                            "activeMenu": '/partner'
                        }
                      }
                    ]
                  })
                } else if (module.route_key == 'download') {
                  menuList.push({
                    "rank": 8,
                    "path": "/download",
                    "hidden": false,
                    "redirect": "noRedirect",
                    "component": "Layout",
                    "children": [{
                      "path": "",
                      "name": "Download",
                      "component": "download/index",
                      "meta": {
                          "titleCode": 'menu.menu4',
                          "icon": "menu4",
                            "iconActive": "menu4_1",
                          "noCache": false,
                          "link": null,
                          "activeMenu": '/download'
                      }
                      }]
                  })
                } else if (module.route_key == 'pamm') {
                  menuList.push({
                    "rank": 7,
                    "path": "/pamm",
                    "hidden": false,
                    "redirect": "noRedirect",
                    "component": "Layout",
                    "children": [{
                      "path": "",              
                      "name": "PAMM",
                      "component": "pamm/index",
                      "meta": {
                        "titleCode": 'menu.menu5',
                        "icon": "menu5",
                        "iconActive": "menu5_1",
                        "noCache": false,
                        "link": null,
                        "activeMenu": '/pamm'
                      }
                    }]
                  })
                } else if (module.route_key == 'tools') {
                  menuList.push({
                    "rank": 5,
                    "path": "/tools",
                    "hidden": false,
                    "redirect": "noRedirect",
                    "component": "Layout",
                    "children": [{
                        "path": "",
                        "name": "Tools",
                        "component": "tools/index",
                        "meta": {
                            "titleCode": 'menu.menu6',
                            "icon": "menu6",
                            "iconActive": "menu6_1",
                            "noCache": false,
                            "link": null,
                            "activeMenu": '/tools'
                        }
                      },
                      {
                        "path": 'toolsDetail/:id',
                        "component": "tools/detail",
                        "name": 'ToolsDetail',
                        "hidden": true,
                        "meta": {
                          "title": "报告详情",
                          "noCache": false,
                          "link": null,
                          "activeMenu": '/tools'
                        }
                      }
                    ]
                  })
                } else if (module.route_key == 'fts') {
                  menuList.push({
                    "rank": 6,
                    "path": "/fts",
                    "hidden": false,
                    "redirect": "noRedirect",
                    "component": "Layout",
                    "children": [{
                      "name": "Fts",
                      "path": "",
                      "component": "fts/index",
                      "meta": {
                          "titleCode": 'menu.menu7',
                          "icon": "menu7",
                          "iconActive": "menu7_1",
                          "noCache": false,
                          "link": null,
                          "activeMenu": '/fts'
                      }
                    }]
                  })
                } else if (module.route_key == 'news') {
                  menuList.push({
                    "rank": 9,
                    "path": "/news",
                    "hidden": false,
                    "redirect": "noRedirect",
                    "component": "Layout",
                    "children": [{
                        "name": "News",
                        "path": "",
                        "component": "news/index",
                        "meta": {
                            "titleCode": 'menu.menu8',
                            "icon": "menu8",
                            "iconActive": "menu8_1",
                            "noCache": false,
                            "link": null,
                            "activeMenu": '/news'
                        }
                      },
                      {
                        "path": 'newsDetail/:id',
                        "component": "news/detail",
                        "name": 'NewsDetail',
                        "hidden": true,
                        "meta": {
                          "title": "新闻详情",
                          "noCache": false,
                          "link": null,
                          "activeMenu": '/news'
                        }
                      }
                    ]
                  })
                } else if (module.route_key == 'activity') {
                  menuList.push({
                    "rank": 4,
                    "path": "/activity",
                    "hidden": false,
                    "redirect": "noRedirect",
                    "component": "Layout",
                    "children": [{
                        "name": "Activity",
                        "path": "",
                        "component": "activity/index",
                        "meta": {
                            "titleCode": 'menu.menu9',
                            "icon": "menu9",
                            "iconActive": "menu9_1",
                            "noCache": false,
                            "link": null,
                            "activeMenu": '/activity'
                        }
                      },
                      {
                        "path": 'actDetail/:type/:id',
                        "component": "activity/detail",
                        "name": 'ActivityDetail',
                        "hidden": true,
                        "meta": {
                          "title": "活动详情",
                          "noCache": false,
                          "link": null,
                          "activeMenu": '/activity'
                        }
                      },
                      {
                        "path": '/shop',
                        "component": "activity/shop/index",
                        "name": 'Shop',
                        "hidden": true,
                        "meta": {
                          "title": "积分商城",
                          "noCache": false,
                          "link": null,
                          "activeMenu": '/activity'
                        }
                      },
                      {
                        "path": '/shop/goods/:id',
                        "component": "activity/shop/goods",
                        "name": 'Goods',
                        "hidden": true,
                        "meta": {
                          "title": "积分商品",
                          "noCache": false,
                          "link": null,
                          "activeMenu": '/activity'
                        }
                      },
                      {
                        "path": '/shop/myOrder',
                        "component": "activity/shop/myOrder",
                        "name": 'MyOrder',
                        "hidden": true,
                        "meta": {
                          "title": "我的礼品",
                          "noCache": false,
                          "link": null,
                          "activeMenu": '/activity'
                        }
                      },
                      {
                        "path": '/shop/pointRecord',
                        "component": "activity/shop/pointRecord",
                        "name": 'PointRecord',
                        "hidden": true,
                        "meta": {
                          "title": "积分账单",
                          "noCache": false,
                          "link": null,
                          "activeMenu": '/activity'
                        }
                      }
                    ]
                  })
                } else if (module.route_key == 'contact') {
                  menuList.push({
                    "rank": 10,
                    "path": "/contact",
                    "hidden": false,
                    "redirect": "noRedirect",
                    "component": "Layout",
                    "children": [{
                      "name": "Contact",
                      "path": "",
                      "component": "contact/index",
                      "meta": {
                          "titleCode": 'menu.menu10',
                          "icon": "menu10",
                          "iconActive": "menu10_1",
                          "noCache": false,
                          "link": null,
                          "activeMenu": '/contact'
                      }
                    }]
                  })
                }
              }
            }
            menuList.sort((a, b) => a.rank - b.rank)
            const sdata = JSON.parse(JSON.stringify(menuList))
            const rdata = JSON.parse(JSON.stringify(menuList))
            const defaultData = JSON.parse(JSON.stringify(menuList))
            const sidebarRoutes = filterAsyncRouter(sdata)
            const rewriteRoutes = filterAsyncRouter(rdata, false, true)
            const defaultRoutes = filterAsyncRouter(defaultData)
            const asyncRoutes = filterDynamicRoutes(dynamicRoutes)
            asyncRoutes.forEach(route => { router.addRoute(route) })
            this.setRoutes(rewriteRoutes)
            this.setSidebarRouters(constantRoutes.concat(sidebarRoutes))
            this.setDefaultRoutes(sidebarRoutes)
            this.setTopbarRoutes(defaultRoutes)
            resolve(rewriteRoutes)
          })
        })
      }
    }
  })

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
  return asyncRouterMap.filter(route => {
    if (type && route.children) {
      route.children = filterChildren(route.children)
    }
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else if (route.component === 'ParentView') {
        route.component = ParentView
      } else if (route.component === 'InnerLink') {
        route.component = InnerLink
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

function filterChildren(childrenMap, lastRouter = false) {
  var children = []
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView' && !lastRouter) {
        el.children.forEach(c => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + '/' + el.path
      if (el.children && el.children.length) {
        children = children.concat(filterChildren(el.children, el))
        return
      }
    }
    children = children.concat(el)
  })
  return children
}

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes) {
  const res = []
  routes.forEach(route => {
    if (route.permissions) {
      if (auth.hasPermiOr(route.permissions)) {
        res.push(route)
      }
    } else if (route.roles) {
      if (auth.hasRoleOr(route.roles)) {
        res.push(route)
      }
    }
  })
  return res
}

export const loadView = (view) => {
  let res;
  for (const path in modules) {
    const dir = path.split('views/')[1].split('.vue')[0];
    if (dir === view) {
      res = () => modules[path]();
    }
  }
  return res;
}

export default usePermissionStore
