import axios from "axios";
import {
	Notification,
	MessageBox,
	Message,
	Loading
} from "element-ui";
import store from "@/store";
import {
	getToken,
	setToken,
	removeCompanyId,
	removeToken,
	removeInfo,
} from "@/utils/auth";
import errorCode from "@/utils/errorCode";
import {
	tansParams,
	blobValidate
} from "@/utils/ruoyi";
import { closeLoading, openLoading } from '@/utils/loading'
import cache from "@/plugins/cache";
import {
	saveAs
} from "file-saver";
import route from "../router/index";

// import configKey from '@/assets/js/configKey.js'
let downloadLoadingInstance;
let downloadLoadingAxios;
// 是否显示重新登录
export let isRelogin = {
	show: false,
};
let timer = null;
// 是否正在刷新的标记
let isRefreshing = false;
//重试队列
let requests = [];

axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
// 创建axios实例
const service = axios.create({
	// axios中请求配置有baseURL选项，表示请求URL公共部分
	// baseURL:configKey.urlType?configKey.baseURL:process.env.VUE_APP_BASE_API,
	baseURL: process.env.VUE_APP_BASE_API,
	// baseURL: "http://192.168.2.240:8066/",
	// 超时
	timeout: 2 * 60 * 1000,
});

// request拦截器
service.interceptors.request.use(
	(config) => {
		// do something bedocument.getElementById("")fore request is sent
		// config.headers['secretkey'] = 'aQ+b2wGj1LuhR8N2O0aOmKlkjgnOyHSlZ0QUtZMP3dHkVkAGhJe37KOdmpexsE6W' //本机密钥

		// config.headers['secretkey'] = 'm/Ah8KQ6IfWEv85KEoaHKf4SfwtemYtGkiuBabkQCnOuJ/+nyvqBLOVheirHN1TO' //本机密钥
		config.headers["secretkey"] = configKey.secretkey;

		// if (store.getters.token) {
		// if (window.localStorage.userToken) {
		let token = getToken();
		if (token) {
			config.headers["token"] = token;
		}

		if (config.url.indexOf('updateDto') != -1 || config.url.indexOf('saveDto') != -1) {
			openLoading('submit')
		} else if (config.url.indexOf('getById') != -1) {
			openLoading('detail')
		} else if (config.url.indexOf('deleteById') != -1) {
			openLoading('del')
		} else if (config.url.indexOf('changerState') != -1) {
			openLoading('submit')
		}

		// 生成请求的唯一标识符
		const requestIdentifier = `${config.url}-${config.method}`;
		// 判断是否已存在相同的请求
		const isDuplicateRequest = requests.includes(requestIdentifier);
		// 如果存在相同请求，取消当前请求
		if (isDuplicateRequest) {
			// return Promise.reject(new Error("Duplicate request"));
		}
		// 将请求的唯一标识符添加到请求队列中
		requests.push(requestIdentifier);
		// 设置计时器，在秒后移除请求的唯一标识符
		clearTimeout(timer);
		timer = setTimeout(() => {
			const index = requests.indexOf(requestIdentifier);
			if (index !== -1) {
				requests.splice(index, 1); // 移除请求的唯一标识符
			}
		}, 2000);
		return config;
	},

	(error) => {
		// do something with request error
		// 请求发生错误时清除唯一标识符
		const requestIdentifier = `${error.config.url}-${error.config.method}`;
		const index = requests.indexOf(requestIdentifier);
		if (index !== -1) {
			requests.splice(index, 1); // 清除唯一标识符
		}
		return Promise.reject(error);
	}
);

// 响应拦截器
service.interceptors.response.use(
	(res) => {
		// 请求完成时清除唯一标识符
		const requestIdentifier = `${res.config.url}-${res.config.method}`;
		const index = requests.indexOf(requestIdentifier);
		if (index !== -1) {
			requests.splice(index, 1); // 清除唯一标识符
		}
		// downloadLoadingAxios.close()
		// 未设置状态码则默认成功状态
		const code = res.data.status || '200';
		// 获取错误信息
		const msg = res.data.msg;
		closeLoading();
		// 二进制数据则直接返回
		if (
			res.request.responseType === "blob" ||
			res.request.responseType === "arraybuffer"
		) {
			return res.data;
		}

		if (code === '500') {
			MessageBox.confirm(msg, "系统提示", {
				confirmButtonText: "确定",
				showCancelButton: false,
				showClose: false,
				closeOnClickModal: false,
				closeOnPressEscape: false,
				type: "error",
			})
				.then(() => {
					if (msg === 'token无效') {
						store.dispatch('LogOut').then(() => {
							route.replace({
								path: "/login"
							});;
						})
					}

				})
				.catch(() => { });
			return Promise.reject(new Error(msg));
		} else if (code == '1002') {

			MessageBox.confirm(msg, "系统提示", {
				confirmButtonText: "确定",
				showCancelButton: false,
				showClose: false,
				closeOnClickModal: false,
				closeOnPressEscape: false,
				type: "error",
			})
				.then(() => {
					store.dispatch('LogOut').then(() => {
						route.replace({
							path: "/login"
						});;
					})
				})
				.catch(() => { });
		} else if (code !== '200') {

			MessageBox.confirm(msg, "系统提示", {
				confirmButtonText: "确定",
				showCancelButton: false,
				showClose: false,
				closeOnClickModal: false,
				closeOnPressEscape: false,
				type: "error",
			})
				.then(() => { })
				.catch(() => { });
			return Promise.reject("error");
		} else {
			return res.data;
		}
	},
	(error) => {
		let response = error.response;
		closeLoading();
		// downloadLoadingAxios.close()
		// if (response.status == 401) {
		// 	if (response.data.code == 1002) {
		// 		if (!isRefreshing) {
		// 			isRefreshing = true;
		// 			setToken(response.data.data[0]);
		// 			response.headers.token = response.data.data[0];
		// 			// token 刷新后将数组的方法重新执行
		// 			requests.forEach((cb) => cb(token));
		// 			requests = []; // 重新请求完清空
		// 			return service(response.config);
		// 			isRefreshing = false;
		// 		} else {
		// 			// 返回未执行 resolve 的 Promise
		// 			return new Promise((resolve) => {
		// 				// 用函数形式将 resolve 存入，等待刷新后再执行
		// 				requests.push((token) => {
		// 					response.headers.token = `${token}`;
		// 					resolve(service(response.config));
		// 				});
		// 			});
		// 		}
		// 		return response && response.data;
		// 	} else {
		// 		Message({
		// 			message: response.data.message,
		// 			type: "error",
		// 			showClose: true,
		// 			duration: 0,
		// 		});
		// 		if (response.data.code == -1) {} else {
		// 			store.dispatch("LogOut").then(() => {
		// 				route.replace({
		// 					path: "/login",
		// 				});
		// 			});
		// 		}
		// 	}
		// } else {
		// 	let {
		// 		message
		// 	} = error;
		// 	if (message == "Network Error") {
		// 		message = "后端接口连接异常";
		// 	} else if (message.includes("timeout")) {
		// 		message = "系统接口请求超时";
		// 	} else if (message.includes("Request failed with status code")) {
		// 		message = "系统接口" + message.substr(message.length - 3) + "异常";
		// 	}
		// 	MessageBox.confirm(message, "系统提示", {
		// 			confirmButtonText: "确定",
		// 			showCancelButton: false,
		// 			showClose: false,
		// 			closeOnClickModal: false,
		// 			closeOnPressEscape: false,
		// 			type: "error",
		// 		})
		// 		.then(() => {})
		// 		.catch(() => {});
		// }

		return Promise.reject(error);
	}
);

// 通用下载方法
export function download(url, params, filename, config) {
	downloadLoadingInstance = Loading.service({
		text: "正在下载数据，请稍候",
		spinner: "el-icon-loading",
		background: "rgba(0, 0, 0, 0.7)",
	});
	return service
		.post(url, params, {
			transformRequest: [
				(params) => {
					return tansParams(params);
				},
			],
			headers: {
				"Content-Type": "application/x-www-form-urlencoded",
			},
			responseType: "blob",
			...config,
		})
		.then(async (data) => {
			const isLogin = await blobValidate(data);
			if (isLogin) {
				const blob = new Blob([data]);
				saveAs(blob, filename);
			} else {
				const resText = await data.text();
				const rspObj = JSON.parse(resText);
				const errMsg =
					errorCode[rspObj.code] || rspObj.msg || errorCode["default"];
				Message.error(errMsg);
			}
			downloadLoadingInstance.close();
		})
		.catch((r) => {
			Message.error("下载文件出现错误，请联系管理员！");
			downloadLoadingInstance.close();
		});
}

export default service;
