import Taro from '@tarojs/taro';

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

import Badge from '@/components/badge';
import { PREFIX } from '@/components/product-dialog/const';
import { PageUrl } from '@/constants/app';
import { CollectEventName } from '@/constants/event';
import { OrderStatus, OrderType, ProductType } from '@/constants/product';
import { SubscribeTempId } from '@/constants/subscribe';
import { ProductSpecResult } from '@/types/product';
import { logWithPrefix } from '@/utils/common';
import { collectEvent } from '@/utils/event';
import {
  isCancelPay,
  requestCreatePayInfo,
  requestOrderInfo,
  requestPayment,
  requestProductTypeList,
} from '@/utils/product';
import { navigateTo } from '@/utils/route';
import { postSubscribe, subscribeMessage } from '@/utils/subscribe';
import Toast from '@/utils/toast';

interface IProps {
  onConfirm: () => void;
  isCreateResume?: boolean;
}

// interface Item {
//   id: ProductSpecId;
//   title: string;
//   content: string;
//   buyOnlyContent?: string;
//   price: string;
//   amt: number;
//   badge?: string;
// }

// const LIST: Item[] = [
//   { id: ProductSpecId.WeeklyVIP, title: '非会员', content: '每日2次', price: '免费', amt: 0 },
//   {
//     id: ProductSpecId.DailyVIP,
//     title: '日会员',
//     content: '每日+10次',
//     buyOnlyContent: '每日12次',
//     price: '60播豆',
//     amt: 6,
//     badge: '限时体验',
//   },
//   {
//     id: ProductSpecId.WeeklyVIP,
//     title: '周会员',
//     content: '每日+10次',
//     buyOnlyContent: '每日12次',
//     price: '180播豆',
//     amt: 18,
//     badge: ' 超值',
//   },
// ];

const log = logWithPrefix('job-buy');
const SUBSCRIBE_ID = SubscribeTempId.SUBSCRIBE_VIP;

const subscribe = async () => {
  const result = await subscribeMessage([SUBSCRIBE_ID]);
  const success = result[SUBSCRIBE_ID] === 'accept';
  if (!success) {
    postSubscribe([SUBSCRIBE_ID], []);
    return;
  }
  postSubscribe([SUBSCRIBE_ID], [SUBSCRIBE_ID]);
};

export default function JobBuy(props: IProps) {
  const { onConfirm, isCreateResume } = props;
  const [productList, setProductList] = useState<ProductSpecResult[]>([]);
  const [selectItem, setSelectItem] = useState<ProductSpecResult | undefined>();

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

  const handleBuy = useCallback(async () => {
    log('handleBuy', selectItem);
    if (!selectItem) {
      Toast.error('请选择购买的产品');
      return;
    }
    try {
      Taro.showLoading();

      const { payOrderNo, createPayInfo } = await requestCreatePayInfo({
        type: OrderType.VIP,
        amt: selectItem.payPrice,
        productCode: ProductType.VIP,
        productSpecId: selectItem.productSpecId,
      });
      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();
      onConfirm();
    } catch (e) {
      Taro.hideLoading();
      Toast.error(isCancelPay(e) ? '取消购买' : '购买失败请重试');
      log('handleBuy error', e);
    }
  }, [selectItem, onConfirm]);

  const handleGetProductInfo = useCallback(async () => {
    const result = await requestProductTypeList(ProductType.VIP);
    setProductList(result);
    setSelectItem(result[0]);
  }, []);

  const handleResume = useCallback(() => {
    navigateTo(PageUrl.MaterialUploadVideo);
  }, []);

  useEffect(() => {
    handleGetProductInfo();
    collectEvent(CollectEventName.CREATE_ORDER_VIEW, { orderType: OrderType.VIP });
  }, []);

  return (
    <div className={`${PREFIX}__job-buy`}>
      {isCreateResume ? (
        <Fragment>
          <div className={`${PREFIX}__job-buy__header`}>
            <div>今日免费查看次数</div>
            <div className="highlight">已用完</div>
          </div>
          <div className={`${PREFIX}__job-buy__describe`}>
            <div>请</div>
            <div className="highlight">明日</div>
            <div>再来</div>
            <div> 或 </div>
            <div className="highlight">升级会员</div>
          </div>
        </Fragment>
      ) : (
        <Fragment>
          <div className={`${PREFIX}__job-buy__header`}>
            <div>开通会员即可查看联系方式</div>
          </div>
          <div className={`${PREFIX}__job-buy__describe`}>
            <div>完善模卡，每日可免费查看 </div>
            <div className="highlight" onClick={handleResume}>
              去完善
            </div>
          </div>
        </Fragment>
      )}
      <div className={`${PREFIX}__job-buy__container`}>
        {productList.map(item => {
          return (
            <div
              key={item.payPrice}
              className={classNames(`${PREFIX}__job-buy__item`, {
                selected: selectItem && item.payPrice === selectItem.payPrice,
                disabled: item.payPrice === 0,
              })}
              onClick={item.payPrice === 0 ? undefined : () => handleClickItem(item)}
            >
              <div className={classNames(`${PREFIX}__job-buy__item__title`, { free: item.payPrice === 0 })}>
                {item.title}
              </div>
              <div className={`${PREFIX}__job-buy__item__content`}>{item.contentSingle}</div>
              <div className={`${PREFIX}__job-buy__item__price`}>{item.showPrice}元</div>
              {item.badge && <Badge className={`${PREFIX}__job-buy__item__badge`} text={item.badge} />}
            </div>
          );
        })}
      </div>
      {selectItem && (
        <div className={`${PREFIX}__job-buy__hint`}>
          注：{selectItem?.title}有效期为
          <div className="highlight">
            支付后{selectItem?.expire > 1 ? `${selectItem.expire}天` : `${selectItem.expire * 24}小时`}
          </div>
        </div>
      )}
      <Button className={`${PREFIX}__job-buy__button`} disabled={!selectItem} onClick={handleBuy}>
        {`支付 ${selectItem?.showPrice} 元`}
      </Button>
      {/* <div className={`${PREFIX}__job-buy__tips`}>{`已选：${selectItem.title}，含进本地群服务`}</div> */}
    </div>
  );
}
