import axios from "axios";
import { state } from "../store/state";
import { get } from "./cookie";

const service = axios.create({
	withCredentials: false, // send cookies when cross-domain requests
	timeout: 60 * 1000, // request timeout
});

service.interceptors.request.use(
	(config) => {
		const token = sessionStorage.getItem("xcjyToken");

		config.headers.Authorization = `Bearer ${token}`;
		config.headers["content-type"] = "application/json";
		config.headers["Cross-Origin-Embedder-Policy"] = "require-corp";
		config.headers["Cross-Origin-Opener-Policy"] = "same-origin";
		if (config.url.indexOf("/auth") !== -1) {
			//如果是请求auth接口，则不带token
			delete config.headers.Authorization;
		}
		return config;
	},
	(error) => {
		return Promise.reject(error);
	}
);

service.interceptors.response.use(
	(response) => {
		const { config, data: res } = response;
		return res;
	},
	(err) => {
		return Promise.reject(err);
	}
);
// http method
export const METHOD = {
	GET: "get",
	POST: "post",
	DEL: "delete",
	PUT: "put",
	PATCH: "patch",
};

/**
 * axios请求
 * @param url 请求地址
 * @param method {METHOD} http method
 * @param params 请求参数
 * @returns {Promise<AxiosResponse<T>>}
 */
export function request(url, method, params, config) {
	switch (method) {
		case METHOD.GET:
			return service.get(url, { params, ...config });
		case METHOD.POST:
			return service.post(url, params, config);
		case METHOD.DEL:
			return service.delete(url, { params, ...config });
		case METHOD.PUT:
			return service.put(url, params, config);
		case METHOD.PATCH:
			return service.patch(url, params, config);
		default:
			return service.get(url, { params, ...config });
	}
}
export default service;
