import axios from 'axios'
import qs from 'qs'
import {
  getToken
} from '@/utils/auth'
import load from '@/utils/loading'

/**
 * 导出模板
 * @param {*} params
 * params: {
 *      url: xxx,
 *      params: {},
 *      fileName: xxx.xls
 * }
 */
export const Export = (that, params, message) => {
    // 报表导出
    let url = params.url
    const options = {
        method: params.method ? params.method : 'get',
        headers: {
            Authorization: getToken()
        },
        // params: params.params,
        url,
        responseType: "blob"
    };
    if(options.method == 'post') {
        options.data = params.params
    } else {
        options.params = params.params
    }
    that.$confirm((message || "您确定下载模板"), "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
        })
        .then(() => {
            load.startLoading()
            axios(options).then(res => {
                let blob = new Blob([res.data], {
                // type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
                type: "application/vnd.ms-excel;charset=utf-8"
                //word文档为application/msword,pdf文档为application/pdf,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8
                });
                let text = (new Response(blob)).text()
                text.then(res => {
                // 判断是否报错
                if (res.indexOf('code') != -1) {
                    let json = JSON.parse(res)
                    that.$message.error(json.msg)
                } else {
                    let objectUrl = URL.createObjectURL(blob);
                    let link = document.createElement("a");
                    let fname = params.fileName || "导出文件.xlsx"; //下载文件的名字
                    link.href = objectUrl;
                    link.setAttribute("download", fname);
                    document.body.appendChild(link);
                    link.click();
                }
                })

                load.endLoading();
            }).catch(error => {
                that.$message.error('下载失败，请联系管理员');
                load.endLoading();
            });
        })
        .catch(() => {});
}
