// uni-app请求封装
import store from "@/store";
export default class Request {
	http(router, data = {}, method, contentType, url) {
		let that = this;
		// let path = 'http://127.0.0.1:8113';
		var path = uni.getStorageSync('requestPath')
		// var path = 'https://userapp.his.cdwjyyh.com';
		// var path = 'https://app.rtys.cdwjyyh.com';
		let token = "";
		let pathType = 0
		if (url != null) {
			path = url;
			pathType = 1
			token = uni.getStorageSync('AppTokenmini_RTCourse')
		} else {
			pathType = 0
			uni.setStorageSync('requestPath', path)
			token = uni.getStorageSync('AppToken');
		}
		// uni.showLoading({
		// 	title: '加载中'
		// });
		// 内部真正发请求的方法
		const _request = (retry = false) => {
			return new Promise((resolve, reject) => {
				let CompanyUserToken = uni.getStorageSync('CompanyUserToken');
				var httpContentType='application/x-www-form-urlencoded';
				if(contentType!=undefined){
					//application/json;charset=UTF-8
					httpContentType=contentType;
				}

				uni.request({
					header: {
						'Content-Type': httpContentType,
						'AppToken': token,
						'CompanyUserToken':CompanyUserToken
					},
					url: `${path}${router}`,
					data,
					method,
					success: (res) => {
						if(pathType == 1) {
							store.commit("networkErrorInfo/setStatus", '0');
						}
						//没有权限直接退出到登录界面
						if (res.data.code == 401) {
							const pages = getCurrentPages();
							const cur = pages[pages.length - 1];
							if (cur && cur.route == 'pages/auth/login') {
								resolve(res.data);
								return;
							}
							uni.navigateTo({
								url: '/pages/auth/login'
							});
							return;
						}

						// 更新 token
						if (res.data.token && pathType == 0) {
							uni.setStorageSync('AppToken', res.data.token);
						}
						resolve(res.data);
					},
					fail: (err) => {
						// 看课页面网络异常，刷新重试
						const excludeRouter = ['/app/course/updateWatchDuration','/app/course/getInternetTraffic','/app/course/getIntegralByH5Video','/app/course/getErrMsg']

						if (excludeRouter.indexOf(router) == -1 &&pathType == 1&&err.errMsg.indexOf('request:fail') !== -1) {
							// // 第一次失败 -> 重试
							// if (!retry) {
							// 	_request(true).then(resolve).catch(reject);
							// 	return;
							// }
							// 第二次仍失败
							store.commit("networkErrorInfo/setStatus", '1');
						}
						reject(err);
					},
					complete: (res) => {
						if (res.data && res.data.code == 401) return;
					}
				});
			});
		};

		return _request(); // 第一次调用 
	}

}