import md5 from 'md5'
import { login, getUserInfo } from '@/api/login'
import { setItem, getItem, removeAllItem } from '@/utils/index'
import { TOKEN } from '@/utils/constant'
import router from '@/router/index'
import { setTimeStamp } from '@/utils/auth'
import { Message } from 'element-ui'
import { loginOutApi } from '@/api/login'

export default {
  namespaced: true, //单独的模块 不会合并到主模块里面去
  state: () => ({
    token: getItem(TOKEN) || '',
    userInfo: {}
  }),
  mutations: {
    setToken(state, token) {
      setItem(TOKEN, token)
      // 保存登录时间
      setTimeStamp()
      if (token) {
        Message({
          message: '登陆成功',
          type: 'success',
          duration: 1000
        })
        setTimeout(() => {
          router.push('/')
        }, 1000)
      }
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    }
  },
  actions: {
    // 登录请求动作
    async login(context, userInfo) {
      const { username, password } = userInfo
      const res = await login({ username, password })
      // const res = { token: '123', code: 200 }
      this.commit('user/setToken', res.token)
      return res
    },
    // 获取用户信息
    async getUserInfo(context, userInfo) {
      const { data, code } = await getUserInfo()
      // const data = []
      this.commit('user/setUserInfo', data)
      return data
    },
    // 退出登录
    async loginOut() {
      this.commit('user/setToken', '')
      this.commit('user/setUserInfo', {})
      this.commit('app/removeTagsViewList')
      removeAllItem()
      // TODO 清理权限相关配置
      router.push('login')
      router.go(0)
    },
    // 手动退出登录
    async loginOutCopy() {
      const { code } = await loginOutApi()
      if (code == 200) {
        this.commit('user/setToken', '')
        this.commit('user/setUserInfo', {})
        this.commit('app/removeTagsViewList')
        removeAllItem()
        // TODO 清理权限相关配置
        router.push('login')
        router.go(0)
      }
    }
  }
}
