// 下载文件
import axios from "axios";
import { showToast } from "vant";
import {ref} from 'vue'


/**
 * 
 * @returns {
 *  progress 下载进度
 *  fileSize 文件大小
 *  startDownload 开始下载函数
 *  cancelDownload  取消下载
 * }
 */
export function useDownLoadFile(){
    let progress=ref(0)//进度 0-1
    let fileSize=ref(0)//文件大小

    const controller = new AbortController();

    // 开始下载
    const startDownload=(url,filename)=>{
        axios({
            url:url,
            method:'get',
            responseType:'blob',
            signal: controller.signal,
            onDownloadProgress:function(progressEvent){
                // console.log(progressEvent);
                fileSize.value=Math.floor(progressEvent.total/1024/1024)
                progress.value = Math.floor(progressEvent.progress*100)
            }
        }).then(res=>{
            // console.log(res);
            const {status,data}=res
            if(status!=200){
                showToast('下载失败')
                return
            }
            const content = data
            const blob = new Blob([content])
            if ('download' in document.createElement('a')) {
                const elink = document.createElement('a')
                elink.download = filename || url.split('/')[url.split('/').length - 1]
                elink.style.display = 'none'
                elink.href = window.URL.createObjectURL(blob)
                document.body.appendChild(elink)
                elink.click()
                window.URL.revokeObjectURL(elink.href)
                document.body.removeChild(elink)
            } else {
                navigator.msSaveBlob(blob, filename)
            }
        }).catch((e)=>{
            console.log(e);
            showToast('下载失败')
        })
    }

    //取消下载
    const cancelDownload=()=>{
        // 取消请求
        controller.abort()
        progress.value=0
        fileSize.value=0
    }

    return {
        fileSize,
        progress,
        startDownload,
        cancelDownload
    }
}