import API from '@/api'
// import Web3 from 'web3'
import { showError } from '@/util/util'

let ethHelper = {
  isInitEth: false,
  curAccount: '',
  network: 0,
  getMainNetwork () {
    return window.web3.eth.net.getNetworkType()
  },
  /**
   * @des 签名认证
   */
  async initEth () {
    if (!window.ethereum || !window.web3) {
      showError('你还没有安装eth插件')
      return Promise.reject(new Error(''))
    }

    if (window.ethereum) {
      await window.ethereum.enable()
    }

    // let networkType = await window.web3.eth.net.getNetworkType()
    // if (networkType != 'main') {
    //   showError('eth不是主网')
    //   return Promise.reject(new Error('eth不是主网'))
    // }

    let accounts = window.web3.eth.accounts
    let account = this.account = accounts[0]

    if (account) {
      this.curAccount = account
      let randomRes = await API.user.getRandom2({ account: account })

      return new Promise((resolve, reject) => {
        try {
          window.web3.personal.sign(window.web3.fromUtf8(randomRes.data.data.random), window.web3.eth.coinbase, (err, rs) => {
            if (err) {
              reject(err)
            } else {
              resolve({
                account: account,
                sign: rs
              })
            }
          })
        } catch (err) {
          reject(err)
        }
      })
    } else {
      return Promise.reject(new Error(''))
    }
  },
  /**
   * @des 转账
   * @param {Number} money 转账金额
   */
  async doTransfer (money) {
    try {
      await this.initEth()
      let balance = await window.web3.eth.getBalance(this.curAccount)
      if (10e17 * money > balance) {
        showError('The balance of account is insufficient.')
        return
      }
      const txData = {
        from: this.account,
        to: '0x42eb768f2244c8811c63729a21a3569731535f06',
        value: window.web3.utils.toWei(money.toString(), 'ether')
      }

      return new Promise((resolve, reject) => {
        window.web3.eth.sendTransaction(txData, (err, txHash) => {
          if (err) {
            reject(err)
          } else {
            // this.waitEthTransfer(txHash)
            resolve()
          }
        })
      })
    } catch (e) {
      return Promise.reject(e)
    }
  },
  // 检测转账进度
  waitEthTransfer (txHash) {
    window.web3.eth.getTransactionReceipt(txHash, (err, res) => {
      console.log('waitEthTransfer', err, res)
      if (err) {
        console.error(err)
      }

      if (!res) {
        setTimeout(this.waitEthTransfer, 1000, txHash)
      } else if (res && res.status) {
        this.visible = false
      }
      console.log('res', res)
    })
  }
}

export default ethHelper
