/* eslint-disable @typescript-eslint/no-unused-expressions */
import Icon, { PlusOutlined, LoadingOutlined } from '@ant-design/icons';
import { Upload, message } from 'antd';
import React, { useEffect, useState } from 'react';
import styles from './uploadImg.module.less';
import { review, deleteIcon } from './icon';
import schema from './schema';
import FormItem from '../FormItem/FormItem';
import Preview from './preview';
import { ChangeImgUrl, getItemProps } from '../../utils';
import Loading from '../Loading';
import OCR from '../../utils/ocr';
import { zipImg, zipImg10M } from '../../utils/zipImg';
import ImagePreveEdit from '../ImagePreveEdit/index';
const UploadImg = (item: any) => {
  const data: any = getItemProps(schema, item);
  const {
    UploadProps,
    otherProps,
    componentType,
    FormItemProps,
    beforeUploadRules,
    callback,
    Type,
    form,
    ocr,
  } = data;
  const [imageUrl, setImageUrl] = useState<string>('');
  const [ocrLoading, setOcrLoading] = useState(false);
  const [loading, setLoading] = useState(false);
  const { uploadText, imageUrl: _imageUrl } = otherProps;
  const [isPreview, setIsPreview] = useState(false);
  useEffect(() => {
    _imageUrl
      ? (setImageUrl(_imageUrl),
        form && form.setFieldValue(FormItemProps?.name, _imageUrl))
      : Type === 'upload'
      ? null
      : setImageUrl(`${BASE_IMG}79770e20-06eb-4375-b91a-724ea677655e.jpg`);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [_imageUrl]);

  const UploadButton = () => {
    return (
      <div className={styles.U_B_Wapper}>
        <div className={styles.Up_Btn}>
          {loading ? (
            <LoadingOutlined />
          ) : (
            <>
              <PlusOutlined style={{ fontSize: '18px', margin: '2px 0' }} />
              {uploadText ? (
                <div style={{ fontSize: '12px' }}>{uploadText}</div>
              ) : null}
            </>
          )}
        </div>
      </div>
    );
  };

  const AfterButon = () => {
    return (
      <div
        className={styles.U_B_Wapper}
        onClick={e => {
          e.stopPropagation();
        }}
      >
        <img src={ChangeImgUrl(imageUrl)} alt="" style={{ height: '100%' }} />
        <div className={styles.Up_Btn_2}>
          <Icon component={review} onClick={() => setIsPreview(true)} />
          {Type === 'upload' ? (
            <Icon
              onClick={() => {
                form && form?.setFieldValue(FormItemProps?.name, '');
                setImageUrl('');
              }}
              component={deleteIcon}
            />
          ) : null}
        </div>
      </div>
    );
  };

  const beforeUpload = (file: any) => {
    const { fileSize } = beforeUploadRules;
    const isLt2M = file.size / 1024 / 1024 < fileSize;
    if (!isLt2M) {
      message.error(`图片大小不能超过${fileSize}MB!`);
    }
    return isLt2M;
  };

  const handleChange = async (fileInput: any): Promise<any> => {
    const { file } = fileInput;
    if (file.status === 'uploading') {
      setLoading(true);
      return '';
    }
    if (file.status === 'done') {
      let url = file.response.data;
      let res: any = null;
      let zipUrl = '';

      if (ocr) {
        await setOcrLoading(true);
        if (file.size > 1024 * 1024 * 6) {
          const zip = await zipImg10M(file);
          zipUrl = zip.data;
        }
        res = await OCR({
          code: ocr,
          facePhotoUrl: zipUrl ? ChangeImgUrl(zipUrl) : ChangeImgUrl(url),
        });
        if (res?.code === 0) {
          if (typeof res.data === 'string' || res.data === null) {
            if (file.size > 1024 * 1024 * 6) {
              message.error('ocr识别失败！');
            } else {
              const zOcr = await zipImg(file, ocr, true);
              res = zOcr;
            }
          } else {
            message.success('ocr识别成功！');
          }
        } else {
          message.error('ocr识别失败！');
        }
        await setOcrLoading(false);
      }
      setLoading(false);
      setImageUrl(url);
      callback &&
        callback({
          url,
          ocr: {
            data: res,
          },
        });
      return '';
    }
  };
  return (
    <>
      {isPreview ? (
        FormItemProps?.previewType === 'edit' ? (
          <ImagePreveEdit
            visible={isPreview}
            setOpen={setIsPreview}
            src={ChangeImgUrl(imageUrl)}
          />
        ) : (
          <Preview
            isPreview={isPreview}
            setIsPreview={setIsPreview}
            imageUrl={ChangeImgUrl(imageUrl)}
          />
        )
      ) : null}
      {componentType === 'FormItem' ? (
        <FormItem
          label={FormItemProps?.label}
          style={FormItemProps?.style}
          required={FormItemProps?.required}
          className="kx_UploadImg"
        >
          {ocrLoading ? <Loading tip={'ocr识别中...'} /> : null}
          <FormItem
            noStyle
            name={FormItemProps?.name}
            rules={
              FormItemProps?.required
                ? [
                    {
                      required: true,
                      message: `请上传${FormItemProps?.label || '图片'}`,
                    },
                  ]
                : []
            }
            valuePropName={FormItemProps.name}
            getValueFromEvent={(info: any) => {
              if (info.file.status === 'done') {
                return info.file.response.data;
              }
            }}
          >
            <Upload
              {...UploadProps}
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {imageUrl ? <AfterButon /> : <UploadButton />}
            </Upload>
          </FormItem>
          {beforeUploadRules?.tips ? (
            <div className={styles.tips}>{beforeUploadRules?.tips}</div>
          ) : null}
        </FormItem>
      ) : (
        <Upload
          {...UploadProps}
          beforeUpload={beforeUpload}
          onChange={handleChange}
        >
          {imageUrl ? <AfterButon /> : <UploadButton />}
        </Upload>
      )}
    </>
  );
};

export default UploadImg;
