import axios from 'axios'
import { ElLoading } from 'element-plus'
// import vue from 'vue';
// import { createApp } from 'vue'
// import {defineComponent, onMounted} from 'vue'//引入方法

const mimeMap = {
    xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    zip: 'application/zip',
    wps: 'application/wps'
}

// const baseUrl = process.env.VUE_APP_BASE_API;
// const baseUrl = window.baseURL ? (process.env.NODE_ENV === 'development' ? window.baseURL.devUrl : window.baseURL.prodUrl) : process.env.VUE_APP_BASE_API;
let loading; // loading;

export function downLoadWps(filename, cycleId, token) {
    loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)'
    })
    // console.log(window.baseURL.devUrl,'window');
    let url = window.baseURL.devUrl || "";
    axios({
        method: 'post',
        url: `${url}/export/exportReport/${cycleId}`,
        // url: 'http://222.75.116.199:9094/indexImport/quarterlyReport',
        responseType: 'blob',
        headers: { 'Authorization': 'Bearer ' + token }
    }).then(res => {
        resolveBlob(res, mimeMap.wps, filename)
    }).catch(err=>{
        console.log('downLoadWps','下载失败',err);
    })
}

/**
 * 解析blob响应内容并下载
 * @param {*} res blob响应内容
 * @param {String} mimeType MIME类型
 */
export function resolveBlob(res, mimeType, fileName) {
    // 异常处理
    if (res.data.type == "application/json") {
        const reader = new FileReader();
        reader.onload = function (e) {
            const { msg } = JSON.parse(e.target.result);
            // Vue.config.globalProperties.$message.error(msg);
        }
        reader.readAsText(res.data);
        if (loading) loading.close();
        return
    }
    if (loading) loading.close();
    var blob = new Blob([res.data], { type: mimeType });
    // //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
    var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*');
    var contentDisposition = decodeURI(res.headers['content-disposition']);
    if (fileName) {
        console.log('有文件名');
    } else if (contentDisposition == undefined || contentDisposition == 'undefined') {
        console.log('文件名未获取到');
    } else {
        var result = patt.exec(contentDisposition)
        var name = result[1];
        fileName = name.replace(/\"/g, '')
    }
    let objectUrl = URL.createObjectURL(blob)
    const aLink = document.createElement('a')

    try {
        aLink.style.display = 'none'
        aLink.href = URL.createObjectURL(blob)
        aLink.setAttribute('download', fileName) // 设置下载文件名称
        document.body.appendChild(aLink)
        aLink.click()
        URL.revokeObjectURL(aLink.href); //清除引用
        document.body.removeChild(aLink);
        // Vue.config.globalProperties.$download.saveAs(objectUrl, fileName);
    } catch (e) {
        console.log(e, '异常');
    }
}