import { RcFile } from 'antd/es/upload'
import Toast from '../../../../../Toast'

interface IfileInfo {
    width: number
    height: number
    status: boolean
}
export const verifyLoadImage = async (file: RcFile, tFun: any, maxWidth = 0, maxHeight = 0) => {
    const isGIF = file.type === 'image/gif'
    if (isGIF) {
        Toast({
            message: tFun('toast.gifError'),
            duration: 3000,
        })
        return false
    }

    const isLt10M = file.size / 1024 / 1024 < 10
    if (!isLt10M) {
        Toast({
            message: tFun('toast.picSizeLimit'),
            duration: 3000,
        })
        return false
    }

    const { width, height, status } = (await checkAspectRatio(file)) as IfileInfo
    if (!width && !height) {
        Toast({
            message: tFun('toast.picInvalid'),
            duration: 3000,
        })
        return false
    } else if (maxWidth || maxHeight) {
        if (width > maxWidth || height > maxHeight) {
            Toast({
                message: tFun('toast.picCustomHWLimit', {
                    maxHeight,
                    maxWidth,
                }),
                duration: 3000,
            })
            return false
        }
    } else if (!status) {
        Toast({
            message: tFun('toast.picHWLimit'),
            duration: 3000,
        })
        return false
    }

    return true
}

export const checkAspectRatio = (file: RcFile) => {
    const image = new Image()
    const url = URL.createObjectURL(file)
    return new Promise((resolve) => {
        image.onload = () => {
            const aspectRatio = image.width / image.height
            resolve({
                width: image.width,
                height: image.height,
                status: image.width >= 512 && image.height >= 512 && aspectRatio <= 2,
            })
        }
        image.onerror = () => {
            resolve({ width: 0, height: 0, status: false })
        }
        image.src = url
    })
}
