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, options) {
  // 获取用户公钥
  Vue.prototype.$getPubKey = function () {
    return new Promise((resolve, reject) => {
      let publicKey
      let account = this.$store.state.account
      if (account) {
        this.$store.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)
        })
      }
    })
  }
  // 生成随机数
  Vue.prototype.$getRandom = function () {
    let account = this.$store.state.account
    return new Promise((resolve, reject) => {
      API.user.getRandom({
        account: account.name
      }).then(data => {
        resolve(data.data.data)
      })
    })
  }

  // 私钥签名登录
  Vue.prototype.$login = async function () {
    if (!this.$store.state.account.name) {
      let networkConfig = await getNetwork()
      try {
        let identity = await this.$store.state.scatter.getIdentity({ accounts: [networkConfig] })
        let accounts = identity.accounts.find(x => x.blockchain === 'eos')
        this.$store.dispatch('setAccount', accounts)
        this.$store.dispatch('setEos', this.$store.state.scatter.eos(networkConfig, Eos, {}))
        return Promise.resolve()
      } catch (error) {
        return Promise.reject(error)
      }
    }

    if (Cookie.getCookie('account') && Cookie.getCookie('token')) {
      return Promise.resolve()
    } else {
      try {
        let account = this.$store.state.account
        let [random, pubkey] = await Promise.all([this.$getRandom(), this.$getPubKey()])
        return new Promise((resolve, reject) => {
          this.$store.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(new Error(data.msg))
              }
            })
          }).catch(error => {
            reject(error)
          })
        })
      } catch (error) {
        Promise.reject(error)
      }
    }
  }

  Vue.prototype.$isLogin = function () {
    return Cookie.getCookie('account') && Cookie.getCookie('token')
  }
}

export default LoginPlugin
