import env from '@/config';
import config from '@/common/mxConfig';
import {useEnvStore} from "@/hooks/useEnvStore";
import {useUserStore} from "@/hooks/useUserStore";

export const useDownload = function () {
    const {token, period} = useUserStore()
    const {isH5, isWap2App} = useEnvStore()

    const postMessage = (msgType, data) => {
        uni.webView.postMessage({
            data: {
                action: msgType,
                data: data
            }
        });
    }

    const downloadBlobFile = (response, filename) => {
        // download blob file
        const url = window.URL.createObjectURL(new Blob([response.data]))

        // get file suffix from response header
        // build file name from data.name data.score data.batchName and suffix
        let disposition = response.header['content-disposition']
        disposition = disposition.replace('"', '').replace("'", '')
        const suffix = disposition.substring(disposition.lastIndexOf('.'))
        const fileName = `${filename}${suffix}`

        // Create a download link and trigger a click event to download the file
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', fileName)
        document.body.appendChild(link)
        link.click()

        // Remove the link element and release the object URL
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
    }

    const downloadBlobFileForWap2app = (reqOption, fileName) => {
        // reqOption: {url, params}
        if (isWap2App.value) {
            postMessage('downloadBlob', {
                ...reqOption,
                token: token.value
            });
        }
    }

    const downloadRealPaper = (paperId) => {
        let path = env.serverBaseUrl + '/front/v2/papers/downloadRealPaper'
        path += '?paperId=' + paperId + '&period=' + period.value
        const override = {
            isOffice: () => true,
            getFileType: () => 'docx'
        }
        downloadFile(path, false, override)
    }

    const downloadFile = (url, openOnly = false, overrideFileHelper = {}) => {
        const itemList = (openOnly || isWap2App.value) ? ["打开文档"] : ["打开文档", "下载文档"];
        uni.showActionSheet({
            itemList: itemList,
            success: res => {
                const fileHelper = {
                    ...config.fileHelper,
                    ...overrideFileHelper
                }
                switch (res.tapIndex) {
                    case 0:
                        if (fileHelper.isFile(url)) {
                            if (isWap2App.value) {
                                postMessage('openFile', {url});
                            } else if (isH5.value) {
                                window.open(url);
                            }
                        } else if (fileHelper.isImage(url)) {
                            if (isWap2App.value) {
                                postMessage('openImage', {url});
                            } else if (isH5.value) {
                                uni.previewImage({
                                    urls: [url]
                                });
                            }
                        } else {
                            if (isWap2App.value) {
                                postMessage('openFile', {url});
                            } else if (isH5.value) {
                                uni.showToast({
                                    title: "暂不支持直接打开该文档",
                                    icon: "none"
                                });
                            }
                        }

                        break;
                    case 1:
                        const remoteFunc = fileHelper.isImage(url) ? 'openImage' : 'downloadFile';
                        if (isWap2App.value) {
                            postMessage(remoteFunc, {url});
                        } else if (isH5.value) {
                            // 大文件不适合此方案，最好后台请求头部加上Content-Disposition: attachment; filename=xxx.xxx来触发下载
                            uni.showLoading();
                            uni.downloadFile({
                                url: url,
                                success: (res) => {
                                    if (res.statusCode === 200) {
                                        const fileName = url.split('/').pop();
                                        const a = document.createElement("a");
                                        a.target = '_blank';
                                        a.download = fileName;
                                        a.href = res.tempFilePath;
                                        document.body.appendChild(a);
                                        a.click();
                                        a.remove();
                                    }
                                },
                                fail: (err) => {
                                    uni.showToast({
                                        icon: 'none',
                                        mask: true,
                                        title: '失败请重新下载',
                                    });
                                },
                                complete: () => {
                                    uni.hideLoading();
                                }
                            })
                        }
                        break;
                    default:
                        break;
                }
            }
        });
    }

    return {
        postMessage,
        downloadRealPaper,
        downloadFile,
        downloadBlobFile,
        downloadBlobFileForWap2app
    }
}