import Taro from '@tarojs/taro';

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

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

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

const log = logWithPrefix('company-publish-job-buy');
const TEMP_IDS = [SubscribeTempId.UNREAD_MESSAGE_REMINDER, SubscribeTempId.NEW_MESSAGE_REMINDER];
interface Item {
  id: ProductSpecId;
  title: string;
  price: string;
  amt: number;
  contents: { content: string; highlight?: boolean }[];
  badge?: string;
}

const LIST: Item[] = [
  {
    id: ProductSpecId.BOSS_VIP_NEW_1,
    title: '展示一周',
    price: '480播豆',
    amt: 48,
    badge: '限时体验',
    contents: [
      { content: '-1个通告' },
      { content: '-每天可查看20个主播详情' },
      { content: '-每天可自主联系10个主播' },
      // { content: '-播络可代为联系20个主播（高成功率）', highlight: true },
      { content: '-有效期一周' },
    ],
  },
  {
    id: ProductSpecId.BOSS_VIP_NEW_2,
    title: '展示一月',
    price: '960播豆',
    amt: 96,
    badge: '五折',
    contents: [
      { content: '-1个通告' },
      { content: '-每天可查看20个主播详情' },
      { content: '-每天可自主联系10个主播' },
      // { content: '-播络可代为联系20个主播（高成功率）', highlight: true },
      { content: '-有效期一个月' },
    ],
  },
  // {
  //   id: ProductSpecId.BOSS_VIP_NEW_3,
  //   title: '季会员',
  //   price: '2680播豆',
  //   amt: 268,
  //   badge: '7折',
  //   contents: [
  //     { content: '-1个通告' },
  //     { content: '-每天可查看20个主播详情' },
  //     { content: '-每天可自主联系10个主播' },
  //     { content: '-播络可代为联系60个主播（高成功率）', highlight: true },
  //     { content: '-有效期3个月' },
  //   ],
  // },
];

const subscribe = async () => {
  const result = await subscribeMessage(TEMP_IDS);
  const successIds: SubscribeTempId[] = [];
  TEMP_IDS.forEach(id => {
    result[id] === 'accept' && successIds.push(id);
  });
  postSubscribe(TEMP_IDS, successIds);
};

export default function CompanyPublishJobBuy(props: IProps) {
  const { onNext } = props;
  const [selectItem, setSelectItem] = useState(LIST[0]);

  const handleClickItem = useCallback((newSelectItem: Item) => setSelectItem(newSelectItem), []);

  const handleBuy = useCallback(async () => {
    log('handleBuy');
    reportEvent(ReportEventId.CLICK_PAY_PUBLISH_JOB);
    try {
      Taro.showLoading();
      const { payOrderNo, createPayInfo } = await requestCreatePayInfo({
        type: OrderType.CompanyVip,
        amt: getOrderPrice(selectItem.amt),
        productCode: ProductType.BOSS_VIP_NEW,
        productSpecId: selectItem.id,
      });
      log('handleBuy payInfo', payOrderNo, createPayInfo);
      await requestPayment({
        timeStamp: createPayInfo.timeStamp,
        nonceStr: createPayInfo.nonceStr,
        package: createPayInfo.packageVal,
        signType: createPayInfo.signType,
        paySign: createPayInfo.paySign,
        success: () => subscribe(),
      });
      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);
    }
  }, [selectItem, onNext]);

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

  return (
    <div className={`${PREFIX}__company-publish-job-buy`}>
      <div className={`${PREFIX}__company-publish-job-buy__header`}>发认证通告限时折扣</div>
      <div className={`${PREFIX}__company-publish-job-buy__price-container`}>
        {LIST.map(item => (
          <div
            key={item.price}
            className={classNames(`${PREFIX}__company-publish-job-buy__item`, {
              selected: item.amt === selectItem.amt,
              disabled: item.amt === 0,
            })}
            onClick={item.amt === 0 ? undefined : () => handleClickItem(item)}
          >
            <div className={classNames(`${PREFIX}__company-publish-job-buy__item__title`, { free: item.amt === 0 })}>
              {item.title}
            </div>
            <div className={`${PREFIX}__company-publish-job-buy__item__price`}>{item.price}</div>
            {item.badge && <Badge className={`${PREFIX}__company-publish-job-buy__item__badge`} text={item.badge} />}
          </div>
        ))}
      </div>
      <div className={`${PREFIX}__company-publish-job-buy__divider`}>
        <div className={`${PREFIX}__company-publish-job-buy__divider__left-line`} />
        <div className={`${PREFIX}__company-publish-job-buy__divider__title`}>包含</div>
        <div className={`${PREFIX}__company-publish-job-buy__divider__right-line`} />
      </div>
      <div className={`${PREFIX}__company-publish-job-buy__contents`}>
        {selectItem.contents.map(i => (
          <div
            className={classNames(`${PREFIX}__company-publish-job-buy__content`, { highlight: i.highlight })}
            key={i.content}
          >
            {i.content}
          </div>
        ))}
      </div>
      <Button className={`${PREFIX}__company-publish-job-buy__button`} onClick={handleBuy}>
        {`支付${selectItem.amt}元`}
      </Button>
    </div>
  );
}
