<template>
  <div class="eth-address-container">
    <el-form>
      <div :span="12">
        <el-form :inline="true" :model="queryForm" @submit.prevent style="padding: 20px;">
          <el-form-item>
            <el-select v-model="token" placeholder="请选择代币">
              <el-option
                v-for="(v, i) in tokenList"
                :key="i"
                :label="v.network + ' - ' + v.symbol"
                :value="i"
              >
                {{ v.network + ' - ' + v.symbol }}
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button :icon="Search" type="primary" @click="queryData">
              查询
            </el-button>
            <el-button :icon="Plus" type="primary" @click="handleEdit">
              添加
            </el-button>
            <el-button :icon="Plus" type="primary" @click="exportExcel">
              导出Excel
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-form>

    <el-table v-loading="listLoading" :data="list">
      <el-table-column
        align="center"
        label="备注"
        prop="alias"
        show-overflow-tooltip
        width="200"
      />
      <el-table-column
        align="center"
        label="地址"
        prop="address"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="余额"
        prop="balance"
        show-overflow-tooltip
        width="200"
      />
      <el-table-column
        align="center"
        label="key"
        prop="key"
        show-overflow-tooltip
      />
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.page"
      :layout="layout"
      :page-size="queryForm.size"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <edit ref="editRef" @fetch-data="fetchData"/>
  </div>
</template>

<script>
import { defineComponent, onMounted, reactive, toRefs } from 'vue';
import { Delete, Plus, Search }                         from '@element-plus/icons';
import { getAddressList }                               from '@/apis/address';
import Edit                                             from './components/AddressEdit';
import { getTokenData }                                 from '@/apis/token';
import { getTronBalance }                               from '@/apis/wallet/tronweb';
import {
  getWeb3Balance,
  getWeb3TokenBalance,
  setTokenWeb3Rpc,
  web3,
}                                                       from '@/apis/wallet/web3';
import { exportExcel }                                  from '@/utils/excel';

export default defineComponent( {
  name       : 'EthAddress',
  components : { Edit },
  setup () {
    const state = reactive( {
      editRef     : null,
      list        : [],
      listLoading : true,
      layout      : 'total, sizes, prev, pager, next, jumper',
      total       : 0,
      selectRows  : '',
      tokenList   : [],
      token       : 0,
      queryForm   : {
        page      : 1,
        size      : 20,
        coin_type : 'eth',
      },
    } );

    const setSelectRows       = ( val ) => {
      state.selectRows = val;
    };
    const handleSizeChange    = ( val ) => {
      state.queryForm.size = val;
      fetchData();
    };
    const handleCurrentChange = ( val ) => {
      state.queryForm.page = val;
      fetchData();
    };
    const queryData           = () => {
      state.queryForm.page = 1;
      fetchData();
    };
    const handleEdit          = ( row ) => {
      if ( row.id ) {
        state.editRef.showEdit( row );
      } else {
        state.editRef.showEdit();
      }
    };
    const fetchData           = async () => {
      state.listLoading = true;
      try {
        const {
                data : { list, count },
              }     = await getAddressList( state.queryForm );
        const token = state.tokenList && state.tokenList[ state.token ];
        if ( token ) {
          setTokenWeb3Rpc( token.rpcUrl );
        }
        await Promise.all(
          list.map( async ( v ) => {
            v.balance = '';
            if ( token ) {
              if ( token.contract ) {
                v.balance = await getWeb3TokenBalance(
                  token.contract,
                  v.address
                );
                v.balance = web3.utils
                                .toBN( v.balance )
                                .div( web3.utils.toBN( Math.pow( 10, Number( token.decimals ) ) ) )
                                .toNumber();
              } else {
                v.balance = await getWeb3Balance( v.address );
              }
            }
          } )
        );
        state.list  = list;
        state.total = count;
      } catch ( e ) {
        console.log( e );
      }
      state.listLoading = false;
    };

    const getTokenList = async () => {
      state.tokenList = await getTokenData( 'eth' );
    };

    const _exportExcel = async () => {
      if ( state.list.length === 0 ) {
        return;
      }
      exportExcel(
        [
          ['address', 'key', 'alias'],
          ...state.list.map( ( e ) => [e.address, e.key, e.alias] ),
        ],
        'eth_address'
      );
    };
    onMounted( async () => {
      await getTokenList();
      fetchData();
    } );

    return {
      ...toRefs( state ),
      setSelectRows,
      handleEdit,
      handleSizeChange,
      handleCurrentChange,
      queryData,
      fetchData,
      exportExcel : _exportExcel,
      Delete,
      Plus,
      Search,
    };
  },
} );
</script>
