import { login } from '@/api/user'
import router, { resetRouter } from '@/router'
import { setToken, deleteToken } from '@/utils/auth'
// import Base from '@/utils/base64ToPassword'
// import Vue from 'vue'

// const defaultSingleSignOn = localStorage.getItem('SET_SINGLE_SIGN_ON') !== '0' // 默认单点登录

const userInfo = localStorage.getItem('userInfo')

const state = {
  singleSignOn: localStorage.getItem('SET_SINGLE_SIGN_ON') !== '0', // 单点登录
  userInfo: userInfo && userInfo !== 'undefined' ? JSON.parse(userInfo) : {}
}

const mutations = {
  SET_SINGLE_SIGN_ON (state, loginType) {
    state.singleSignOn = loginType === 1
    localStorage.setItem('SET_SINGLE_SIGN_ON', loginType)
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
  }
}

const actions = {
  login ({ commit, dispatch }, params) {
    const { username, password } = params
    // const newBase = new Base()
    const newParams = {
      username: username.trim(),
      password: password
      // password: newBase.encode(password + (Math.random()).toString().slice(2, 8))
    }
    // 账号密码处理
    return new Promise((resolve, reject) => {
      login(newParams).then(res => {
        // 登录成功返回对应的信息 包括token 用户信息 权限等等
        const { data } = res
        commit('SET_SINGLE_SIGN_ON', 0)
        setToken(data.token)
        // const { username, name, id, employeeCode } = data.user
        commit('SET_USERINFO', data)
        resolve()
      }).catch(err => { reject(err) })
    })
  },
  // 退出登录
  /**
   *
   * @param {*} param
   * @param { Boolean } isLogin 是否调用回到登录页方法
   */
  userLogout ({ commit }) {
    // 清空权限菜单
    // deleteRoles()
    // 清空token
    deleteToken()
    // 清除路由
    resetRouter()
    // 清除问卷uuid
    localStorage.removeItem('verifyUUID')
    // 单点登录信息
    // localStorage.removeItem('SET_SINGLE_SIGN_ON')
    // 跳转到登录菜单

    if (!state.singleSignOn) {
      // 普通退出
      router.push({ path: '/login-local' })
      commit('SET_SINGLE_SIGN_ON', 1) // 重置为单点登录
      // window.location.href = '/login'
      return
    }
    // 单点退出
    // const windowBox = window.open(`${window?.g}/gzIcbcCertification/aam/logout`, 'new', 'location=no, toolbar=no')
    // const windowBox = window.open('http://aam.icbc/uniform_attestation/exitokoa.jsp', 'new', 'location=no, toolbar=no')
    // setTimeout(_ => {
    //   windowBox.close()
    // }, 500)
    // location.reload()
    router.push({ path: '/reminder' })
    // }, 500)
  }
}

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