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) => {
		config.headers["content-type"] = "application/json";
		config.headers["scope"] = "web";
		config.headers["token"] = get("token");
		config.headers["userid"] = get("userId");
		config.headers["X-Ca-Key"] = "29900884";
		config.headers["X-Ca-Signature"] = "osPf2dpzAP9a59VQWGi6";
		config.headers["X-Ca-Signature-Headers"] =
			"header-a,header-b,x-ca-key,x-ca-timestamp";

		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;
