/**
 * 上传图片 / 文件
 */
import { ref, computed } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { attachFile, attachImage } from '@/api/common.js'
import { base64ToBlob } from '@/utils/index.js'
import QRCode from 'qrcode' //生成二维码

export function useOssloader() {
    const loading = ref(null)

    // 加载信息
    const openFullScreen = (loadText) => {
        loading.value = ElLoading.service({
            lock: true,
            text: loadText,
            background: 'rgba(0, 0, 0, 0.7)',
        })
    }

    const closeFullScreen = () => {
        loading.value.close()
    }

    // 上传图片校验
    const beforeAvatarUpload = (rawFile) => {
        let fileType = ["image/jpeg", "image/png", "image/webp"];
        if (!fileType.includes(rawFile.type)) {
            ElMessage.error("请上传图片格式为jpg/png/webp!");
            return false;
        } else if (rawFile.size / 1024 / 1024 > 2) {
            ElMessage.error(`图片大小不能超过 2MB!`);
            return false;
        }
        return true;
    }

    // 上传前校验文件类型
    const beforeUpload = (file) => {
        const fileExt = file.name.split('.').pop().toLowerCase()
        const validExts = ['apk', 'aab', 'ipa']
        if (!validExts.includes(fileExt)) {
            ElMessage.error('只允许上传 .apk、.aab 或 .ipa 文件')
            return false
        }
        return true
    }

    // 单图片上传
    const selfUpload = async (param, type = false) => {
        const file = param.file

        // 构造唯一文件名
        const uniqueFileName = generateUniqueFileName(file.name)

        // 创建新的 File 对象
        const newFile = new File([file], uniqueFileName, {
            type: file.type
        })

        const formData = new FormData()
        formData.append('file', newFile)

        if (!type) {
            openFullScreen('图片上传中')
        }

        try {
            const res = await attachFile(formData)
            const url = res.data.url

            if (!type) {
                ElMessage.success('图片上传成功')
                return url
            }

            return { url, name: uniqueFileName }
        } catch (err) {
            ElMessage.error('图片上传失败')
            console.error(err)

            return null
        } finally {
            if (!type) {
                closeFullScreen()
            }
        }
    }

    // 自定义上传逻辑
    const customUpload = async (param) => {
        const file = param.file
        const fileExt = file.name.substring(file.name.lastIndexOf('.')) // 原始扩展名，如 .apk

        const formData = new FormData()
        // formData.append('file', file, generateUniqueFileName(fileExt)) // 使用唯一名上传
        formData.append('file', file)

        openFullScreen('APP上传中')

        try {
            const res = await attachFile(formData)
            const apkUrl = res.data.url
            ElMessage.success('上传成功')

            // 生成二维码
            const qrDataURL = await QRCode.toDataURL(apkUrl)
            const blob = base64ToBlob(qrDataURL)
            const qrFormData = new FormData()
            qrFormData.append('file', blob, generateUniqueFileName('.png')) // 二维码也加唯一名

            const imageData = await attachFile(qrFormData)
            const qrCode = imageData.data.url
            ElMessage.success('二维码生成成功！')

            return { apkUrl, qrCode } // 返回对象
        } catch (err) {
            ElMessage.error('APP上传失败')
            console.error(err)
            return null
        } finally {
            closeFullScreen()
        }
    }

    // 批量上传图片
    const uploadAllImages = async (imageList) => {
        openFullScreen('图片上传中')
        try {
            const newImageList = []

            for (const fileItem of imageList) {
                const file = fileItem.raw instanceof File ? fileItem.raw : null
                if (!file) continue

                // 构造 param 模拟 el-upload 组件传入的结构
                const param = { file }

                const result = await selfUpload(param, true)

                if (result) {
                    newImageList.push({
                        attachName: result.name,
                        size: Math.ceil(fileItem.size / 1024),
                        url: result.url
                    })
                }
            }

            return newImageList

        } catch (err) {
            ElMessage.error('图片上传失败')
            console.error('图片上传失败', err)

            return null
        } finally {
            closeFullScreen()
        }
    }

    /**
     * 根据原文件名生成唯一文件名
     * @param {string} originalName 原始文件名，例如 xxx.jpg
     * @returns {string} 唯一文件名，例如 1722323123_xxxxxx.jpg
    */
    function generateUniqueFileName(originalName) {
        const timestamp = Date.now()
        const ext = originalName.substring(originalName.lastIndexOf('.'))
        const randomStr = Math.random().toString(36).substring(2, 10)
        return `${timestamp}_${randomStr}${ext}`
    }

    return {
        beforeAvatarUpload,
        beforeUpload,
        selfUpload,
        customUpload,
        uploadAllImages
    }
}
