import { defineStore } from 'pinia'

import { to } from 'await-to-js'
import store from '@/store'
import { getToken,getAccessToken, rpxoveToken, setToken,setAccessToken,setUserInfo,getUserInfoAuth,removeAccessToken,removeUserInfo } from '@/common/utils/auth'
import { login as loginApi, logout as logoutApi, getInfo as getUserInfo } from '@/api/user.js'


let timerInfo

export const useUserStore = defineStore('user', {
  
  state: () => ({
    token: getToken(),
    accessToken: getAccessToken(),
    passwordStatus:'0', // 0:不用修改密码 1:首次修改密码 2:密码过期
    name: '',
    nickname: '',
    userId: '',
    avatar: '',
    roles: [], // 用户角色编码集合 → 判断路由权限
    permissions: [],// 用户权限编码集合 → 判断按钮权限
    userInfo: getUserInfoAuth(),
    employessInfo: null,
  }),
  actions: {
    /**
     * 更新token
     * @param str
     */
     updateToken(str) {
      this.token = str
      setToken(str)
    },
    updateUserInfo(userInfo) {
      this.userInfo = userInfo
      setUserInfo(userInfo)
    },
    
    /**
     * 更新access_token
     * @param str
     */
     updateAccessToken(str) {
      this.accessToken = str
      setAccessToken(str)
    },
    /**
     * 登录
     * @param userInfo
     * @returns
     */
    async login(userInfo) {
      const tenantId = userInfo.tenantId.trim()
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      const [err, res] = await to(loginApi({ tenantId, username, password, code, uuid, wxOpenId: this.token }))
       console.log('err123', err)
      if (res) {
         console.log('res123', res)
         if(res.code=== 500){
          return Promise.reject(res)
         }
        // const { data } = res
        // setAccessToken(data.access_token)
        // this.updateAccessToken(data.access_token)
        this.getInfo()
        return Promise.resolve()
      }
      return Promise.reject(err)
    },
    
    /**
     * 获取用户信息
     * @param {boolean} flag 如果已登录，是否强制重新获取用户信息
     */
     async getInfo (flag = false) {
      // console.log('accessToken', accessToken.value)
      if (this.accessToken && !flag) {
        return Promise.resolve()
      }
      const [err, res] = await to(getUserInfo())
      if (res) {
        const data:any = res
        const user = data.user
        const profile = user.avatar || ''
        this.name = user.userName
        this.nickname = user.nickName
        this.avatar = profile
        this.userId = user.userId
        this.userInfo = user
        this.updateUserInfo(user)
        this.employessInfo = data.employessInfo
        this.passwordStatus = data.passwordStatus
        this.updateAccessToken(data.access_token)
        // pollingGetInfo(data.expires_in * 1000 * 60 - 1000 * 60)
        // pollingGetInfo(1000 * 10)
        return Promise.resolve()
      }
      return Promise.reject(err)
    },
    
    // 轮询获取用户信息
    pollingGetInfo(expired) {
      clearTimeout(timerInfo)
      timerInfo = setTimeout(() => {
        this.getInfo(true)
      }, expired)
    },
    
    // 注销
    async logout() {
      await logoutApi()
      // rpxoveAccessToken()
      this.updateAccessToken('')
      this.accessToken = ''
      this.name = ''
      this.nickname = ''
      this.avatar = ''
      this.userInfo = {}
      removeAccessToken()
      removeUserInfo()
      clearTimeout(timerInfo)
      
    },
    
    setAvatar(value) {
      this.avatar = value
    }
  }

})

export default useUserStore
// 非setup
export function useUserStoreHook() {
  return useUserStore(store)
}
