import Taro from '@tarojs/taro';

import { Button } from '@taroify/core';
import { useCallback, useEffect } from 'react';

import Badge from '@/components/badge';
import { PREFIX } from '@/components/product-dialog/const';
import { CollectEventName } from '@/constants/event';
import { OrderStatus, OrderType, ProductSpecId, ProductType } from '@/constants/product';
import { logWithPrefix } from '@/utils/common';
import { collectEvent } from '@/utils/event';
import { getOrderPrice, isCancelPay, requestCreatePayInfo, requestOrderInfo, requestPayment } from '@/utils/product';
import Toast from '@/utils/toast';

interface IProps {
  onNext: () => void;
}

const log = logWithPrefix('publish-job-buy');
const PRICE = 48;

export default function PublishJobBuy(props: IProps) {
  const { onNext } = props;

  const handleBuy = useCallback(async () => {
    log('handleBuy');
    try {
      Taro.showLoading();
      const { payOrderNo, createPayInfo } = await requestCreatePayInfo({
        type: OrderType.BossVip,
        amt: getOrderPrice(PRICE),
        // amt: PRICE,
        // amt: 1,
        productCode: ProductType.BossVip,
        productSpecId: ProductSpecId.BossVip,
      });
      log('handleBuy payInfo', payOrderNo, createPayInfo);
      await requestPayment({
        timeStamp: createPayInfo.timeStamp,
        nonceStr: createPayInfo.nonceStr,
        package: createPayInfo.packageVal,
        signType: createPayInfo.signType,
        paySign: createPayInfo.paySign,
      });
      const { status } = await requestOrderInfo({ payOrderNo });
      log('handleBuy orderInfo', status);
      if (status !== OrderStatus.Success) {
        throw new Error('order status error');
      }
      Taro.hideLoading();
      onNext();
    } catch (e) {
      Taro.hideLoading();
      Toast.error(isCancelPay(e) ? '取消购买' : '购买失败请重试');
      log('handleBuy error', e);
    }
  }, [onNext]);

  useEffect(() => {
    collectEvent(CollectEventName.CREATE_ORDER_VIEW, { orderType: OrderType.BossVip, source: 'user-page' });
  }, []);

  return (
    <div className={`${PREFIX}__publish-job-buy`}>
      <div className={`${PREFIX}__publish-job-buy__header`}>发通告限时折扣</div>

      <div className={`${PREFIX}__publish-job-buy__price-container`}>
        <div className={`${PREFIX}__publish-job-buy__price`}>{PRICE}</div>
        <div>元</div>
        <Badge className={`${PREFIX}__publish-job-buy__badge`} text="7.1折" />
      </div>
      <div className={`${PREFIX}__publish-job-buy__tips`}>原价：68元/月</div>
      <Button className={`${PREFIX}__publish-job-buy__button`} onClick={handleBuy}>
        立即支付
      </Button>
    </div>
  );
}
