// import { login, logout, getInfo } from '@/api/user'
import { login, getInfo } from '@/api/user'
import { getOrganizeInfo } from '@/api/sys'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
// import store from '@/store'

const state = {
  token: getToken(),
  isSimplePwd: false,
  name: '',
  avatar: '',
  systemName: '',
  systemImage: '',
  organizeId: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_IS_SIMPLE_PWD: (state, isSimplePwd) => {
    state.isSimplePwd = isSimplePwd
  },
  SET_SYSTEM_NAME: (state, systemName) => {
    state.systemName = systemName
  },
  SET_SYSTEM_IMAGE: (state, systemImage) => {
    state.systemImage = systemImage
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ORGANIZE_ID: (state, organizeId) => {
    state.organizeId = organizeId
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  getSysInfo: function({ commit, state }) {
    return new Promise((resolve, reject) => {
      getOrganizeInfo({ id: state.organizeId }).then(response => {
        const { data } = response
        if (data) {
          const { systemName, systemImage } = data
          commit('SET_SYSTEM_NAME', systemName)
          commit('SET_SYSTEM_IMAGE', systemImage)
        }
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user login
  login: function({ commit, dispatch }, userInfo) {
    const { account, password, simplePwd } = userInfo
    return new Promise((resolve, reject) => {
      commit('SET_IS_SIMPLE_PWD', false)
      if (password.trim() === simplePwd) {
        commit('SET_IS_SIMPLE_PWD', true)
      }
      login({ account: account.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data)
        setToken(data)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        // const { data } = response
        const data = response.data
        if (!data) {
          reject('Verification failed, please Login again.')
        }
        /* const { roles, account, avatar, introduction } = data
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        } */
        data.roles = ['admin']
        const { roles, accountName, avatar, organizeId } = data
        commit('SET_ROLES', roles)
        commit('SET_NAME', accountName)
        commit('SET_AVATAR', avatar)
        commit('SET_ORGANIZE_ID', organizeId)
        dispatch('getSysInfo')
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      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', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    // eslint-disable-next-line no-async-promise-executor
    return new Promise(async resolve => {
      const token = role + '-token'

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

      const userInfo = await dispatch('getInfo')

      resetRouter()

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

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

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

      resolve()
    })
  }

}

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