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
}

/**
 * @description:
 * @param {*} routes
 * @return {*}
 */
function dataArrayToRoutes(routes) {
  const res = []
  routes.forEach(item => {
    const tmp = { ...item }
    // // 如果有component配置
    // if (tmp.component) {
    //   // Layout引入
    //   if (tmp.component === 'Layout') {
    //     tmp.component = Layout
    //   } else {
    //     const sub_view = tmp.component.replace(/^\/*/g, '')
    //     const component = `../${sub_view}.vue`
    //     tmp.component = modules[component]
    //   }
    //   if (tmp.children) {
    //     tmp.children = dataArrayToRoutes(tmp.children)
    //   }
    // }
    // 如果pid为0
    if (tmp.pid === 0) {
      // Layout引入
      tmp.component = Layout
      if (tmp.children) {
        tmp.children = dataArrayToRoutes(tmp.children)
      }
    } else {
      const sub_view = tmp.component.replace(/^\/*/g, '')
      const component = `../${sub_view}.vue`
      tmp.component = modules[component]
    }
    tmp.name = tmp.title
    tmp.meta = {
      ...tmp.meta,
      title: tmp.meta.title || tmp.title
    }
    res.push(tmp)
  })
  return res
}

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: [],
      accessPermissionCodes: []
    }
  },
  getters: {
    routes() {
      return basicRoutes.concat(this.accessRoutes)
    },
    permissionRoutes() {
      return this.accessRoutes
    },
    validatePermission() {
      return this.accessPermissions
    },
    validatePermissionCode() {
      return this.accessPermissionCodes
    }
  },
  actions: {
    generateRoutesMock(role = []) {
      const accessRoutes = filterAsyncRoutes(asyncRoutes, role)
      this.accessRoutes = accessRoutes
      return accessRoutes
    },
    async generateRoutes(roleId) {
      try {
        const res = await fetchPermission({ roleId, clientId: 'tuoheng-pilot-admin' })
        // const res = await fetchPermission(3)
        if (res.code === 0) {
          const { opMenusList, permissionsList } = res.data
          const menus = dealRoutes(opMenusList)
          const permissionCodes = dealPermissions(permissionsList)
          this.accessRoutes = menus
          this.accessPermissions = permissionsList
          this.accessPermissionCodes = permissionCodes
          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)
      }
    }
  }
})
