import React, { useRef, useState } from 'react';
import Table, { ProColumns, ActionType } from '@/components/Table';
import { queryAddressList } from '@/services/eth';
import { fetchTableData } from '@/utils/table';
import CoinType from '@/constants/enum/coinType';
import AddAddressModal from './components/AddAddressModal';
import { AddAddress } from '@/services/eth';
import { initWeb3, walletSign } from '@/utils/web3';
import { message, Select } from 'antd';

const AddressList = () => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectValue, setSelectValue] = useState(CoinType.ETH);

  const tableRef = useRef<ActionType>();
  const columns: ProColumns<any>[] = [
    {
      title: '类型',
      dataIndex: 'coinType',
      hideInTable: true,
      initialValue: CoinType.ETH,
      renderFormItem: (item, { type, defaultRender, ...rest }, form) => {
        return (
          <Select
            options={[
              {
                label: 'ETH',
                value: CoinType.ETH,
              },
              {
                label: 'TRON',
                value: CoinType.TRON,
              },
            ]}
            onChange={(val) => {
              setSelectValue(val);
            }}
          />
        );
      },
    },
    {
      title: '备注',
      dataIndex: 'remarks',
      hideInSearch: true,
      width: '20%',
      // hideInSearch: true,
    },
    {
      title: '地址',
      dataIndex: 'address',
      hideInSearch: true,
      ellipsis: true,
    },

    {
      title: 'key',
      dataIndex: 'key',
      hideInSearch: true,
    },
  ];
  return (
    <div>
      <Table
        columns={columns}
        rowKey="id"
        actionRef={tableRef}
        toolBarActions={[
          {
            type: 'add',
            onConfirm: () => {
              setIsModalVisible(true);
            },
          },
        ]}
        request={async (params) => {
          return fetchTableData(queryAddressList, params);
        }}
      />
      <AddAddressModal
        visible={isModalVisible}
        onCancel={function () {
          setIsModalVisible(false);
        }}
        onOk={async function (val: any): Promise<void> {
          try {
            await initWeb3();
            const signInfo = await walletSign();
            val.key = signInfo.raw;
            val.sign = signInfo.sign;
            val.coinType = selectValue;
            const params = { ...val };
            await AddAddress(params);
            message.success('操作成功');
          } catch (e) {}
          setIsModalVisible(false);
        }}
      />
    </div>
  );
};

export default AddressList;
