import storage from 'store'
import { login, getInfo, logout } from '@/api/login'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getToken, setToken, removeToken, removeTokenDoMain, removeCookie, setCMSLoginName } from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {},
    userName: '',
    userId: null
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_USERNAME: (state, userName) => {
      state.userName = userName
    },
    SET_USERID: (state, userId) => {
      state.userId = userId
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    }
  },

  actions: {
    // 登录
    Login ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(res => {
          console.log('111', 111)
          setToken(res.token)
          // commit('SET_TOKEN', res.token)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo ({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(res => {
          console.log(`res`, res)
          const user = res.user
          const avatar = user.avatar === '' ? require('@/assets/images/profile.jpg') : process.env.VUE_APP_BASE_API + user.avatar
          if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', res.roles)
            commit('SET_PERMISSIONS', res.permissions)
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }
          commit('SET_NAME', user.nickName)
          commit('SET_USERNAME', user.userName)
          commit('SET_USERID', user.userId)
          commit('SET_AVATAR', avatar)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    Logout ({ commit, state }) {
      console.log(state)
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          storage.remove(ACCESS_TOKEN)
           // 清除登陆信息
          removeToken()
          removeCookie('BackAddr')
          removeCookie('joinsysCode')
          removeCookie('CMSLoginName')
          resolve()
        }).catch(error => {
          reject(error)
        }).finally(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
        })
      })
    },
    // // 用户名密码登录方式验证（登录页面向浏览器中添加token）
    CaUserLogin ({ commit }, userInfo) {
        const username = userInfo.username
        const password = userInfo.password
        return new Promise((resolve, reject) => {
          CAVerifyLogin(userInfo).then(response => {
            const result = response
            setToken.set(result.token)
            commit('SET_TOKEN', result.token)
            resolve(response)
          }).catch(error => {
            reject(error)
          })
        })
      }
  }
}

export default user
