<template>
  <div class="fox-dropdown" v-if="Cookie">
    <ClientOnly>
      <t-popup trigger="click" placement="bottom">
        <div class="fox-info">
          {{ hasdisabled ? AfterConnection : defaultTitle }}
        </div>
        <template #content>
          <div class="s-header-fox-box">
            <div class="fox-title">{{ $t('header.FoxwalletTitle') }}</div>
            <div class="wallet-Connect">
              <t-button class="center-btn-box" @click="connectionFox">
                <template #icon>
                  <img :src="Imgs.FoxSvg" alt="" class="icon" />
                </template>
                {{ $t('header.FoxwalletTitle2') }}
              </t-button>
            </div>
          </div>
        </template>
      </t-popup>
    </ClientOnly>
  </div>
</template>

<script lang="ts" setup>
import { MessagePlugin } from 'tdesign-vue-next';
import detectEthereumProvider from '@metamask/detect-provider';
import { useI18n } from 'vue-i18n';
const i18n = useI18n();
let provider;
if (process.client) {
  provider = detectEthereumProvider();
}
const Imgs = {
  FoxSvg: '/images/svg/header/fox.svg',
};
// 用户token
const Cookie = useCookie('userCookie');
const hasdisabled = ref(false);
const defaultTitle = computed(() => i18n.t('header.Foxwalletbutton'));
const UserAddress = useUserAddress();
// 连接钱包后展示的文字
const AfterConnection = ref('');
// 用户原始交易地址
const account = ref('');
onBeforeMount(() => {
  // 是否可以连接
  // console.log(ethereum.isConnected());
  let ConnectFox = window.sessionStorage.getItem('ConnectFox');
  let eth: any = window;
  if (ConnectFox === 'true' && eth.ethereum?.isConnected()) {
    // 这里自动连接钱包，不需要存储本地
    hasdisabled.value = true;
    getConnectFox();
  }
});

const connectionFox = () => {
  if (!provider) {
    MessagePlugin.warning('请先下载MetaMask');
    return;
  }
  // 连接钱包
  getConnectFox();
};
const getConnectFox = async () => {
  if (!Cookie.value) {
    MessagePlugin.closeAll();
    MessagePlugin.warning('请先登录');
    return;
  }
  // 这里是用户主动连接，临时存储到本地，刷新页面时自动赋值
  let eth: any = window;
  try {
    const accounts = await eth.ethereum.request({
      method: 'eth_requestAccounts',
    });
    if (accounts[0]) {
      account.value = accounts[0];
      AfterConnection.value = `${accounts[0].slice(0, 6)}...${accounts[0].slice(
        accounts[0].length - 4,
        accounts[0].length
      )}`;
      window.sessionStorage.setItem('ConnectFox', 'true');
      // 禁用下拉菜单
      setTimeout(() => {
        hasdisabled.value = true;
      }, 100);
    }
    UserAddress.value = account.value;
  } catch (e) {
    MessagePlugin.warning(i18n.t('MessagePlugin.Foxwallet'));
    hasdisabled.value = false;
    return;
  }
};
</script>

<style lang="less">
@import '@/style/flex.less';
// dropdown挂载在根元素
.s-header-fox-box {
  width: 240px;
  padding: 6px 0;
  .fox-title {
    padding: 0 0 6px 6px;
    font-weight: bold;
    user-select: none;
  }
  .wallet-Connect {
    .t-button {
      width: 100%;
      background-color: var(--td--main-btn-color-1);
      border: none;
      .icon {
        padding-right: 8px;
      }
    }
  }
}
</style>
<style lang="less" scoped>
.fox-dropdown {
  margin-right: 20px;
  user-select: none;
  .fox-info {
    cursor: pointer;
    white-space: nowrap;
    padding: 0 20px;
    height: 34px;
    border: 1px solid var(--td--main-btn-color-1);
    border-radius: 4px;
    line-height: 34px;
    text-align: center;
    font-weight: bold;
    color: var(--td--main-btn-color-1);
  }
}
</style>
