import { Row, Upload, message } from 'antd';
import React, { useEffect, useState } from 'react';
import Icon, { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import FormItem from '../FormItem/FormItem';
import styles from './uploadImg.module.less';
import { review, deleteIcon } from './icon';
import Preview from './preview';
import { ChangeImgUrl, getItemProps } from '../../utils';
import schema from './schema';
import OCR from '../../utils/ocr';
import Loading from '../Loading';
import ImagePreveEdit from '../ImagePreveEdit/index';
import { zipImg, zipImg10M } from '../../utils/zipImg';
const backImg = `${BASE_IMG}da57cc3d-1168-4e97-8ad6-5d2c5ab333c4.png`;
const frontImg = `${BASE_IMG}d278ab84-9b15-4237-923d-3a8e9cbb8c65.png`;

const styleLoading: object = {
  position: 'absolute',
  top: 0,
  left: 0,
  bottom: 0,
  right: 0,
  margin: 'auto',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  background: 'rgba(0,0,0,.6)',
  color: '#fff',
};

const IDCard = (item: any) => {
  const data: any = getItemProps(schema(), item);
  const {
    FormItemProps,
    beforeUploadRules,
    frontProps,
    backProps,
    valueType,
    UploadProps,
    Type,
    form,
    ocr,
    otherProps,
    callback,
  } = data;

  const [ocrLoading, setOcrLoading] = useState(false);
  const [loading, setLoading] = useState(false);
  const [loading2, setLoading2] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();
  const [imageUrl2, setImageUrl2] = useState<string>();
  const [isPreview, setIsPreview] = useState(false);

  useEffect(() => {
    if (otherProps?.imageUrl?.length) {
      if (otherProps?.imageUrl[0]) {
        setImageUrl(otherProps?.imageUrl[0] || undefined);
      } else {
        Type === 'upload'
          ? setImageUrl(undefined)
          : setImageUrl(`${BASE_IMG}79770e20-06eb-4375-b91a-724ea677655e.jpg`);
      }
      if (otherProps?.imageUrl[1]) {
        setImageUrl2(otherProps?.imageUrl[1] || undefined);
      } else {
        Type === 'upload'
          ? setImageUrl2(undefined)
          : setImageUrl2(`${BASE_IMG}79770e20-06eb-4375-b91a-724ea677655e.jpg`);
      }
    } else {
      if (Type === 'upload') {
        setImageUrl(undefined);
        setImageUrl2(undefined);
      } else {
        setImageUrl(`${BASE_IMG}79770e20-06eb-4375-b91a-724ea677655e.jpg`);
        setImageUrl2(`${BASE_IMG}79770e20-06eb-4375-b91a-724ea677655e.jpg`);
      }
    }
  }, [otherProps]);

  const UploadButton = ({ uploadBtnProps }: any) => {
    let { uploadText, uploadBackgroundImg, index } = uploadBtnProps;
    if (valueType === 'IDCard' && index === 0) {
      uploadBackgroundImg = uploadBackgroundImg || frontImg;
    }
    if (valueType === 'IDCard' && index === 1) {
      uploadBackgroundImg = uploadBackgroundImg || backImg;
    }
    return (
      <div className={styles.U_B_Wapper}>
        {index === 0 && loading ? (
          <div style={styleLoading}>
            <LoadingOutlined />
          </div>
        ) : null}
        {index === 1 && loading2 ? (
          <div style={styleLoading}>
            <LoadingOutlined />
          </div>
        ) : null}
        {uploadBackgroundImg ? (
          <img src={uploadBackgroundImg} alt="" />
        ) : (
          <div className={styles.Up_Btn}>
            {
              <>
                <PlusOutlined style={{ fontSize: '18px', margin: '2px 0' }} />
                {uploadText ? (
                  <div style={{ fontSize: '12px' }}>{uploadText}</div>
                ) : 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 zipUrl = '';
      let res: any = null;
      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(file.response.data),
        });
        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,
          facePhotoOCR: {
            data: res,
          },
        });
      return '';
    }
  };
  const handleChangeBack = async (fileInput: any): Promise<any> => {
    const { file } = fileInput;
    if (file.status === 'uploading') {
      setLoading2(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,
          backPhotoUrl: 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);
      }
      setLoading2(false);
      setImageUrl2(url);
      callback &&
        callback({
          url,
          backPhotoOCR: {
            data: res,
          },
        });
      return '';
    }
  };

  const deleteImg = (index: number) => {
    if (index === 0) {
      form && form.setFieldValue(FormItemProps?.name[0], '');
      setImageUrl('');
    }
    if (index === 1) {
      form && form.setFieldValue(FormItemProps?.name[1], '');
      setImageUrl2('');
    }
  };

  const AfterButon = ({ url, index }: any) => {
    return (
      <div
        className={styles.U_B_Wapper}
        onClick={e => {
          e.stopPropagation();
        }}
      >
        <img src={url} alt="" style={{ height: '100%' }} />
        <div className={styles.Up_Btn_2}>
          <Icon component={review} onClick={() => setIsPreview(url)} />
          {Type === 'upload' ? (
            <Icon component={deleteIcon} onClick={() => deleteImg(index)} />
          ) : null}
        </div>
      </div>
    );
  };

  return (
    <FormItem
      label={FormItemProps?.label}
      style={FormItemProps?.style}
      required={FormItemProps?.required}
      labelCol={FormItemProps?.labelCol}
      wrapperCol={FormItemProps?.offset}
      className="DoubleUploadImg"
    >
      {ocrLoading ? <Loading tip={'ocr识别中...'} /> : null}
      <Row>
        {isPreview ? (
          FormItemProps?.previewType === 'edit' ? (
            <ImagePreveEdit
              visible={isPreview}
              setOpen={setIsPreview}
              src={isPreview}
            />
          ) : (
            <Preview
              isPreview={isPreview}
              setIsPreview={setIsPreview}
              imageUrl={imageUrl}
            />
          )
        ) : null}
        <FormItem
          noStyle
          name={FormItemProps?.name[0]}
          valuePropName={FormItemProps?.name[0]}
          getValueFromEvent={(info: any) => {
            if (info.file.status == 'done') {
              return info.file.response.data;
            } else {
              return undefined;
            }
          }}
          rules={
            FormItemProps?.required
              ? [
                  {
                    required: true,
                    message: `请上传${frontProps.errorMessage || '第一张照片'}`,
                  },
                ]
              : []
          }
        >
          <Upload
            {...UploadProps}
            beforeUpload={beforeUpload}
            onChange={handleChange}
          >
            {imageUrl ? (
              <AfterButon url={ChangeImgUrl(imageUrl)} index={0} />
            ) : (
              <UploadButton uploadBtnProps={{ ...frontProps, index: 0 }} />
            )}
          </Upload>
        </FormItem>
        <div style={{ width: '10px' }}></div>
        <FormItem
          noStyle
          name={FormItemProps?.name[1]}
          valuePropName={FormItemProps?.name[1]}
          getValueFromEvent={(info: any) => {
            if (info.file.status == 'done') {
              return info.file.response.data;
            }
          }}
          rules={
            FormItemProps?.required
              ? [
                  {
                    required: true,
                    message: `${
                      !imageUrl
                        ? ''
                        : `请上传${backProps.errorMessage || '第二张照片'}`
                    }`,
                  },
                ]
              : []
          }
        >
          <Upload
            {...UploadProps}
            beforeUpload={beforeUpload}
            onChange={handleChangeBack}
          >
            {imageUrl2 ? (
              <AfterButon url={ChangeImgUrl(imageUrl2)} index={1} />
            ) : (
              <UploadButton uploadBtnProps={{ ...backProps, index: 1 }} />
            )}
          </Upload>
        </FormItem>
      </Row>
      {beforeUploadRules?.tips ? (
        <div className={styles.tips}>{beforeUploadRules?.tips}11</div>
      ) : null}
    </FormItem>
  );
};

export default IDCard;
