import { login, logout, getInfo } from '@/api/user'
import { initData } from '@/api/dashboard'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { initNumberHtml } from '@/utils/costum'
import router, { resetRouter } from '@/router'
// refreshtoken
const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  permissions: [],
  permisaction: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USERID: (state, userId) => {
    state.userId = userId
  },
  SET_AVATAR: (state, avatar) => {
    if (avatar.indexOf('http') !== -1) {
      state.avatar = avatar
    } else {
      state.avatar = process.env.VUE_APP_BASE_API + avatar
    }
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PERMISSIONS: (state, permisaction) => {
    state.permisaction = permisaction
  },
  SET_REFRESH_TOKEN: (state, refreshToken) => {
    state.refreshToken = refreshToken
  },
  SET_EXPIRES_IN: (state, expiresIn) => {
    state.expiresIn = expiresIn
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password, clientId: 'oa', clientSecret: 'oa' }).then(response => {
        const { data } = response
        if (response.code == 200) {
          console.log(data)
          const token = data.authentication.token_type + ' ' + data.authentication.access_token
          commit('SET_REFRESH_TOKEN', data.authentication.refresh_token)
          commit('SET_EXPIRES_IN', data.authentication.expires_in)
          commit('SET_TOKEN', token)
          setToken(token)
          resolve()
        }
        // const { token } = response
      }).catch(error => {
        reject(error)
      })
    })
  },
  setAvatar({commit}, url) {
    commit('SET_AVATAR', url)
  },
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        if (!response || !response.data) {
          commit('SET_TOKEN', '')
          removeToken()
          resolve()
        }

        const { userId, roles, name, avatar, introduction, permissions } = response.data

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }
        commit('SET_PERMISSIONS', permissions)
        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_USERID', userId)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        resolve(response)
      }).catch(() => {
        commit('SET_TOKEN', '')
        setToken('')
        router.push({ path: '/' })
      })
    })
  },
  getInitData({ commit, state }) {
    return new Promise((resolve, reject) => {
      initData().then(response => {
        const result = response.data
        // 添加我的代办显示数据
        if(result.count.upcoming && result.count.upcoming > 0) {
          initNumberHtml(result.count.upcoming)
        }
      })
      resolve(response)
    }).catch(() => {
    })
  },
  // 退出系统
  LogOut({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_PERMISSIONS', [])
        removeToken()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 刷新token
  // refreshToken({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     refreshtoken({ token: state.token }).then(response => {
  //       const { token } = response
  //       commit('SET_TOKEN', token)
  //       setToken(token)
  //       resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

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

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      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 })

      resolve()
    })
  }
}

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