import { showCustomModal } from "./util";
import { BASEURL, REQUESTIMEOUT } from "./config";
console.log(BASEURL, 'BASEURLBASEURLBASEURL')
const BASE_URL = BASEURL;
const REQUEST_TIMEOUT = REQUESTIMEOUT;


export default function request(options) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: options.url,
			method: options.method || 'GET',
			data: options.data || {},
			header: options.header || {
				'Content-Type': 'application/json',
				'Authorization': uni.getStorageSync('token')
			},
			success: (res) => {
				console.log(res, 'request')
				if (res.code === 200) {
					resolve(res.data);
				} else {
					reject(res);
				}
			},
			fail: (err) => {
				reject(err);
			}
		});
	});
}

uni.addInterceptor("request", {
	invoke(args) {
		// request 触发前拼接 url
		args.url = BASE_URL + args.url
	},
	success(res) {
		const {
			code,
			msg
		} = res.data;
		console.log('addInterceptor', code, msg)
		if(code === 401){
			showCustomModal({
				content: msg,
				success: function() {
					uni.getStorageSync('token', '')
					uni.reLaunch({ // 登录超时跳转登录页面
						url: "/pages/user/login"
					})
				}
			});
		}
		if (code !== 200) {
			showCustomModal({
				content: msg,
			});
			// uni.navigateTo({
			// 	url: "/pages/login/login"
			// });
			return;
		}
		
		return Promise.resolve(res.data);
	},
	fail(err) {
		uni.showToast({
			title: "网络异常",
			icon: "error",
			duration: 2000
		});
		return Promise.reject(err);
	}
});