import { useAclStore } from './acl'
import { useSettingsStore } from './settings'
import { useTabsStore } from './tabs'
import { getEnums, usersLogin, usersUserinfo, usersBindLogin } from '/@/api/index'
import { tokenName } from '/@/config'
import { getToken, removeToken, setToken } from '/@/utils/token'
import { isString } from '/@/utils/validate'
import { gp } from '/@vab/plugins/vab'

export const useUserStore = defineStore('user', {
  state: (): any => ({
    token: getToken() as string,
    username: '',
    avatar: '',
    enums: [],
    buttonPermissions: {}
  }),
  getters: {
    getToken: (state) => state.token,
    getUsername: (state) => state.username,
    getAvatar: (state) => state.avatar,
    buttonPermissions: (state) => state.buttonPermissions
  },
  actions: {
    /**
     * @description 设置token
     * @param {*} token
     */
    setToken(token: string) {
      this.token = token
      setToken(token)
    },
    /**
     * @description 设置enums
     * @param {*} enums
     */
    setEnums(enums: any) {
      this.enums = enums
    },
    /**
     * @description 设置用户名
     * @param {*} username
     */
    setUsername(username: string) {
      this.username = username
    },
    /**
     * @description 设置头像
     * @param {*} avatar
     */
    setAvatar(avatar: string) {
      this.avatar = avatar
    },
    setVirtualRoles() {
      const aclStore = useAclStore()
      aclStore.setFull(true)
      this.setUsername('admin(未开启登录拦截)')
      this.setAvatar('./static/svg/avatar.svg')
    },
    setButtonPermissions(buttonPermissions:any) {
      this.ButtonPermissions = buttonPermissions
    },
    /**
     * @description 设置token并发送提醒
     * @param {string} token 更新令牌
     * @param {string} tokenName 令牌名称
     */
    afterLogin(token: string, tokenName: string) {
      const settingsStore = useSettingsStore()
      if (token) {
        this.setToken(token)
        const hour = new Date().getHours()
        const thisTime = hour < 8 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 18 ? '下午好' : '晚上好'
        gp.$baseNotify(`欢迎登录${settingsStore.title}`, `${thisTime}！`)
      } else {
        const err = `登录接口异常，未正确返回${tokenName}...`
        gp.$baseMessage(err, 'error', 'hey')
        throw err
      }
    },
    async enumsTap() {
      let data:any = await getEnums()
      let enumsData:any = reactive<any>({})
      data.data.forEach((item: any) => { enumsData[item.code] = item.data });
      this.setEnums(enumsData)
    },
    async login(userInfo: any) {
      let data: any = await usersLogin({ "account": userInfo.username, "password": userInfo.password })
      this.afterLogin(data.data.token, tokenName)
    },
    async bindLoginTap(userInfo: any) {
      let data: any = await usersBindLogin({ "code": userInfo.code })
      this.afterLogin(data.data.token, tokenName)
    },
    async getUserInfo() {
      const { data: { name, base64Face, roles, permissions } } = await usersUserinfo()
      await this.enumsTap()
      if (
        (name && !isString(name)) || (base64Face && !isString(base64Face))
      ) {
        const err = 'getUserInfo核心接口异常，请检查返回JSON格式是否正确'
        gp.$baseMessage(err, 'error', 'hey')
        throw err
      } else {
        const aclStore = useAclStore()
        if (name) this.setUsername(name)
        if (permissions) this.setAvatar(permissions)
        aclStore.setRole(['Admin'])
        aclStore.setPermission(["read:system", "write:system", "delete:system"])
      }
    },
    /**
     * @description 退出登录
     */
    async logout() {
      // await logout()
      await this.resetAll()
      //@ts-ignore
      await location.reload(true)
    },
    /**
     * @description 重置token、roles、permission、router、tabsBar等
     */
    async resetAll() {
      const aclStore = useAclStore()
      const tabsStore = useTabsStore()
      await removeToken()
      this.setToken('')
      this.setUsername('')
      this.setAvatar('')
      await aclStore.setPermission([])
      await aclStore.setFull(false)
      await aclStore.setRole([])
      await tabsStore.delAllVisitedRoutes()
    },
  },
})
