import Request from './request'
import apiList from './apis.js'
import store from '@/rokeTools/store/index.js'
import {
	CLIENT_URL_KEY,
	SESSION_ID_KEY
} from '../../env.js';

/* 
网络请求工具,使用参考,App的版本判断中已使用
          this.$http('login.mobile_app_version').then(data => {
				if (data.state == 'success') {
				} else {
				}
			}).catch((err) => {
			}); 
 
 */
const rokeRequest = new Request();
export default function http(
	url,
	data = {},
	toastBefore = '', // 请求前加载提示
	toastAfter = false, // 请求后错误提示
) {
	let api = getApiPath(url);
	/* 请求之前拦截器 */
	rokeRequest.interceptor.request((config, cancel) => {
		// let token = uni.getStorageSync('token');
		// if (api.auth && !token) {
		// 	store.dispatch('showAuthModal');
		// 	uni.hideLoading()
		// 	throw (`暂未登录,已阻止此次API请求: '${api.url}'`);
		// }
		// token && rokeRequest.setConfig(config => {
		// 	config.header.token = token
		// })


		//设置baseUrl
		rokeRequest.setConfig(config_this => {
			if (api.noSetContentType) {
				//有些接口使用'Content-Type': 'application/json',请求会报错，根据api返回信息清除
				config_this.header['Content-Type'] = "";
			}
			let baseUrl = uni.getStorageSync(CLIENT_URL_KEY);
			// let baseUrl = "http://58.56.9.105:8011"
			let xSessionId = uni.getStorageSync(SESSION_ID_KEY);
			config_this.baseUrl = baseUrl;
			config_this.header['x-session-id'] = xSessionId;
		})
		if (toastBefore !== '') {
			uni.showLoading({
				title: toastBefore,
				mask: true
			});
		}
		return config
	});

	/* 请求之后拦截器 */
	rokeRequest.interceptor.response((response) => {
		uni.hideLoading();
		if (response.code === 0) {
			if (toastAfter) {
				uni.showToast({
					title: response.msg || '请求出错,稍后重试',
					icon: 'none',
					duration: 1000,
					mask: true
				});
			}
		}

		// token过期注销
		if (response.code === 401) {
			// store.dispatch('logout');
			// store.dispatch('showAuthModal');
			// throw (`登录已过期或注销,已阻止此次API请求: '${api.url}'`);
		}
		return response
	})
	// console.log(JSON.stringify(api));

	return rokeRequest.request({
		url: api.url,
		data,
		method: api.method
	})

}

// 组装接口路径
function getApiPath(url) {
	let apiArray = url.split(".");
	let api = apiList;
	apiArray.forEach(v => {
		api = api[v];
	});
	return api;
}