import UserService from '@/api/user'
import { setStoreState } from '../../utils'
import Store from '@/store'
import router from '@/router'
import message from '@/utils/message'
/**
 * @description 所有跟用户相关的内容
 * @return status 返回状态 err_code：1，逻辑正确，err_code：0，发生错误。
 */

const userActions = {
  // 刷新令牌
  refreshToken() {
    return UserService.refreshToken({
      // eslint-disable-next-line
      refresh_token: Store.state.user.token.refresh_token
    }).then(res => {
      // token过期时间
      const expireTime = res.data.expires_in * 1000 + new Date().getTime()
      setStoreState('user', 'token', { ...res.data, expireTime })
    })
  },

  // 获取用户信息
  getUserDetail() {
    return UserService.getUserDetail().then(res => {
      setStoreState('user', 'userDetail', res.data.data)
    })
  },

  setUserSignout() {
    //清理用户数据
    const loginUser = {}
    setStoreState('user', 'userDetail', loginUser)
    //清除token
    const token = {}
    const expireTime = 1 + new Date().getTime()
    setStoreState('user', 'token', { ...token, expireTime })
    //清除菜单权限
    setStoreState('user', 'menuList', [])
  },

  userLogin(params: { Account: string; Password: string }) {
    //TODO: 实现用户登录
    UserService.login(params).then(res => {
      // const auths = getStoreGetter<UserGetter>('user', 'getUserAllAuth')
      // console.log(70, auths, ResultType.EmptyArray)
      // if (auths != ResultType.EmptyArray) {
      // Object.assign(menus, ...auths)
      // }
      if (res.data.Code == 1) {
        message.successMsg('登录成功')
        setStoreState('user', 'loginUserInfo', res.data.Data)
        setStoreState('user', 'menuList', res.data.Data.MenuList)
        const token = {
          token_type: 'login_auth',
          access_token: res.data.Data.Token
        }
        const expireTime = 60 * 72 * 1000 + new Date().getTime()
        setStoreState('user', 'token', { ...token, expireTime })
        router.push({
          path: '/index'
        })
      }
    })

    //测试伪造数据
    const loginUser = {
      email: 'alex9012@vip.qq.com',
      type: 0, // 用户账号本身类型 0：主账号，1：子账号
      userId: 1,
      username: params.Account,
      description: '',
      nickName: '罗超',
      phone: '17308037817',
      tenantId: 1,
      roleId: 1,
      userAvatar: 'https://preview.keenthemes.com/metronic8/demo7/assets/media/avatars/150-26.jpg'
    }
    setStoreState('user', 'userDetail', loginUser)
  }
}

type UserActionsType = typeof userActions

export { UserActionsType }
export default userActions
