import { login, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { getAccountAuthQuery } from '@/api/accountAuth'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    authAccountInfo: null
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_AUTH_ACCOUNT_INFO: (state, authAccountInfo) => {
    state.authAccountInfo = authAccountInfo
  }
}

const actions = {
  // user login
  login({ commit, dispatch }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(async response => {
        const { data } = response
        commit('SET_NAME', username.trim())
        commit('SET_TOKEN', data)
        setToken(data)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 获取登录账号信息
  async getAuthAccountQuery({ commit, dispatch }) {
    return new Promise((resolve) => {
      getAccountAuthQuery().then(async res => {
        /**
         HHArome设备授权管理 --> 设备基本信息
         */
        const deviceInfoFieldArr = {
          0: 'tenantId', // 服务商平台名称
          1: 'ampeId' // Ampe平台名称
        }
        commit('SET_AUTH_ACCOUNT_INFO', {
          ...(res?.data || {}),
          deviceConfig: (res?.data?.deviceConfig || []).filter(dv => dv.moduleSwitch).map(mItem => deviceInfoFieldArr[Number(mItem.moduleType)])
        })
        // accountType 账号类型 0:超级管理员 1:普通管理员 2:授权账号
        const accountType = res.data?.accountType
        const hhAromeSwitch = !!res.data?.hhAromeSwitch
        const hhFaceSwitch = !!res.data?.hhFaceSwitch
        let authType = []
        if (accountType == 2) {
          if (hhAromeSwitch) {
            authType.push('HHArome')
          }
          if (hhFaceSwitch) {
            authType.push('HHFace')
          }
        } else {
          authType = ['HHFace', 'HHArome']
        }
        console.log(authType)
        await resetRouter()
        // generate accessible routes map based on roles
        const accessRoutes = await dispatch('permission/generateRoutes', {
          accountType,
          authType,
          role: 1
        }, {
          root: true
        })
        console.log('accessRoutes', accessRoutes)
        // dynamically add accessible routes
        router.addRoutes(accessRoutes)
        resolve(accessRoutes)
      })
    })
  },
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { name, avatar } = data

        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
      //   removeToken() // must remove  token  first
      //   resetRouter()
      //   commit('RESET_STATE')
      //   resolve()
      // }).catch(error => {
      //   reject(error)
      // })
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

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

