/*
 * @Author       : ldc 951052117@qq.com
 * @Date         : 2023-06-12 15:34:19
 * @LastEditors  : ldc 951052117@qq.com
 * @LastEditTime : 2024-01-08 14:42:07
 * @Description  : 登录退出 存储用户信息路由权限
 */

import { defineStore } from 'pinia'
import { asyncRoutes, routes } from '@/router/routes.js'
import { loginApi } from '@/utils/api'
import { setToken, removeToken } from '@/utils/auth'
import { filterAsyncRoutes, editRedirect } from '@/router/index'
import router from '../router'
export const useUserStore = defineStore('user', {
  state: () => ({
    registerRouteFresh: true,
    asyncRoutes: [], //处理后异步路由表
    userInfo: {}, //用户信息
    permissions: [], //权限路由list
    routerHistory: sessionStorage.getItem('routerHistory') ? JSON.parse(sessionStorage.getItem('routerHistory')) : [], //路由记录
    nowRouter: sessionStorage.getItem('nowRouter'),
  }),
  actions: {
    async login(params) {
      try {
        const res = await loginApi.login(params)
        setToken(res.token)
         await this.updateUserInfo()
        ElMessage.success({ message: '登录成功' })
        const permissions = [...this.userInfo.permissions]
        // , 'WorkOrderError', 'workOrderDestroy', 'workOrderReserver'
        sessionStorage.setItem('permissions', $utils.encryptByDES.CBC(JSON.stringify(permissions)))
        this.updateAsyncRoutes()
        this.updateFresh(true)
        router.push('/home')
      } catch (error) {
        console.log(error)
        throw new Error(error)
      }
    },
    async logOut() {
      // await loginApi.loginOut()
      removeToken()
      router.push('/')
    },
    async updateUserInfo() {
      const userInfo = await loginApi.getUserInfo()
      sessionStorage.setItem('userInfo', $utils.encryptByDES.CBC(JSON.stringify(userInfo)))
      this.userInfo = userInfo
    },
    updateFresh(flag) {
      this.registerRouteFresh = flag
    },
    updateAsyncRoutes() {
      // 权限时处理异步路由
      let sessionPermissions = JSON.parse($utils.decryptByDES.CBC(sessionStorage.getItem('permissions')))
      // let result = filterAsyncRoutes(asyncRoutes, sessionPermissions)
      let result = asyncRoutes

      result = editRedirect(result)
      // console.log(result, 'result')
      result.unshift({
        path: '/home',
        name: 'home',
        redirect: result[0].path,
        component: () => import('@/layout/Layout.vue'),
        children: [result[0]],
      })
      this.asyncRoutes = result
      sessionStorage.setItem('asyncRoutes', $utils.encryptByDES.CBC(JSON.stringify(result)))
    },
    setRouterHistory(routerHistory) {
      this.routerHistory = routerHistory
      sessionStorage.setItem('routerHistory', JSON.stringify(routerHistory))
    },
    // 清除路由历史
    cleanRouterHistory() {
      this.routerHistory = []
      sessionStorage.removeItem('routerHistory')
    },
    // 设置当前路由
    setNowRouter(nowRouter) {
      this.nowRouter = nowRouter
      sessionStorage.setItem('nowRouter', nowRouter)
    },
    // 清除当前路由
    cleanNowRouter() {
      this.nowRouter = undefined
      sessionStorage.removeItem('nowRouter')
    },
  },
})
