import axios,{AxiosInstance,AxiosResponse} from "axios";


interface Account{
    address: string
    privateKey:string
    publicKey?:string
}
type Callback = (data:AxiosResponse<any>)=>any

class ChainService {
    service:AxiosInstance
    account:Account

    constructor(url:string,account:Account){
        this.account = account;
        this.service = axios.create({
            baseURL:url,
            timeout: 15000,
            method:'post'
        })
    }
    /**
     * 请求区块链RPC接口的基本方法
     * @param method 区块链请求方法
     * @param data 请求的数据内容
     * @param cb 回掉方式获取Response
     * @returns 
     */
    private async chainRequire(method:string,data:any[],cb?:Callback){
       return await this.service.request({
            data:{
                id:1,
                method:method,
                params:data
            }
        }).then(res=>{
            if(cb){
            return cb(res)
            }
            return res
        }).catch((err)=>{
            if(cb){
                return cb(err)
            }
            return err
        })

    }

    /**
     * 
     * @param toAddr 要转账的目标地址
     * @param contractPair 
     * @returns 
     */
    async creatTransition(toAddr:string,amount:number,execer?:string){
        return await this.chainRequire('Chain33.CreateRawTransaction',[{
            to:toAddr,
            amount:amount,
            fee:0.003*10e8,
            isWithdraw:false,
            execer:execer?execer:'coins'
        }])
    }

    async signTransition(txHex:string,privateKey:string){
        return await this.chainRequire('Chain33.SignRawTx',[{
            privkey:privateKey,
            txHex:txHex,
            expire:'1h',
            fee:0.003*10e8
        }])
    }

    async sendTransaction(txHex:string){
        return await this.chainRequire('Chain33.SendTransaction',[{
            data:txHex
        }])
    }

    async buildGroupTransaction(txHexs:string[]){
        return await this.chainRequire('Chain33.CreateRawTxGroup',[{
            txs:txHexs
        }])
    }

    async getInfoByHash(hash:string){
        return await this.chainRequire('Chain33.QueryTransaction',[{
            "hash":hash
        }])
    }
}