import API from '@/api'
import Eos from 'eosjs'
import { Cookie } from '../../util/util'
import { getNetwork } from '../../util/contract.js'

var LoginPlugin = {}
LoginPlugin.install = function (Vue, store) {
  let { state } = store
  // 获取用户公钥
  Vue.prototype.$getPubKey = function () {
    return new Promise((resolve, reject) => {
      let publicKey
      let account = state.account
      if (account) {
        state.eos.getAccount(account.name).then(data => {
          const perms = JSON.parse(JSON.stringify(data.permissions))
          perms.forEach(v => {
            if (v.perm_name == "active") {
              publicKey = v.required_auth.keys[0].key
            }
          })
          resolve(publicKey)
        })
      } else {
        reject('account is not define')
      }
    })
  }
  //生成随机数
  Vue.prototype.$getRandom = function () {
    let account = state.account
    return new Promise((resolve, reject) => {
      API.user.getRandom({
        account: account.name
      }).then(data => {
        resolve(data.data.data)
      }).catch(reject)
    })
  }

  // 私钥签名登录
  Vue.prototype.$login = async function () {
    if (!state.account.name) {
      let networkConfig = await getNetwork();
      try {
        let identity = await state.scatter.login({ accounts: [networkConfig] })
        let accounts = identity.accounts.find(x => x.blockchain === 'eos')
        store.dispatch('setAccount', accounts)
        store.dispatch('setEos', state.scatter.eos(networkConfig, Eos, {}))
        return Promise.resolve()
      } catch (error) {
        return Promise.reject()
      }
    }
    if (Cookie.getCookie('account') && Cookie.getCookie('token')) {
      return Promise.resolve()
    } else {
      try {
        let account = state.account
        let [random, pubkey] = await Promise.all([this.$getRandom(), this.$getPubKey()])
        return new Promise((resolve, reject) => {
          state.scatter.getArbitrarySignature(pubkey, random, this.$t('walletLogin')).then(sign => {
            let param = {
              account: account.name,
              sign,
              pubkey,
              data: random
            }
            API.user.login(param).then(({ data }) => {
              if (data.result == 1) {
                let account = data.data.account
                let token = data.data.token
                Cookie.setCookie('account', account)
                Cookie.setCookie('token', token)
                resolve(data)
              } else {
                reject(data.msg)
              }
            })
          }).catch(err => {
            reject(err)
          })
        })
      } catch (error) {
        Promise.reject(error)
      }
    }
  }
}

export default LoginPlugin
