import { ref } from 'vue'
import { genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { useMessage } from '@/hooks/useMessage'

export function useUpload(emit, onClose, onShow) {
    const upload = ref<UploadInstance>()
    const { createMessage } = useMessage()

    // 文件上传超限制时触发
    const handleExceed: UploadProps['onExceed'] = (files) => {
        console.log(files, ":上传的files");
        upload.value!.clearFiles()
        const file = files[0] as UploadRawFile
        file.uid = genFileId()
        upload.value!.handleStart(file)
    }

    // 文件上传时的限制
    const handleBeforeUpload = (rawFile) => {
        console.log(rawFile, ":触发文件上传的文件");
        // if (rawFile.type !== 'image/jpeg') {
        //     createMessage.error('Avatar picture must be JPG format!')
        //     return false
        // } else if (rawFile.size / 1024 / 1024 > 2) {
        //     createMessage.error('Avatar picture size can not exceed 2MB!')
        //     return false
        // }
        return true
    }

    // 文件提交上传
    const submitUpload = () => {
        // upload.value!.submit()
        console.log(upload.value, ":upload.value");
    }

    // 获取的数据
    const confirm = () => {
        submitUpload()
        // 取消弹窗
        // onClose()
    }

    // 隐藏操作
    const hanleOnClose = () => {
        // 取消弹窗
        onClose()
    }

    // 显示操作
    const show = () => {
        onShow()
    }

    return {
        handleExceed,
        handleBeforeUpload,
        show,
        confirm,
        hanleOnClose,
        upload,
    }
}