import { login, logout, getInfo, getMenu ,getImgCode,updateUserAvatarNickname } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  userid:'',
  role_id:''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLE_ID: (state, role_id) => {
    state.role_id = role_id
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_USERID: (state, id) => {
    state.userid = id
  },
  // 退出登录逻辑直接放在 mutations 中
  LOGOUT(state) {
    state.token = ''
    state.roles = []
    removeToken()
    resetRouter()
  }
}

const actions = {
  // 用户登录
  login({ commit }, userInfo) {
    const { username, password, type, captcha } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password, type: type, captcha: captcha.trim() }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token,data.exp)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户身份信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        // if (!data) {
        //   reject('Verification failed, please Login again.')
        // }
        // 所有用户的身份都为admin
        const roles = ['admin']
        const { nickname, avatar, introduction,role_id } = data
        data.roles = roles
        // roles must be a non-empty array
        // 判断是否包含权限
        // if (!roles || roles.length <= 0) {
        //   reject('getInfo: roles must be a non-null array!')
        // }
        commit('SET_ROLES', roles)
        commit('SET_USERID', data.id)
        commit('SET_NAME', nickname)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        commit('SET_ROLE_ID', role_id)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取图形验证码
  getImgCode() {
    return new Promise((resolve, reject) => {
      getImgCode({}).then(response => {
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 用户退出
  // logout({ commit, state, dispatch }) {
  //   return new Promise((resolve, reject) => {
  //     logout(state.token).then(() => {
  //       commit('SET_TOKEN', '')
  //       commit('SET_ROLES', [])
  //       removeToken()
  //       resetRouter()

  //       // 重置已经访问过的视图
  //       // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
  //       dispatch('tagsView/delAllViews', null, { root: true })

  //       resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  // 清理token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // 用户切换时重置路由
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  },

  //修改用户名和密码
  updateUserAvatarNickname({commit},data) {
    return new Promise((resolve, reject) => {
      updateUserAvatarNickname(data).then(response => {
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
