import Taro from '@tarojs/taro';

import { Dialog } from '@taroify/core';
import { useCallback, useEffect, useRef, useState } from 'react';

import { DialogStatus, PREFIX } from '@/components/product-dialog/const';
import QrCodeContent from '@/components/product-dialog/steps-ui/common-qr-code';
import GroupBuy from '@/components/product-dialog/steps-ui/group-buy';
import GroupBuySuccess from '@/components/product-dialog/steps-ui/group-buy-success';
import ContactWithGroup from '@/components/product-dialog/steps-ui/job-contact-with-group';
import UnableUnlockContent from '@/components/product-dialog/steps-ui/job-unable';
import { ProductType, QrCodeType } from '@/constants/product';
import { GroupDetail } from '@/types/group';
import { JobDetails } from '@/types/job';
import { copy, logWithPrefix } from '@/utils/common';
import { getConnectCustomerServiceText, requestGroupDetail } from '@/utils/group';
import { requestProductUseRecord, requestProductBalance, requestUseProduct } from '@/utils/product';
import Toast from '@/utils/toast';

import '../index.less';

interface IProps {
  jobDetail: JobDetails;
  onClose: (opened: boolean) => void;
}

const log = logWithPrefix('product-job-with-group');

function ProductJobWithGroupDialog(props: Omit<IProps, 'visible'>) {
  const { jobDetail, onClose } = props;
  const [status, setStatus] = useState<DialogStatus>(DialogStatus.LOADING);
  const [addGroupTime, setAddGroupTime] = useState(0);
  const [groupDetail, setGroupDetail] = useState<GroupDetail | null>(null);
  const initRef = useRef(() => {});

  const handleCloseDialog = useCallback(() => {
    onClose(false);
  }, [onClose]);

  const handleCopyText = useCallback(async () => {
    if (!groupDetail) {
      return;
    }
    const text = getConnectCustomerServiceText(jobDetail, groupDetail);
    await copy(text);
  }, [jobDetail, groupDetail]);

  const handleWithGroupConfirm = useCallback(
    async (dialogStatus: DialogStatus) => {
      if (!groupDetail) {
        return;
      }
      switch (dialogStatus) {
        case DialogStatus.JOB_CONTACT_INVITE_GROUP: {
          try {
            const text = getConnectCustomerServiceText(jobDetail, groupDetail);
            await Promise.all([
              copy(text),
              requestUseProduct(ProductType.AddGroup, { blGroupId: groupDetail.blGroupId }),
            ]);
            setStatus(DialogStatus.GROUP_QR_CODE);
          } catch (e) {
            Toast.error('出错了，请重试');
          }
          break;
        }
        case DialogStatus.JOB_CONTACT_NEED_BUY_GROUP: {
          setStatus(DialogStatus.GROUP_BUY);
          break;
        }
        default:
          break;
      }
    },
    [jobDetail, groupDetail]
  );

  const handleClickBuy = useCallback(async (time: number) => {
    setAddGroupTime(time);
    setStatus(DialogStatus.GROUP_BUY_SUCCESS);
  }, []);

  const handleClickBuySuccess = useCallback(async () => {
    setStatus(DialogStatus.JOB_CONTACT_INVITE_GROUP);
  }, []);

  useEffect(() => {
    initRef.current = async () => {
      const handleGroup = async () => {
        const detail = await requestGroupDetail(jobDetail.blGroupId);
        setGroupDetail(detail);
        // if (1 < 2) {
        //   setStatus(DialogStatus.JOB_CONTACT_INVITE_GROUP);
        //   return;
        // }
        // 当前群之前解锁过，直接显示二维码页面
        const result = await requestProductUseRecord(ProductType.AddGroup, { blGroupId: jobDetail.blGroupId });
        if (result) {
          const text = getConnectCustomerServiceText(jobDetail, detail);
          await copy(text);
          setStatus(DialogStatus.GROUP_QR_CODE);
          return;
        }
        // 否则：如果有解锁次数，显示是否确定消费。无解锁次数，显示不无次数 UI
        const [time] = await requestProductBalance(ProductType.AddGroup);
        if (time <= 0) {
          setStatus(DialogStatus.JOB_CONTACT_NEED_BUY_GROUP);
        } else {
          setAddGroupTime(time);
          setStatus(DialogStatus.JOB_CONTACT_INVITE_GROUP);
        }
      };
      const handleJob = async () => {
        // 通告是否已经报单过
        const result = await requestProductUseRecord(ProductType.GetJob, { jobId: jobDetail.id });
        if (result) {
          // 报单过走加群流程
          await handleGroup();
          return;
        }
        // 自动报单
        const [time] = await requestProductBalance(ProductType.GetJob);
        if (time <= 0) {
          setStatus(DialogStatus.JOB_UNABLE_UNLOCK);
        } else {
          await requestUseProduct(ProductType.GetJob, { jobId: jobDetail.id });
          // 报单后走加群流程
          await handleGroup();
        }
      };
      try {
        Taro.showLoading();
        await handleJob();
      } catch (e) {
        Toast.error('出错了，请重试');
        handleCloseDialog();
      } finally {
        Taro.hideLoading();
      }
    };
  }, [jobDetail, handleCloseDialog]);

  useEffect(() => {
    initRef.current();
  }, []);

  log('render status', status);

  if (status === DialogStatus.LOADING) {
    return null;
  }

  return (
    <Dialog className={PREFIX} onClose={onClose} open>
      <Dialog.Content>
        {status === DialogStatus.JOB_UNABLE_UNLOCK && <UnableUnlockContent onConfirm={handleCloseDialog} />}
        {status === DialogStatus.GROUP_QR_CODE && (
          <QrCodeContent type={QrCodeType.ConnectCustomerService} onClickCopy={handleCopyText} />
        )}
        {[DialogStatus.JOB_CONTACT_INVITE_GROUP, DialogStatus.JOB_CONTACT_NEED_BUY_GROUP].includes(status) && (
          <ContactWithGroup
            status={status}
            publisherAcctNo={jobDetail.publisher}
            inviteTime={addGroupTime}
            imGroupNick={groupDetail?.imGroupNick || ''}
            onConfirm={handleWithGroupConfirm}
          />
        )}
        {status === DialogStatus.GROUP_BUY && <GroupBuy source="job-detail" onConfirm={handleClickBuy} />}
        {status === DialogStatus.GROUP_BUY_SUCCESS && (
          <GroupBuySuccess unlockTime={addGroupTime} onConfirm={handleClickBuySuccess} />
        )}
      </Dialog.Content>
    </Dialog>
  );
}

export default ProductJobWithGroupDialog;
