import { login, logout, getInfo, refreshToken } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import storage from '@/utils/storage'
import { MessageBox } from 'element-ui'
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_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
  }
}

const actions = {
  // setTokenRefresh({ commit, dispatch }, refreshTime) {
  //   const delay = refreshTime - Date.now()
  //   console.log('userstore-----delay-----', delay)
  //   if (delay > 0) {
  //     setTimeout(() => {
  //       dispatch('refreshTokenFn')
  //     }, delay)
  //   }
  // },
  // user login
  login({ commit, dispatch }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        const { token } = response
        commit('SET_TOKEN', token)
        setToken(token)
        // 计算过期时间（expire 是一个相对时间戳，通常单位是秒）
        // const expireTime = new Date(expire).getTime() // 转换为毫秒
        // localStorage.setItem('expireTime', expireTime)
        // // 设置刷新 token 的时间（提前 10 分钟）
        // const refreshTime = expireTime - 50 * 60 * 1000
        // dispatch('setTokenRefresh', refreshTime)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        if (!response || !response.data) {
          commit('SET_TOKEN', '')
          removeToken()
          resolve()
        }

        const { 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_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 退出系统
  LogOut({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_PERMISSIONS', [])
        removeToken()
        storage.clear()
        clearInterval(window.refreshTime)
        window.refreshTime = null
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 刷新token
  refreshTokenFn({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      // 创建配置对象，设置请求头
      const config = {
        headers: {
          'Authorization': 'Bearer ' + getToken() // 特定请求的 header
        }
      }
      refreshToken({ token: state.token }, config).then(response => {
        if (response.code == 200) {
          const { token } = response
          commit('SET_TOKEN', token)
          setToken(token)
          // 更新 accessToken 和 expire 时间
          // const expireTime = new Date(expire).getTime() // 转换为毫秒
          // localStorage.setItem('expireTime', expireTime)
          // // 设置刷新 token 的时间（提前 5 分钟）
          // const refreshTime = expireTime - 10 * 60 * 1000 // 提前 10 分钟刷新
          // console.log('refreshToken====refreshTime----', refreshTime)
          // dispatch('setTokenRefresh', refreshTime)
          resolve()
        } else {
          MessageBox.confirm(
            '登录状态已过期，您可以继续留在该页面，或者重新登录',
            '系统提示',
            {
              confirmButtonText: '重新登录',
              cancelButtonText: '取消',
              type: 'warning'
            }
          ).then(() => {
            commit('SET_TOKEN', '')
            removeToken()
            clearInterval(window.refreshTime)
            window.refreshTime = null
            storage.clear()
            location.reload() // 为了重新实例化vue-router对象 避免bug
            this.$router.push('/login')
            resolve()
          })
          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) {
    // eslint-disable-next-line no-async-promise-executor
    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
}
