import axios from 'axios';
import router from '@/router';
import store from '../store';
import { ElLoading, ElMessage } from 'element-plus';
import { setNotLoggedIn } from '@/utils/auth';
export default class Request {
	http;
	isMock = false;
	isJWT = true;
	isLoginIn = false;
	// loadingInstance
	loading = true;
	constructor() {
		// let token = localStorage.getItem('userToken')
		this.http = axios.create({
			baseURL:
				import.meta.env.VITE_APP_API_BASEURL +
				import.meta.env.VITE_APP_API_VERSION +
				'/',
			timeout: 30000,
			withCredentials: true,
		});

		this.interceptors();
	}

	mock(mock) {
		this.isMock = mock;
		return this;
	}

	JWT(isJwt) {
		this.isJWT = isJwt;
		// this.http.defaults.headers.common['isJWT'] = true;
		return this;
	}

	LoginIn() {
		this.http.defaults.headers.common['LoginIn'] = 'LoginIn';
		return this;
	}

	showLoading(show) {
		this.loading = show;
		return this;
	}

	post(path, params) {
		let config = {};
		if (this.isMock)
			config = { baseURL: import.meta.env.VITE_APP_API_MOCK };
		return new Promise((resolve, reject) => {
			this.http
				.post(path, params, config)
				.then((r) => {
					resolve(r);
				})
				.catch((e) => {
					reject(e.message);
				});
		});
	}

	get(path, params) {
		const data = {
			params: params,
		};
		if (this.isMock) data.baseURL = import.meta.env.VITE_APP_API_MOCK;
		return new Promise((resolve, reject) => {
			this.http
				.get(path, data)
				.then((r) => {
					resolve(r);
				})
				.catch((e) => {
					reject(e.message);
				});
		});
	}

	put(path, params) {
		let config = {};
		if (this.isMock)
			config = { baseURL: import.meta.env.VITE_APP_API_MOCK };
		return new Promise((resolve, reject) => {
			this.http
				.put(path, params, config)
				.then((r) => {
					resolve(r);
				})
				.catch((e) => {
					reject(e.message);
				});
		});
	}

	delete(path) {
		let config = {};
		if (this.isMock)
			config = { baseURL: import.meta.env.VITE_APP_API_MOCK };
		return new Promise((resolve, reject) => {
			this.http
				.delete(path, config)
				.then((r) => {
					resolve(r);
				})
				.catch((e) => {
					reject(e.message);
				});
		});
	}

	interceptors() {
		this.http.defaults.headers.post['Content-Type'] =
			'application/x-www-form-urlencoded;charset=utf-8';
		// 添加请求拦截器
		this.http.interceptors.request.use(
			(config) => {
				let url = '';
				const NO_C_API = ['Login/code'];
				if (!NO_C_API.includes(config.url)) {
					let companyId = localStorage.getItem('companyId') || '';
					url = companyId
						? config.url + `?c=${companyId}`
						: config.url;
					config.url = url;
				}

				var token = localStorage.getItem('userToken');
				config.headers.Authorization = token;
				// 显示loading
				// if (this.loading) {
				//   this.loadingInstance = ElLoading.service({
				//     fullscreen: true
				//   })
				// }
				return config;
			},
			(error) => {
				// 请求错误
				// console.log('请求错误',error)
				return Promise.reject(error);
			}
		);
		// 添加响应拦截器
		this.http.interceptors.response.use(
			(response) => {
				// 关闭loading
				// if (this.loading) this.loadingInstance.close()
				if (response.status === 200) {
					if (
						response.data.status !== 200 &&
						response.data.status !== 99999
					) {
						if (response.data.message) {
							ElMessage.error({
								message: response.data.message,
								showClose: true,
							});
						}
					}
					if (response.data.status === 40003) {
						setNotLoggedIn(); // 设置未登录
						router.replace('/login');
					}
					return response.data;
				}
			},
			(error) => {
				const status = error.response ? error.response.status : null;
				// 关闭loading
				// setTimeout(() => {
				//   if (this.loading) this.loadingInstance.close()
				// }, 2000)
				// 响应错误
				if (status === 500) {
					console.log('inner --> 500');
					ElMessage.error({
						message:
							'服务器错误，不能执行此请求，请稍后重试，若问题一直存在，请与站点管理员联系',
						showClose: true,
					});
				}
				if (status === 504) {
					console.log('inner --> 504');
					ElMessage.error({
						message:
							'服务器暂无响应，请稍后重试，若问题一直存在，请与站点管理员联系',
						showClose: true,
					});
				}
				if (status === 403) {
					ElMessage.error({
						message:
							'拒绝用户证书试图访问此web站点，请与站点管理员联系以建立用户证书权限',
						showClose: true,
					});
				}
				if (status == 401) {
					if (store.state.storeData.lock) {
						ElMessage.error({
							message: '授权失败，请重新登录',
							showClose: true,
						});
					}
					store.state.storeData.lock = false;
					setNotLoggedIn(); // 设置未登录
					router.replace('/login');
				}
				// console.log('lock ---> ',store.state.storeData.lock)
				if (store.state.storeData.lock) {
					if (status === 401 || status === 2001) {
						if (store.state.storeData.lock) {
							ElMessage.error({
								message: '授权失败，请重新登录',
								showClose: true,
							});
						}
						store.state.storeData.lock = false;
						setNotLoggedIn(); // 设置未登录
						router.replace('/login');
					}
				}
				if (status === 502 || error.response == undefined) {
					ElMessage.error({
						message: '网关出错，请与站点管理员联系',
						showClose: true,
					});
				}
				return Promise.reject(error);
			}
		);
	}
}
