import API from '@/api'
import { showError } from '@/util/util'
import { Promise } from 'es6-promise'

let TronHelper = {
  account: '',
  /**
   * @des 签名认证
   */
  async initTron () {
    if (!window.tronWeb) {
      showError('你还没有安装tron插件')
      return Promise.reject(new Error(''))
    }

    let account = window.tronWeb.defaultAddress.base58
    let randomRes = await API.user.getRandom2({ account: account })
    let s = window.tronWeb.sha3(randomRes.data.data.random)
    let resutlSign
    try {
      resutlSign = await window.tronWeb.trx.signMessage(s)
    } catch (e) {
      if (e == 'Invalid transaction provided') showError('请重新安装钱包插件')
      else showError(e)

      this.setLogining(false)
      return
    }

    // if (window.tronWeb.fullNode.host != 'https://api.trongrid.io') {
    //   showError('tron不是主网')
    //   return Promise.reject(new Error(''))
    // }

    try {
      // let rs = await window.tronWeb.trx.verifyMessage(s, resutlSign, account)

      return Promise.resolve({
        account: account,
        sign: resutlSign
      })
    } catch (e) {
      return Promise.reject(e)
    }
  }
}

export default TronHelper
