/* eslint-disable @typescript-eslint/no-unused-expressions */
import Icon, { PlusOutlined, LoadingOutlined } from '@ant-design/icons';
import { Upload, message, Space } from 'antd';
// eslint-disable-next-line prettier/prettier
import type { RcFile } from 'antd/es/upload/interface';
import React, { Fragment, useEffect, useState } from 'react';
import styles from './uploadImg.module.less';
import { review, deleteIcon } from "./icon"
import { cloneDeep } from 'lodash';
import schema from "./schema"
import FormItem from '../FormItem/FormItem'
import Preview from "./preview"
import { ChangeImgUrl, getItemProps } from "../../utils"
// import OCR from "../../utils/ocr"
const UploadImg = (item: any) => {
  const data: any = getItemProps(schema, item)
  const { UploadProps, otherProps, FormItemProps, beforeUploadRules, callback, Type, form } = data
  const [imageUrl, setImageUrl] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const { uploadText, imageUrl: _imageUrl } = otherProps
  const [isPreview, setIsPreview] = useState(false)
  useEffect(() => {
    _imageUrl ? setImageUrl(_imageUrl) : null
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  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 = ({ 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 onClick={() => {
          const CloneImage = cloneDeep(imageUrl)
          CloneImage.splice(index, 1)
          form && form?.setFieldValue(FormItemProps?.name, CloneImage)
          setImageUrl(CloneImage)
        }
        } component={deleteIcon} /> : null}
      </div>
    </div>
  }

  const beforeUpload = (file: RcFile) => {
    const { fileSize } = beforeUploadRules
    const isLt2M = file.size / 1024 / 1024 < fileSize;
    const isCount = FormItemProps?.maxCount <= imageUrl?.length
    if (isCount) {
      message.error(`最多可上传${FormItemProps?.maxCount}张图片!`);
      return !isCount
    }
    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;
      setLoading(false);
      const CloneImage = cloneDeep(imageUrl)
      CloneImage.push(url)
      setImageUrl(CloneImage);
      callback && callback(CloneImage)
      return '';
    }
  };

  return <>
    {isPreview ? <Preview isPreview={isPreview} setIsPreview={setIsPreview} imageUrl={imageUrl} /> : null}
    {
      <FormItem
        label={FormItemProps?.label}
        style={FormItemProps?.style}
        required={FormItemProps?.required}
      >
        <Space size={5} wrap={true}>
          {
            imageUrl?.map((url, index) => {
              return <Fragment key={url}>
                <AfterButon url={ChangeImgUrl(url)} index={index} />
              </Fragment>
            })
          }
          <div style={{ height: "60px" }}>
            <FormItem
              noStyle
              style={{ height: "60px", display: "block" }}
              name={FormItemProps?.name}
              rules={FormItemProps?.required ? [{
                required: true,
                message: `请上传${FormItemProps?.label || "图片"}`
              }] : []}
              valuePropName={FormItemProps.name}
              getValueFromEvent={(info: any): any => {
                if (info.file.status == 'done') {
                  return [...imageUrl, info.file.response.data];
                } else {
                  return imageUrl
                }
              }}
            >
              <Upload
                {...UploadProps}
                beforeUpload={beforeUpload}
                onChange={handleChange}
              >
                <UploadButton />
              </Upload>
            </FormItem>
          </div>
        </Space>
        <div className={styles.tips}>{beforeUploadRules?.tips}</div>
      </FormItem>
    }
  </>
};

export default UploadImg;
