import { defineComponent, PropType, ref } from 'vue';
import './index.less';
import CustomCountDown from '../CountDown';
import OpenSvg from '@/assets/svg/raffle/open.svg';
import { useFoxDialog } from '@/store/dialog';
import { useFoxWallet } from '@/store/FoxWallet';
import { MessagePlugin } from 'tdesign-vue-next';
import InviteDialog from '../InviteDialog';
import { getCurrentDevice } from '@/utils/tool';
import {
  buy_blindBox,
  IntervalCheckOrder,
  useCanNotBuy,
} from '@/utils/api/BlindBox';
import { useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { EtherPay } from '@/utils/ethers';
export default defineComponent({
  props: {
    info: {
      type: Object as PropType<any>,
      default: {},
    },
  },
  setup(props) {
    const { t } = useI18n();
    const route = useRoute();
    const RouteParams = route.params;
    // 邀请弹窗状态
    const InviteVisible = ref(false);
    let InterVal: any = null;
    // 用户hash
    const UserHash = ref('');
    const { $state: foxDialog } = useFoxDialog();
    const { $state: FoxWallet } = useFoxWallet();
    // 打开连接弹窗
    const openDialog = () => {
      foxDialog.dialog = true;
    };
    // 检测充值到账
    const Check = async () => {
      try {
        let res: any = await IntervalCheckOrder({
          hash: UserHash.value,
          price: props.info.price,
          form: FoxWallet.address,
        });
        if (res.data == true) {
          closeInterval();
          MessagePlugin.success(t('raffle.PurchaseSuccess'));
        }
      } catch (e) {
        console.log(e);
      }
    };
    // 开启轮询
    const openCheckInterval = () => {
      InterVal = window.setInterval(() => {
        Check();
      }, 3000);
    };
    // 关闭轮询
    const closeInterval = () => {
      if (InterVal) {
        window.clearInterval(InterVal);
      }
    };
    // 发起交易
    const recharge = async (hash: string = '', price: number = 0) => {
      let params: any = {
        address: FoxWallet.address,
        hash: hash,
        id: props.info.id,
      };
      // 判断是否为分享的链接
      if (
        RouteParams.code &&
        RouteParams.id &&
        typeof RouteParams.id == 'string'
      ) {
        params.invite_code = RouteParams.code;
        params.Invitees_box_id = parseFloat(RouteParams.id);
      }
      let res: any = await buy_blindBox(params);
      if (res.code == 0) {
        // 开启轮询
        MessagePlugin.info(t('raffle.ChargingRecord'));
        if (UserHash.value) {
          openCheckInterval();
        }
      }
    };
    const send_token = async () => {
      let hash: any = await EtherPay(FoxWallet.to, props.info.price);
      if (hash) {
        UserHash.value = hash;
        // 发送充值信息
        recharge(hash, parseInt(props.info.price));
      }
    };
    // 支付
    const Payment = () => {
      if (!FoxWallet.to) {
        MessagePlugin.warning(t('raffle.Missingpayment'));
        return;
      }
      // ethers
      send_token();
    };
    const getUserBuyStatus = async () => {
      try {
        let res: any = await useCanNotBuy({
          address: FoxWallet.address,
          id: props.info.id,
        });
        if (res.data === true) {
          return true;
        }
        return false;
      } catch (e) {
        console.log(e);
        return false;
      }
    };
    // 打开邀请弹窗
    const openInviteDialog = () => {
      InviteVisible.value = true;
    };
    // 立即购买
    const Buy_now = async () => {
      const { info } = props;
      // 地址
      if (!FoxWallet.address) {
        MessagePlugin.warning(t('header.plconnect'));
        return;
      }
      if (info.countdown <= 0) {
        MessagePlugin.warning(t('raffle.hasEnded'));
        return;
      }
      // 能否购买
      let cannot = await getUserBuyStatus();
      if (cannot) {
        Payment();
      } else {
        MessagePlugin.closeAll();
        MessagePlugin.warning(t('raffle.Unableto'));
      }
    };
    return () => (
      <div class="custom-card-detail">
        <div class="detail-head">
          <div class="detail-head-img">
            <img src={props.info.project_icon} alt="" />
          </div>
          <div class="detail-head-content">
            <div class="title">{props.info.projectName}</div>
            <div class="count-down-box">
              <div class="label">{t('raffle.PurchaseCountdown')}</div>
              <div class="value">
                <CustomCountDown time={props.info.countdown}></CustomCountDown>
              </div>
            </div>
            <div class="price-and-buynum">
              <div class="price-box">
                <div class="label">{t('raffle.price')}</div>
                <div class="value">{props.info.price} RESDAO</div>
              </div>
              <div class="price-box margin">
                <div class="label">{t('raffle.Numbercurrent')}</div>
                <div class="value">
                  {props.info.buy_num}/{props.info.max_participants_num}
                </div>
              </div>
            </div>
            <div class="line"></div>
            <div class="price-and-prize">
              <div>
                <span>{t('raffle.Youwillspend')}：</span>
                {props.info.price}RESDAO
              </div>
              <div>
                <span class="text2">{t('raffle.Winprize')}：</span>
                {props.info.price * 3}RESDAO
              </div>
            </div>
            <div class="content-wallet-tooltip">
              {FoxWallet.address ? (
                <button class="connect-wallet" onClick={Buy_now}>
                  {t('raffle.BuyNow')}
                </button>
              ) : (
                <button class="connect-wallet" onClick={openDialog}>
                  {t('header.connectWallet')}
                </button>
              )}
              <div class="tooltip-right">
                <span class="text">{t('raffle.onepurchase')}</span>
                <div class="open-link">
                  {getCurrentDevice() ? (
                    <span onClick={openInviteDialog}>
                      <OpenSvg></OpenSvg>
                    </span>
                  ) : (
                    <t-tooltip content={t('tips.invite')}>
                      <span onClick={openInviteDialog}>
                        <OpenSvg></OpenSvg>
                      </span>
                    </t-tooltip>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="content-line"></div>
        <div class="custom-Rules">
          <div class="title">{t('raffle.rule')}</div>
          <div class="value" innerHTML={props.info.rules}></div>
        </div>
        <InviteDialog
          v-model={InviteVisible.value}
          id={props.info.id}
        ></InviteDialog>
      </div>
    );
  },
});
