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 {
  buy_blindBox,
  IntervalCheckOrder,
  useCanNotBuy,
} from '@/utils/api/BlindBox';
import { useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
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 Payment = () => {
      if (!FoxWallet.to) {
        MessagePlugin.warning(t('raffle.Missingpayment'));
        return;
      }
      let eth: any = window;
      // 转换后的收款地址
      let MyNewAddress = FoxWallet.to.substring(2).padStart(64, '0');
      // 实际价格--props.price
      // 测试价格
      // let price = 0.01;
      // 转换后的数量
      let newPrice = (parseInt(props.info.price) * Math.pow(10, 18))
        .toString(16)
        .padStart(64, '0');
      // 小狐狸支付
      eth.ethereum
        .request({
          method: 'eth_sendTransaction',
          params: [
            {
              // 用户钱包地址
              from: FoxWallet.address,
              // 支付代币类型 BUSD
              to: '0xCC88e86AA0E589e18ff03fB9b0449468A1EF1f4B',
              // gas价格
              // gasPrice: "0x12a05f200",
              // gas: "0x16e360",
              // 交易数据十六进制  交易0xa9059cbb  目标钱包地址(我们的钱包地址)  交易金额（十六转换）
              data: '0xa9059cbb' + MyNewAddress + newPrice,
            },
          ],
        })
        .then((hash: string) => {
          // 交易hash
          if (hash) {
            UserHash.value = hash;
            // 发送充值信息
            recharge(hash, parseInt(props.info.price));
          }
        })
        .catch((e: any) => {
          console.log(e);
        });
      //
    };
    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>
              )}
              <span class="text">{t('raffle.onepurchase')}</span>
              <div class="open-link">
                <t-tooltip content={t('tips.invite')}>
                  <span onClick={openInviteDialog}>
                    <OpenSvg></OpenSvg>
                  </span>
                </t-tooltip>
              </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>
    );
  },
});
