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 JobBuy from '@/components/product-dialog/steps-ui/job-buy';
import ContactCustomerService from '@/components/product-dialog/steps-ui/job-contact-customer';
import ContactDirect from '@/components/product-dialog/steps-ui/job-contact-direct';
import UnableUnlockContent from '@/components/product-dialog/steps-ui/job-unable';
import { DeclarationType, ProductType } from '@/constants/product';
import { JobDetails } from '@/types/job';
import { ProductInfo } from '@/types/product';
import { logWithPrefix } from '@/utils/common';
import {
  requestProductUseRecord,
  requestProductBalance,
  requestUseProduct,
  requestAllBuyProduct,
} from '@/utils/product';
import Toast from '@/utils/toast';

import '../index.less';

interface IProps {
  data: JobDetails;
  onClose: () => void;
}

const PRODUCT_CODE = ProductType.VIP;
const log = logWithPrefix('product-job-dialog');

function ProductJobDialog(props: Omit<IProps, 'visible'>) {
  const { data, onClose } = props;
  const [status, setStatus] = useState<DialogStatus>(DialogStatus.LOADING);
  const [publisherAcctNo, setPublisherAcctNo] = useState<string>('');
  const initRef = useRef(() => {});

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

  const handleAfterBuy = useCallback(async () => {
    const time = await requestProductBalance(PRODUCT_CODE);
    if (time <= 0) {
      Toast.error('发生错误请重试');
      onClose();
      return;
    }
    const productInfo = await requestUseProduct(PRODUCT_CODE, { jobId: data.id });
    const declarationTypeResult = productInfo.declarationTypeResult;
    if (declarationTypeResult?.type === DeclarationType.Direct && declarationTypeResult.publisherAcctNo) {
      setStatus(DialogStatus.JOB_CONTACT_DIRECT);
      setPublisherAcctNo(declarationTypeResult.publisherAcctNo);
    } else {
      setStatus(DialogStatus.JOB_CONTACT_CS);
    }
  }, [data, onClose]);

  const handleReport = useCallback(() => {
    log('report', data.id);
  }, [data]);

  useEffect(() => {
    initRef.current = async () => {
      const handleContact = (declarationTypeResult?: ProductInfo['declarationTypeResult']) => {
        if (declarationTypeResult?.type === DeclarationType.Direct && declarationTypeResult.publisherAcctNo) {
          setStatus(DialogStatus.JOB_CONTACT_DIRECT);
          setPublisherAcctNo(declarationTypeResult.publisherAcctNo);
        } else {
          setStatus(DialogStatus.JOB_CONTACT_CS);
        }
      };
      try {
        Taro.showLoading();
        // if (1 < 2) {
        //   setStatus(DialogStatus.JOB_CONTACT_CS);
        //   return;
        // }
        const result = await requestProductUseRecord(PRODUCT_CODE, { jobId: data.id });
        log('requestProductUseRecord result', result);
        if (result) {
          handleContact(result.declarationTypeResult);
          return;
        }
        const time = await requestProductBalance(PRODUCT_CODE);
        if (time <= 0) {
          const allowBuy = await requestAllBuyProduct(PRODUCT_CODE);
          setStatus(allowBuy ? DialogStatus.JOB_BUY : DialogStatus.JOB_UNABLE_UNLOCK);
        } else {
          const productInfo = await requestUseProduct(PRODUCT_CODE, { jobId: data.id });
          handleContact(productInfo.declarationTypeResult);
        }
      } catch (e) {
        Toast.error('出错了，请重试');
        handleCloseDialog();
      } finally {
        Taro.hideLoading();
      }
    };
  }, [data, handleCloseDialog]);

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

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

  return (
    <Dialog className={PREFIX} onClose={onClose} open>
      <Dialog.Content>
        {status === DialogStatus.JOB_CONTACT_CS && <ContactCustomerService onAfterConfirm={handleCloseDialog} />}
        {status === DialogStatus.JOB_CONTACT_DIRECT && (
          <ContactDirect publisherAcctNo={publisherAcctNo} onAfterConfirm={handleCloseDialog} onReport={handleReport} />
        )}
        {status === DialogStatus.JOB_BUY && <JobBuy onConfirm={handleAfterBuy} />}
        {status === DialogStatus.JOB_UNABLE_UNLOCK && <UnableUnlockContent onConfirm={handleCloseDialog} />}
      </Dialog.Content>
    </Dialog>
  );
}

export default ProductJobDialog;
