// uni-app请求封装
import store from "@/store/index.js";
export default class Request {
	http(router, data = {}, method,contentType,url) {
		let that = this;
		// let path = 'http://localhost:7014';
		let path = 'https://api.fhzx.runtzh.com'; 
		uni.setStorageSync('requestPath',path)
		let token="";
		let type = 0
		if(url!=null){
			path= url;
			type = 1
			uni.setStorageSync('requestImagesPath',url)
			token= uni.getStorageSync('AppTokenmini_RTCourse')
			if(router.indexOf("/course_register")!=-1){
				router = router.replace('/course_register','')
				//如果注册页面是服务号授权就放开
				// token= uni.getStorageSync('TOKEN_WEXIN')
			}
		}
		else{
			type = 0
			uni.setStorageSync('requestPath',path)
			token= uni.getStorageSync('AppToken');
		}
		// uni.showLoading({
		// 	title: '加载中'
		// });
		return new Promise((resolve, reject) => {
			// let token = uni.getStorageSync('AppToken');
			var httpContentType='application/x-www-form-urlencoded';
			if(contentType!=undefined){
				//application/json;charset=UTF-8
				httpContentType=contentType;
			}
			var routers=router;
			// 请求
			uni.request({
				header: {
					// 'Content-Type': 'application/x-www-form-urlencoded',
					'Content-Type': httpContentType,
					'AppToken': token
				},
				url: `${path}${router}`,
				data: data,
				method: method,
				success: (res) => {
					//收到开发者服务器成功返回的回调函数
					if(res.data.code==401){//没有权限直接退出到登录界面
						if(type == 1) {
							store.commit('setCoureLogin', 2);
							resolve({ code: 401, data: null });
							return
						}
						let pages = getCurrentPages();
						pages.forEach(function(element) {
						  if(element!=undefined&&element.route=="pages/auth/login"){
						  	resolve(res.data)
						  	return;
						  }
						});
						// let url = pages[ pages.length - 1]; //当前页页面实例
						// //如果登录界面已打开,自动关闭
						// if(url!=undefined&&url.route=="pages/auth/login"){
						//  	resolve(res.data)
						// 	return;
						// }
						uni.navigateTo({
							url:'/pages/auth/login',
							success: () => {
								uni.hideLoading();
								
							},
							fail: () => {
								uni.hideLoading();
							}
						})
						return;
					}
					if (res.data.token&&type==0) {
						uni.setStorageSync('AppToken',res.data.token)
					}
					resolve(res.data)
				},
				fail:(res) =>{
					//接口调用失败的回调函数
				},
				complete:(res) =>{
					//接口调用结束的回调函数（调用成功、失败都会执行）
					if (res.data.code == 401) {
						return false
					}
					uni.hideLoading();
				}
				
			})
		})
		 
	}
	
}
