import { useAjax } from "@/Hook/useAjax";
import { message, Upload } from "antd";
import { RcFile } from "antd/es/upload";
import React, { useEffect, useState } from "react"
import { MediaTypeProps, saveMediaApi, upLoadMediaApi } from "../../API/weMaterial/weMaterial";
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { useOss } from "@/Hook/useOss";
import dayjs from 'dayjs'
import CropperImg from "@/components/CropperImg";
type CompareType = '<' | '<=' | '>' | '>=' | '=' | '!='

interface Props {
    type?: MediaTypeProps,
    value?: string,
    onChange?: (data: { value: string, file: RcFile, name: string }) => void
    size?: { width: number, height: number, evalW: CompareType, evalH: CompareType, msg: string },
    // 是否裁剪
    isCropper?: boolean,
    isEdit?: boolean
}

const UploadImg: React.FC<Props> = ({ value, onChange, size, type, isCropper, isEdit }) => {

    /********************************/
    const [visible, setVisible] = useState<boolean>(false);
    const [file, setFile] = useState<RcFile>();
    const upLoadMedia = useAjax((params) => upLoadMediaApi(params))
    const saveMedia = useAjax((params) => saveMediaApi(params))
    const ossUpload = useOss(true)
    const [imageUrl, setImageUrl] = useState<string>('');
    /********************************/

    useEffect(() => {
        setImageUrl(value || '')
    }, [value])

    const uploadButton = (
        <div>
            {upLoadMedia.loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>上传图片</div>
        </div>
    );

    const upload = (file: RcFile) => {
        let name = dayjs().valueOf().toString()
        ossUpload.run(file, name).then(res => {
            if (res?.data) {
                let [fileName, nameSuffix] = file.name.split('.')
                saveMedia.run({ fileName: name || fileName, mediaType: type || 'image', suffix: nameSuffix, url: res?.data })
                onChange?.(res.data)
            }
        })
    }

    return <>
        <Upload
            name="avatar"
            listType="picture-card"
            accept='image/png,image/jpg,image/jpeg'
            action="#"
            showUploadList={false}
            customRequest={() => { }}
            beforeUpload={(file: RcFile): any => {
                if (file.size > 10485760) {
                    message.error('图片大小大于10M,请压缩在上传')
                    return
                }
                let img: any = new Image();
                let _URL = window.URL || window.webkitURL;
                img.onload = function (e: any) {
                    if ((size?.width && eval(`${this.width} ${size.evalW} ${size?.width}`)) || (size?.height && eval(`${this.height} ${size?.evalH} ${size?.height}`))) {
                        if (isCropper && ((isEdit && eval(`${this.width} >= ${size?.width}`) && eval(`${this.height} >= ${size?.height}`)) || (!isEdit))) {
                            setFile(file)
                            setVisible(true)
                        } else {
                            message.error(`传入的图片大小不符, 上传图片宽度${this.width}高度${this.height}, ${size?.msg}`)
                        }
                        return
                    }
                    upload(file)
                }
                img.src = _URL.createObjectURL(file);
            }}
        >
            {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
        </Upload>
        {/* 裁剪 */}
        {visible && <CropperImg
            visible={visible}
            size={size}
            isEdit={isEdit}
            onClose={() => setVisible(false)}
            file={file}
            onChange={(fileList: any[], file: any) => {
                upload(file)
                setVisible(false)
            }}
        />}
    </>
}

export default React.memo(UploadImg)