import { defineStore } from 'pinia'
import { asyncRoutes, basicRoutes } from '@/router/routes'
import { fetchPermission } from '@/api/auth/index'
import Layout from '@/layout/index.vue'
import modules from '@/utils/module.js'

/**
 * @description:
 * @param {*} route
 * @param {*} role
 * @return {*}
 */
function hasPermission(route, role) {
  // const routeRole = route.meta?.role ? route.meta.role : []
  // if (!role.length || !routeRole.length) {
  //   return false
  // }
  // return role.some((item) => routeRole.includes(item))
  return true
}

/**
 * @description: 过滤权限路由
 * @param {*} routes
 * @param {*} role
 * @return {*}
 */
function filterAsyncRoutes(routes = [], role) {
  const ret = []
  routes.forEach((route) => {
    if (hasPermission(route, role)) {
      const curRoute = {
        ...route,
        children: []
      }
      if (route.children && route.children.length) {
        curRoute.children = filterAsyncRoutes(route.children, role)
      } else {
        Reflect.deleteProperty(curRoute, 'children')
      }
      ret.push(curRoute)
    }
  })
  return ret
}

function dealRoutes(routes) {
  const res = []
  routes.forEach(item => {
    const tmp = { ...item }
    if (tmp.parentId === 0) {
      tmp.component = Layout
      if (tmp.children) {
        tmp.redirect = tmp.path === '/' ? `/${tmp.children[0].path}` : `${tmp.path}/${tmp.children[0].path}`
        tmp.children = dealRoutes(tmp.children)
      }
    } else {
      const sub_view = tmp.component.replace(/^\/*/g, '')
      const component = `../${sub_view}.vue`
      tmp.component = modules[component]
    }
    tmp.title = tmp.name
    tmp.meta = {
      ...tmp?.meta,
      title: tmp.name
    }
    res.push(tmp)
  })
  return res
}

function dealPermissions(permissionsList) {
  const res = permissionsList.map((tmp) => {
    return tmp.code
  })
  return res
}

export const usePermissionStore = defineStore('permission', {
  state() {
    return {
      accessRoutes: [],
      accessPermissions: []
    }
  },
  getters: {
    routes() {
      return basicRoutes.concat(this.accessRoutes)
    },
    permissionRoutes() {
      return this.accessRoutes
    },
    validatePermission() {
      return this.accessPermissions
    }
  },
  actions: {
    generateRoutesMock(role = []) {
      const accessRoutes = filterAsyncRoutes(asyncRoutes, role)
      this.accessRoutes = accessRoutes
      return accessRoutes
    },
    async generateRoutes(roleId) {
      try {
        const res = await fetchPermission({ roleId, clientId: 'tuoheng-hhz-admin' })
        // const res = await fetchPermission(3)
        if (res.code === 0) {
          const { opMenusList, permissionsList } = res.data
          const menus = dealRoutes(opMenusList)
          const permissions = dealPermissions(permissionsList)
          this.accessRoutes = menus
          this.accessPermissions = permissions
          return Promise.resolve(menus)
          // const accessRoutes = filterAsyncRoutes(asyncRoutes)
          // this.accessRoutes = accessRoutes
          // return Promise.resolve(accessRoutes)
        } else {
          return Promise.reject(res.message)
        }
      } catch (error) {
        console.error(error)
        return Promise.reject(error.message)
      }
    }
  }
})
