/**
 * bitkeep钱包的tron
 * @type {{}}
 */
let bitkeepTron = {}
/**
 * 钱包初始校验
 * @returns {*}
 */
bitkeepTron.isInstall=function (){
    return window.tronLink && window.tronWeb;
}
/**
 * 获取我登陆的地址
 * @returns {any}
 */
bitkeepTron.getMyAddress=function () {
   return  uni.getStorageSync('myAddress')
}

/**
 * 获取基本账户地址
 * @returns {Promise<unknown>}
 */
bitkeepTron.getAccounts=async function (){
    return new Promise(async (resolve, reject) => {
        try {
            await window.tronLink.request({method: "tron_requestAccounts"});
            let selectedAddress = tronWeb.defaultAddress.base58;
            uni.setStorageSync('myAddress',selectedAddress)
            resolve(selectedAddress)
        }catch (e) {
            reject(e)
        }
    })
}

/**
 * 获取我的余额
 * @param selectedAddress
 * @returns {Promise<unknown>}
 */
bitkeepTron.getBalance= function (selectedAddress) {
    if(!selectedAddress){
        selectedAddress=bitkeepTron.getMyAddress();
    }
    return new Promise(async (resolve, reject) => {
        try {
            let balance = await tronWeb.trx.getBalance(selectedAddress);
            uni.setStorageSync('myAddress',selectedAddress)
            resolve(balance)
        }catch (e) {
            reject(e)
        }
    })
}

/**
 * trc转账
 * @param data
 * @returns {Promise<unknown>}
 */
bitkeepTron.sendTransaction=function (data){
    return new Promise(async (resolve, reject) => {
        try {
            let broastTx;
            if (data.contract) {
                const parameter = [{ type: 'address', value: data.to * Math.pow(10, 18) }];
                let tx = await tronWeb.transactionBuilder.triggerSmartContract(
                    data.contract,
                    "registrationExt(address)",
                    {},
                    parameter,
                    data.from
                );
                let signedTx = await tronWeb.trx.sign(tx.transaction);
                 broastTx = await tronWeb.trx.sendRawTransaction(signedTx);
            } else {
                let tx = await tronWeb.transactionBuilder.sendTrx(data.to, data.value * Math.pow(10, 6), data.from);
                // sign 签名
                let signedTx = await tronWeb.trx.sign(tx);
                //  broadcast  广播
                 broastTx = await tronWeb.trx.sendRawTransaction(signedTx);
            }
            if(broastTx.txid){
                resolve(broastTx.txid)
            }else {
                reject(false)
            }
        }catch (e) {
            reject(false)
        }
    })
}

export default bitkeepTron