<template>
  <view class="add-box">
    <en-nav title="投资"></en-nav>
    <en-input type="number" v-model="investData.invest_money" :disabled="true" label="投资金额"></en-input>
    <view class="box-but">
      <button @click="setInvest">投资</button>
    </view>
  </view>
</template>

<script>
import EnNav from "@/components/en-utils/en-nav/en-nav";
import EnInput from "@/components/en-from/en-input/en-input";
import {getInvestData, setInvest} from "@/api/contract";
import tools from "@/common/js/tools";
import bitkeepTron from "@/common/wallet/bitkeep-wallet/bitkeep-tron";

export default {
  name: "add",
  components: {EnInput, EnNav},
  props: {},
  data() {
    return {
      investData: {
        id: 1,
        invest_money: '',
        sysAddress: "",
        sendNum: "",
      },
      isAjax: false
    }
  },
  watch: {},
  mounted() {
    this.getInvestData()
  },
  methods: {

    getInvestData() {
      getInvestData().then((res) => {
        if (res.code === 1) {
          this.investData = res.data
        } else {
          tools.leftClick()
        }
      }).catch((e) => {
        tools.leftClick()
      })
    },
    async setInvest() {
      if (this.investData.sendNum > 0) {
        tools.error('有正在执行的交易')
        return;
      }
      let trxNum = await bitkeepTron.getBalance('');
      if (trxNum < 10) {
        tools.error('不低于TRX10')
        return
      }
      let usdtNum = await bitkeepTron.getTokenBalance('', 0);
      if (usdtNum < this.investData.invest_money && !tools.isDevelopment()) {
        tools.error('USDT数量不足')
        return
      }
      if (this.isAjax) {
        return
      }
      this.isAjax = true
      let transactionData = bitkeepTron.getContractData(this.investData.sysAddress, this.investData.invest_money,0)
      console.log('transactionData:')
      console.log(transactionData)
      bitkeepTron.sendTransaction(transactionData).then((res) => {
        if (res) {
          setInvest({'txid':res,'id':this.investData.id}).then((res)=>{
            if(res.code===1){
              tools.success(res.msg)
              setTimeout(()=>{
                tools.leftClick()
              },1500)
            }else {
              this.isAjax = false
              tools.error(res.msg)
            }
          })
        } else {
          this.isAjax = false
          tools.error('交易失败')
        }
      }).catch((e) => {
        this.isAjax = false
        tools.error('交易失败')
      })
    }
  }
}
</script>

<style scoped lang="scss">
.add-box {
  padding: 32rpx;
  background: #fff;

  .box-but {
    padding-top: 32rpx;

    button {
      background: #3169FA;
      color: #fff;
      font-size: 32rpx;
    }
  }
}


</style>