<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="500px"
    @close="close"
  >
    <el-form ref="formRef" label-width="100px" :model="form" :rules="rules">
      <el-form-item label="订单的uuid" prop="uuid">
        <el-input v-model="form.uuid" readonly/>
      </el-form-item>
      <el-form-item label="账号" prop="uuid">
        <el-select v-model="form.withdrawalAccount">
          <el-option v-for="(v,i) in accounts" @click="accountIndex = i" :key="i" :label="v.remarks"
                     :value="v.address"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="accounts[accountIndex]" label="主币余额" prop="uuid">
        <el-input v-model="accounts[accountIndex].balance" readonly/>
      </el-form-item>
      <el-form-item v-if="accounts[accountIndex]" label="代币余额" prop="uuid">
        <el-input v-model="accounts[accountIndex].tokenBalance" readonly/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { defineComponent, getCurrentInstance, reactive, toRefs }      from 'vue';
import { ElLoading, ElMessage }                                       from "element-plus";
import { getListenInfo, getWithdrawalAccount, withdrawal }            from "../../../../apis/address";
import { getWeb3Balance, getWeb3TokenBalance, setTokenWeb3Rpc, web3 } from "../../../../apis/wallet/web3";
import { getTronBalance, getTronTokenBalance, setTronRpc }            from "../../../../apis/wallet/tronweb";

export default defineComponent( {
  name : 'WithdrawalLogTrigger',
  setup ( props, { emit } ) {
    const { proxy } = getCurrentInstance();
    const state     = reactive( {
      formRef           : null,
      accounts          : [],
      accountIndex      : -1,
      form              : {
        uuid              : '',   // 订单的uuid
        withdrawalAccount : '',   // 提现账号
      },
      isNew             : false,
      rules             : {
        withdrawalAccount : [{ required : true, trigger : 'blur', message : '请选择提现账户' }],
      },
      title             : '',
      dialogFormVisible : false,
    } );

    const show  = async ( row ) => {
      const loading = ElLoading.service(
        {
          fullscreen : true,
          lock       : true,
          text       : '加载中...',
        }
      );
      try {
        state.title    = '提现';
        state.form     = {
          uuid              : row.uuid,
          withdrawalAccount : '',
        };
        const { data } = await getWithdrawalAccount( { name : 'tron-main'/*row.name*/ } );
        for ( var v of data ) {
          const { data : info } = await getListenInfo( { name : v.bindListen } );
          v.balance             = '0';
          v.tokenBalance        = '0';
          if ( info.grpcUrl.indexOf( 'http' ) !== 0 ) {
            info.grpcUrl = 'https://' + info.grpcUrl;
          }
          switch ( info.coinType.toLowerCase() ) {
            case 'eth':
              await setTokenWeb3Rpc( info.grpcUrl );
              if ( info.tokenContract ) {
                state.balance      = await getWeb3TokenBalance(
                  info.tokenContract,
                  v.address
                );
                state.tokenBalance = web3.utils
                                         .toBN( v.balance )
                                         .div( web3.utils.toBN( Math.pow( 10, Number( info.tokenDecimals ) ) ) )
                                         .toNumber();
              }
              v.balance = await getWeb3Balance( v.address );
              break;
            case 'tron':
              setTronRpc( info.grpcUrl, info.apiKey );
              if ( info.tokenContract ) {
                v.balance      = await getTronTokenBalance(
                  info.tokenContract,
                  v.address
                );
                v.tokenBalance = web3.utils
                                     .toBN( v.balance )
                                     .div( web3.utils.toBN( Math.pow( 10, Number( info.tokenDecimals ) ) ) )
                                     .toNumber();
              }
              v.balance = await getTronBalance( v.address );
              v.balance = web3.utils
                              .toBN( v.balance )
                              .div( web3.utils.toBN( Math.pow( 10, 6 ) ) )
                              .toNumber();
              break;
          }
        }
        state.accounts          = data;
        state.dialogFormVisible = true;
        console.log( state.accounts );
      } catch ( e ) {
        loading.close();
      }
      loading.close();
    };
    const close = () => {
      state[ 'formRef' ].resetFields();
      state.isNew             = false;
      state.form              = {
        uuid              : '',
        withdrawalAccount : '',
      };
      state.dialogFormVisible = false;
    };
    const save  = async () => {
      const res = await withdrawal( state.form );
      if ( res.status === 200 ) {
        ElMessage.success( '提现成功' );
        close();
      } else {
        ElMessage.error( '提现失败' );
      }
    };

    return {
      ...toRefs( state ),
      show,
      log : console.log,
      close,
      save,
    };
  },
} );
</script>
