import { Image } from '@tarojs/components';

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

import { QrCodeType } from '@/constants/product';
import { requestCsQrCode } from '@/utils/product';

import './index.less';

interface IProps {
  type: QrCodeType;
  className?: string;
}

const PREFIX = 'qr-code';

function QrCode(props: IProps) {
  const { className, type } = props;
  const [src, setSrc] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);

  const handleLoad = useCallback(() => setLoading(false), []);

  const handleError = useCallback(() => setError(true), []);

  useEffect(() => {
    const request = async () => {
      try {
        const qrCode = await requestCsQrCode(type);
        qrCode ? setSrc(qrCode) : setError(true);
      } catch (e) {
        setError(true);
      }
    };
    request();
  }, [type]);

  return (
    <div className={classNames(PREFIX, className)}>
      {src && (
        <Image
          src={src}
          mode="aspectFit"
          onLoad={handleLoad}
          onError={handleError}
          className={`${PREFIX}__image`}
          showMenuByLongpress
        />
      )}
      {!error && (!src || loading) && <Loading className={`${PREFIX}__loading`} />}
      {error && <div className={`${PREFIX}__error`}>加载错误...</div>}
    </div>
  );
}

export default QrCode;
