import React, { useEffect, useRef, useState } from 'react';
import Table, { ProColumns, ActionType } from '@/components/Table';
import { message } from 'antd';
import AddNftContractModal from './components/AddNftContract';
import { getContractInfo } from '@/services/contract';
import { ContractType } from '@/constants/enum/contract';
import { deployContract, initWeb3 } from '@/utils/web3';
import { createNFTContract, getNFTContractList } from '@/services/nft';
import { fetchTableData } from '@/utils/table';

const Address: React.FC = () => {
  const tableRef = useRef<ActionType>();
  const [visible, setVisible] = useState(false);
  const [contractData, setContractData] = useState({});

  const columns: ProColumns<any>[] = [
    {
      title: '合约名称',
      dataIndex: 'token_name',
      width: '15%',
      hideInSearch: true,
    },
    {
      title: '合约单位',
      dataIndex: 'token_symbol',
      width: '15%',
      hideInSearch: true,
    },
    {
      title: '合约地址',
      dataIndex: 'address',
      hideInSearch: true,
      width: '50%',
    },
    {
      title: '描述',
      dataIndex: 'description',
      hideInSearch: true,
      ellipsis: true,
    },
  ];

  return (
    <div>
      <Table
        columns={columns}
        rowKey="id"
        search={false}
        actionRef={tableRef}
        toolBarActions={[
          {
            type: 'add',
            text: '新建NFT合约',
            onConfirm: async () => {
              const res = await getContractInfo({ erc: ContractType.NFT721 });
              if (res.bin != '') {
                setContractData(res);
                setVisible(true);
              } else {
                message.success('已有NFT合约');
              }
            },
          },
        ]}
        request={async (params) => {
          const res = await fetchTableData(getNFTContractList, params);
          return res;
        }}
      />
      <AddNftContractModal
        visible={visible}
        onCancel={function () {
          setVisible(false);
        }}
        onOk={async function (val: any): Promise<void> {
          try {
            await initWeb3();
            const res = await deployContract(contractData.abi, contractData.bin, [
              val.token_name,
              val.token_symbol,
            ]);
            val.address = res;
            await createNFTContract(val);
            message.success('添加成功');
            setVisible(false);
          } catch (e) {
            console.log(e);
            message.success('发生错误');
            setVisible(false);
          }
        }}
      />
    </div>
  );
};

export default Address;
