import host from "./config.js";
import { goto } from '@/utils/myfun.js';
// let pages = getCurrentPages();
// let currentRoute = pages[pages.length - 1];

export default ({ url, method, params, header, baseURL }) => {
	baseURL = baseURL ? baseURL : host.Hhost;

	return new Promise((resolve, reject) => {
		uni.request({
			url: baseURL + url,
			method,
			header,
			data: {
				...params
			},
			success(res) {
				resolve(res.data);
			},
			fail(err) {
				reject(err);
			}
		});
	});
};

uni.addInterceptor('request', {
	invoke(args) {
		// console.log('interceptor-invoke', args)		//请求前
		let token = uni.getStorageSync('token');
		if (token) args.header.token = token;
	},
	success(args) { //请求成功
		if (args.data.code == 400) {
			uni.removeStorageSync('token');
			uni.showToast({
				title: args.data.msg,
				duration: 2000,
				icon: "none",
			});
			setTimeout(() => {
				// #ifdef  H5 || APP-PLUS
				goto("/pages/my/login");
				// #endif
				// #ifdef  MP-WEIXIN
				uni.switchTab({ url: "/pages/my/index" });
				// #endif
			}, 1500);
		}
		if ([-1, 301].includes(args.data.code)) {
			uni.showToast({
				title: args.data.msg,
				duration: 2000,
				icon: "none",
			});
		}
	},
	fail(err) {
		// console.log('interceptor-fail', err)			//请求失败
	},
	complete(res) {
		// console.log('interceptor-complete', res)		//成功|失败
	}
})
