import { downloadByData } from '@/utils/download';
import { useErrorConfirm } from '@/utils/useErrorConfirm';
import { ref } from 'vue';
import { useMessage } from './useMessage';

const { createMessage } = useMessage()
const { report } = useErrorConfirm()
/**
 * 根据对应的api函数下载模版
 * @param apiFunction api函数
 */
function useApiDownTemplate<G extends any>(apiFunction: (params: G) => Promise<any>) {
    // 加载
    const templateLoading = ref(false)

    // 处理下载
    async function getApiDownload(params: G): Promise<void> {
        try {
            templateLoading.value = true
            const res = await apiFunction(params);
            parseBlobAsJSON(res.data)
                .then((result: any) => {
                    // 解析成功，判断是否为json数据
                    if (result.code === 500) {
                        createMessage.error(result.msg)
                    } else if (result.code === 600) {
                        createMessage.error(result.msg)
                    } else {
                        const header = res.headers['content-disposition'].split("''");
                        const fileName = decodeURIComponent(header[1]);
                        downloadByData(res.data, fileName);
                    }
                })
                .catch(error => {
                    // 解析失败，处理错误
                    console.error(error);
                });
        } catch (error) {
            report(error)
        } finally {
            templateLoading.value = false
        }
    }

    // 点击下载
    const hanleOpenDownload = async (params = {} as G) => {
        getApiDownload(params)
    }

    return {
        templateLoading,
        hanleOpenDownload
    }
}

/**
 * 解析blob对象
 * @param blob 
 */
function parseBlobAsJSON(blob) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = function (event: any) {
            try {
                const jsonString = event.target.result;
                const jsonData = isJSON(jsonString);
                jsonData ? resolve(JSON.parse(jsonString)) : resolve(jsonData)
            } catch (error) {
                reject(error);
            }
        };
        reader.onerror = function (event) {
            reject(new Error("无法将Blob解析为JSON!"));
        };
        reader.readAsText(blob);
    });
}

/**
 * 判断是否为json数据
 * @param str 
 */
function isJSON(str) {
    try {
        JSON.parse(str);
        return true;
    } catch (error) {
        return false;
    }
}

export {
    useApiDownTemplate
}