import { login, getInfo, logout, qyWxLoginApi,innerLogin } from '@/api/system/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

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

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_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, codeKey, code } = userInfo
    return new Promise((resolve, reject) => {
      login(username, password, codeKey, code).then(response => {
        const { result } = response
        console.log(result)
        commit('SET_TOKEN', result)
        setToken(result)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  innerLogin({ commit }) {
    return new Promise((resolve, reject) => {
      innerLogin().then(response => {
        const { result } = response
        console.log(result)
        commit('SET_TOKEN', result)
        setToken(result)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user login
  qyWxLogin({ commit }, userInfo) {
    const { code } = userInfo
    return new Promise((resolve, reject) => {
      qyWxLoginApi(code).then(response => {
        const { data } = response
        commit('SET_TOKEN', data)
        setToken(data)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const { result } = response
        if (!result) {
          reject('Verification failed, please Login again.')
        }
        const { userName, imgUrl, introduction, roles, permissions } = result

        // if has not roles and permissions, add a random code.
        if (!roles || roles.length === 0) {
          roles.push('if has not roles and permissions, add a random code')
        }

        commit('SET_NAME', userName)
        commit('SET_AVATAR', imgUrl)
        commit('SET_INTRODUCTION', introduction)
        commit('SET_ROLES', roles)
        commit('SET_PERMISSIONS', permissions)
        resolve(result)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_PERMISSIONS', [])
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

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

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

  // dynamically modify permissions
  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 })
  }
}

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