import { extend } from "umi-request";
import { showToast } from "vant";
import cleanDeep from "clean-deep";
import { storeData } from "../store";
import { browser, getToken } from ".";
import { postMessage } from "./native-message";
import { getQuery } from "/src/utils/queryString";

const browserInfo = browser();
const query = getQuery();

const request = extend({
	requestType: "form",
	timeout: 10000,
	//prefix: 'https://www.baidu.com',
});

request.interceptors.request.use(
	(url, options) => {
		// console.log(9999,storeData.proxy,storeData.platformApi,options)
		// 内容平台的前缀为cbs-app
		const platformApi = options.isContentCenter ? '/cbs-app' : storeData.platformApi
		const _prefix = storeData.proxy + platformApi;
		/** 
		 * 只有后台才去设置
		 * 暂时没有用到，先注释掉（2024.1.19）
		 */
		// if (storeData.platformType === "WEB" && (apiRouter as any)[url]) {
		// 	url = (apiRouter as any)[url];
		// }
		url = _prefix + url
		const Authorization = getToken();
		const authHeaders: any = {};
		// 内容平台的接口不需要传token，需要传签名
		if (Authorization && !options.isContentCenter && !options.noToken) {
			authHeaders.Authorization = Authorization;
		}
		return {
			url: url,
			options: {
				...options,
				params: cleanDeep(options.params),
				data: cleanDeep(options.data),
				headers: {
					...options.headers,
					...authHeaders,
				},
			},
		};
	},
	{ global: false }
);

request.interceptors.response.use(
	async (res, options) => {
		if (res.status > 299 || res.status < 200) {
			const msg = res.statusText + ", 状态码" + res.status;
			showToast(msg);
		}
		const data = await res.clone().json();

		if (data.code === 403) {
			return data
		}

		if (data.code !== 200 && data.errCode !== 0) {
			const msg = data.msg || data.message || "处理失败，请重试";
			if (!(data.code === 403 || data.code === 401)) {
				// storeData.status = 'error'
				// showToast('登录过期');
			}

			throw new Error(msg);
		}

		return data;
	},
	{ global: false }
);

export default request;
