import Axios from "./axiosCfg";
import Qs from "qs";
import {
	ElLoading
} from "element-plus";

let loading; //加载框
/**
 * 打开加载框
 */
function openLoad() {
	if (loading != null) loading.close();
	//打开加载框
	loading = ElLoading.service({
		text: "正在加载",
	});
}

/**
 * 关闭加载框
 */
function closeLoad() {
	if (loading != null) {
		loading.close();
	}
}

let Http = {
	/**
	 * Post请求
	 */
	Post: function(url, data) {
		//打开加载框
		openLoad();
		//发送请求
		return new Promise((resolve, reject) => {
			Axios.post(url, Qs.stringify(data))
				.then(res => {
					resolve(res);
				})
				.catch(res => {})
				.finally(() => {
					closeLoad();
				})
		});
	},
	/**
	 * Get请求
	 */
	Get: function(url, data) {
		//打开加载框
		openLoad();
		//请求数据
		return new Promise((resolve, reject) => {
			Axios.get(url, {params: data})
				.then(res => {
					resolve(res);
				})
				.catch(res => {
					console.log(res)
				})
				.finally(() => {
					closeLoad();
				})
		});
	},
	/**
	 * 下载
	 */
	Download: function(url, data, fileName) {
		Axios.post(url, Qs.stringify(data), {
			responseType: "blob"
		}).then(res => {
			let link = document.createElement("a");
			link.style.display = "none";
			link.href = window.URL.createObjectURL(new Blob([res]));
			link.setAttribute("download", fileName); // 自定义下载文件名（如exemple.txt）
			document.body.appendChild(link);
			link.click();
			URL.revokeObjectURL(link.href); // 释放URL 对象
			document.body.removeChild(link);
		});
	}
};

export default {
	Http
};
