import uc from '@/api/uc.js'
import portal from '@/api/portal.js'
import {getUserInfoState} from '@/api/systemInterface.js'

const state = {
  currentUser: null,
  loginAccount: null,
  isRefreshToken: false,
  isJump: false,
  isFinishedUserInfo: true,
  isLogin: false
}

const getters = {}

const actions = {
  checkUserInfoState({commit, state}) {
    return new Promise((resolve, reject) => {
      getUserInfoState().then(res => {
        sessionStorage.setItem('UserInfoState', res)
        commit('setUserInfoState', res)
        resolve(res)
      }).catch(err => {
        commit('setUserInfoState', false)
        reject(err)
      })
    })
  },
  actionLoginAccount({commit, state}, loginAccount) {
    commit('mutationLoginAccount', loginAccount)
  },
  // 登录获取字典
  getAllDict({commit, state}) {
    portal.getSysDict().then(res => {
      if (res) {
        sessionStorage.setItem('dict_data', JSON.stringify(res))
      }
    })
  },
  // 愉快政code登录
  loginByReports({commit, state}, code) {
    return new Promise((resolve, reject) => {
      // 设置跳转类型，在返回401无权限时不跳转到登录页
      uc.authEmployeeCodeLogin(code).then(user => {
        if (user.state === undefined && user.loginStatus) {
          sessionStorage.setItem('currentUser', JSON.stringify(user))
          commit('setCurrentUser', user)
          resolve(user)
        } else {
          reject(user)
        }
      }).catch(err => {
        console.log(err, 'err')
        commit('clearCurrentUser')
        reject(err)
      })
    })
  },
  // 愉快政绑定
  bindingYKZ({commit, state}, data) {
    return new Promise((resolve, reject) => {
      // 设置跳转类型，在返回401无权限时不跳转到登录页
      commit('setJumpType', true)
      sessionStorage.setItem('isJUmp', JSON.stringify(true))
      uc.bindingYKZLogin(data).then(user => {
        if (user.loginStatus && user.loginStatus) {
          sessionStorage.setItem('currentUser', JSON.stringify(user))
          commit('setCurrentUser', user)
          resolve(user)
        }
      }).catch(err => {
        commit('clearCurrentUser')
        reject(err)
      })
    })
  },
  loginByPrincipal({commit, state}, principal) {
    return new Promise((resolve, reject) => {
      uc.authentication(principal, user => {
        if (user) {
          sessionStorage.setItem('currentUser', JSON.stringify(user))
          commit('setCurrentUser', user)
          resolve(user.loginStatus)
        }
      }, (msg) => {
        commit('clearCurrentUser')
        reject(msg)
      })
    })
  },
  validAndCompletedCurrent({commit, state}, token) {
    return new Promise((resolve, reject) => {
      if (state.currentUser && !token) {
        resolve()
      } else {
        const user = sessionStorage.getItem('currentUser')
        if (user !== 'null' && user !== undefined && user !== '' && !token) {
          commit('setCurrentUser', JSON.parse(user))
          resolve()
        } else if (token) {
          uc.basicSso(token, user => {
            sessionStorage.setItem('currentUser', JSON.stringify(user))
            commit('setCurrentUser', user)
            resolve(user.loginStatus)
          }, () => {
            reject()
          })
        } else {
          reject()
        }
      }
    })
  },
  refreshAndGetAuthenticationToken({commit, state}) {
    if (state.isRefreshToken) {
      return
    }
    commit('isRefreshToken', true)
    return new Promise((resolve, reject) => {
      uc.refreshAndGetAuthenticationToken().then(user => {

        if (user) {
          sessionStorage.setItem('currentUser', JSON.stringify(state.currentUser))
          commit('refreshToken', user.token)
          setTimeout(() => {
            commit('isRefreshToken', false)
          }, 3000)
          resolve()
        }
      }, (msg) => {
        reject(msg)
      })
    })
  },
  logoutAndCleanUp({commit, state}) {
    return new Promise((resolve, reject) => {
      uc.logout().finally(() => {
        sessionStorage.removeItem('currentRoleMenus')
        sessionStorage.removeItem('currentRoleCode')
        sessionStorage.removeItem('currentUserDetail')
        sessionStorage.removeItem('currentUser')
        sessionStorage.removeItem('searchDate')
        commit('clearCurrentUser')
        commit('user/setCurrentUserDetail', null, {root: true})
        commit('user/setCurrentUserOrg', null, {root: true})
        resolve()
      })
    })
  }
}

const mutations = {
  setUserInfoState(state, status) {
    state.isFinishedUserInfo = status
  },
  isRefreshToken(state, status) {
    state.isRefreshToken = status
  },
  refreshToken(state, token) {
    state.currentUser.token = token
    state.currentUser.loginTime = new Date().getTime()
  },
  setCurrentUser(state, current) {
    state.currentUser = current
  },
  clearCurrentUser(state) {
    state.currentUser = null
  },
  mutationLoginAccount(state, loginAccount) {
    state.loginAccount = loginAccount
  },
  setJumpType(state, type) {
    state.isJump = type
  }
}

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