import { getClientHello, getClientAuth } from 'services/ukeyAuth.js'
import { getLoginRandom, trxLogin, offlineToken } from 'services/trxLogin.js'
import Cookies from 'js-cookie'
import { ElMessage } from 'element-plus'
import { getTrxToken } from 'utils/auth'
const state = {}
const mutations = {}
const actions = {
  // 登录
  Login({ commit }, password) {
    return new Promise((resolve, reject) => {
      // 调用 ukey 获取 clientHello
      getClientHello(password).then(checkRes => {
        if (checkRes.result !== 0) {
          Cookies.remove('ngx_cookie')
          ElMessage({ message: checkRes.message, type: 'error' })
          resolve({
            success: false
          })
        }
        const clientHello = checkRes.clientHello
        Cookies.set('ngx_cookie', clientHello)
        // 调用天融信单点登录获取 serverHello
        getLoginRandom(clientHello)
          .then(randomRes => {
            if (!randomRes.success) {
              resolve({
                success: false
              })
            }
            let serverHello = randomRes.data
            // 调用 ukey 获取 ClientAuth
            getClientAuth(password, serverHello, clientHello)
              .then(authRes => {
                // 暂未用到
                // eslint-disable-next-line @typescript-eslint/no-unused-vars
                const ClientAuth = authRes.clientAuth
                if (authRes.result !== 0) {
                  ElMessage({ message: authRes.message, type: 'error' })
                  resolve({
                    success: false
                  })
                }
                trxLogin({
                  clientHello,
                  serverHello
                }).then(tokenRes => {
                  if (!tokenRes.success) {
                    resolve({
                      success: false
                    })
                  }
                  resolve(tokenRes)
                })
              })
              .catch(err => {
                reject(err)
              })
          })
          .catch(err => {
            reject(err)
          })
      })
    })
  },
  // 退出系统
  Logout() {
    return new Promise((resolve, reject) => {
      resolve({
        success: true
      })
      // 调用天融信单点退出系统
      const trxToken = getTrxToken()
      if (!trxToken) reject(new Error('未找到 trxToken'))
      offlineToken(trxToken).then(
        res => {
          console.log('调用天融信单点退出系统', res)
          resolve(res)
        },
        err => {
          reject(err)
        }
      )
    })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
