import axios from 'axios'
import { ElLoading } from 'element-plus'
import modal from '@/plugins/modal';
import {
	getToken
} from '@/utils/auth'
import {
	blobValidate
} from '@/utils/ruoyi'
let downloadLoadingInstance;
// 通用下载方法
export function previewFile(url, params, filename) {
	downloadLoadingInstance = ElLoading.service({
		text: "正在打开文件，请稍候",
		background: "rgba(0, 0, 0, 0.7)",
	})
	axios.defaults.headers['content-Type'] = 'application/octet-stream;charset=utf-8';
	axios.defaults.headers['Authorization'] = 'Bearer ' + getToken();
	axios.defaults.responseType = 'blob';
	return axios.get("http://10.60.10.144:8080"+url, params, {
			
		// headers: {
		// 	'Content-Type': 'application/octet-stream',
		// 	'Authorization': 'Bearer ' + getToken()
		// },
		// responseType: 'blob', // 切记类型 blob
	}).then(async (data) => {
		console.log(data)
		const isLogin = await blobValidate(data);
		if (isLogin) {
			// const blob = new Blob([data], { type: 'application/pdf' });
			// const blobUrl = URL.createObjectURL(blob);
			// window.open(blobUrl);
			let blob = new Blob([data.data]);
			let url = window.URL.createObjectURL(blob); // 创建 url 并指向 blob
			let a = document.createElement('a');
			a.href = url;
			a.download = filename;
			a.click();
			window.URL.revokeObjectURL(url); // 释放该 url
		} else {
			const resText = await data.text();
			const rspObj = JSON.parse(resText);
			const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
			modal.msgError(errMsg);
		}
		downloadLoadingInstance.close();
	}).catch((r) => {
		console.error(r)
		modal.msgError('预览文件出现错误，请联系管理员！')
		downloadLoadingInstance.close();
	})
}
