import { defineComponent, onMounted, reactive, ref } from 'vue';
import { useFoxDialog } from '@/store/dialog';
import './index.less';
import CloseSvg from '@/assets/svg/dialog/close.svg';
import FoxSvg from '@/assets/svg/dialog/fox.svg';
import detectEthereumProvider from '@metamask/detect-provider';
import { MessagePlugin } from 'tdesign-vue-next';
import Loading from '../Loading';
import { useFoxWallet } from '@/store/FoxWallet';
export default defineComponent({
  setup(props) {
    const { $state: foxDialog } = useFoxDialog();
    // 钱包地址
    const { $state: userAddress } = useFoxWallet();
    const loading = ref(false);
    // 钱包列表
    const WalletList = reactive({
      list: [
        {
          icon: <FoxSvg></FoxSvg>,
          label: 'MetaMask Wallet',
          value: '',
        },
      ],
    });
    const dialogHead = () => {
      return <div>连接钱包</div>;
    };
    const closeIcon = () => {
      return <CloseSvg></CloseSvg>;
    };
    const getConnectFox = async (tooltip: boolean) => {
      // 这里是用户主动连接，临时存储到本地，刷新页面时自动赋值
      let eth: any = window;
      try {
        const accounts = await eth.ethereum.request({
          method: 'eth_requestAccounts',
        });
        if (accounts[0]) {
          userAddress.address = accounts[0];
          userAddress.MaskAddress = `${accounts[0].slice(
            0,
            6
          )}...${accounts[0].slice(
            accounts[0].length - 4,
            accounts[0].length
          )}`;
          window.sessionStorage.setItem('ConnectFox', 'true');
        }
        if (tooltip) {
          MessagePlugin.closeAll();
          MessagePlugin.success('连接成功');
        }
      } catch (e: any) {
        if (tooltip) {
          if (e.code == -32002) {
            MessagePlugin.closeAll();
            MessagePlugin.warning('连接请求已存在');
            return;
          }
          MessagePlugin.closeAll();
          MessagePlugin.warning('连接失败');
        }
        console.log(e);
      }
    };
    // 连接钱包
    const ToConnectWallet = async (item: any) => {
      try {
        loading.value = true;
        let provider = await detectEthereumProvider();
        loading.value = false;
        if (!provider) {
          MessagePlugin.warning('请先下载MetaMask插件');
          return;
        }
        // 连接钱包--主动连接--需要提示文字
        getConnectFox(true);
      } catch (e) {
        console.log(e);
        loading.value = false;
      }
    };
    onMounted(() => {
      // 自动连接--不显示提示文字
      getConnectFox(false);
    });
    return () => (
      <t-dialog
        v-model:visible={foxDialog.dialog}
        placement="center"
        attach="body"
        class="custom-connect-fox-dialog"
        footer={false}
        header={dialogHead}
        closeBtn={closeIcon}
      >
        <div class="fox-wallect-list">
          {WalletList.list.map((item: any) => (
            <div
              class="fox-wallect-list-li"
              onClick={ToConnectWallet.bind(this, item)}
            >
              {item.icon}
              <span class="text">{item.label}</span>
            </div>
          ))}
          <Loading v-show={loading.value}></Loading>
        </div>
      </t-dialog>
    );
  },
});
