/* eslint-disable */
import Request from './request';
// import {
// 	refreshToken
// } from '@/api/login';
import indexConfig from '@/config/global.config.js';
import mUtil from '@/utils/index.js';
import store from '@/store';

const http = new Request();

// request全局参数设置
http.setConfig(config => {
	/* 设置全局配置 */
	config.baseUrl = indexConfig.baseShopUrl || indexConfig.baseUrl; /* 根域名不同 */
	const systemInfo = uni.getSystemInfoSync();
	const systemInfoHeaders = {
		'device-name': systemInfo.brand, // 设备名称
		width: systemInfo.screenWidth, // 屏幕宽度
		height: systemInfo.screenHeight, // 屏幕高度
		os: systemInfo.platform, // 客户端平台
		'os-version': systemInfo.system // 操作系统版本
	};
	config.header = {
		...config.header,
		...systemInfoHeaders
	};
	return config;
});

let isRefreshing = false;
let requests = [];
http.interceptor.request(
	config => {
		if (config.isToken == false) {

		} else {
			config.header['apiToken'] = uni.getStorageSync('apiToken');
		}
		/* 请求之前拦截器 */

		// config.header['client'] = 'applet';
		config.header['client'] = 'app';
		// 单商户
		// config.header['merchant-id'] = uni.getStorageSync('merchantId') || 1;
		return config;
	},
	error => {
		return Promise.reject(error);
	}
);

// 刷新refreshToken
async function handleRefreshToken(refresh_token) {
	const params = {};
	params.group = mUtil.platformGroupFilter();
	params.refresh_token = refresh_token;
	await http.post(refreshToken, params).then(async r => {
		store.commit('login', r.data);
		isRefreshing = false;
	});
}
http.interceptor.response(
	async response => {
			if (response.header['refresh_token']) {
				store.commit('login', response.header.refresh_token);
				uni.setStorageSync('apiToken', response.header.refresh_token);
			}
			/* 请求之后拦截器 */
			switch (response.data.code) {
				case 200:
					return response.data;
				case 400:
					mUtil.toast('错误的请求');
					return Promise.reject(response.data.message);
					break;
				case 500:
					if (!response.config.hideToast) {
						mUtil.toast(response.data.msg);
					}
					return Promise.reject(response.data.msg);
				case 50000:
					isRefreshing = false;
					if (response.config.url === refreshToken) {
						uni.removeStorageSync('apiToken');
						await store.commit('logout');
						uni.showModal({
							content: '会话已过期，是否跳转登录页面？',
							success: confirmRes => {
								if (confirmRes.confirm) {
									// uni.removeStorageSync('shop')
									uni.navigateTo({
										url: '/pages/login/index'
									})
								}
							}
						});
					} else {
						let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
						let curRoute = routes[routes.length - 1].route // 获取当前页面路由，也就是最后一个打开的页面路由
						// 如果refreshToken为空 则直接跳转登录
						console.log('apiToken:' + store.state.refreshToken)
						if (!store.state.refreshToken) {
							uni.removeStorageSync('apiToken');
							// uni.removeStorageSync('shop')
							await store.commit('logout');
							// if (curRoute != 'pages/index/personal') {
							uni.navigateTo({
								url: "/pages/login/index"
							})
							// }
							throw response.data.message;
							break;
						} else {
							// isRefreshing同一个页面只执行一次
							if (!isRefreshing) {
								isRefreshing = true;
								// 刷新token
								await handleRefreshToken(store.state.refreshToken, response);
								requests.forEach(cb => cb());
								requests = [];
								isRefreshing = false;
								return http.request(response.config);
							} else {
								return new Promise(resolve => {
									// 将resolve放进队列，用一个函数形式来保存，等token刷新后直接执行
									requests.push(() => {
										resolve(http.request(response.config));
									});
								});
							}
						}
					}
					break;
				case 99999:
					mUtil.toast(response.data.msg);
					setTimeout(() => {
						mUtil.getCurrentPageFun('/pages/research/pay-password')
					}, 1000)
					return
				case 405:
					mUtil.toast(response.data.msg);
					return Promise.reject(response.data.msg);
				case 404:
					mUtil.toast(response.data.msg);
					return Promise.reject(response.data.msg);
				case 429:
					mUtil.toast(response.data.msg);
					return Promise.reject(response.data.msg);
				default:
					mUtil.toast(response.data.msg);
					return Promise.reject(response.data.msg);
			}
		},
		error => {
			return Promise.reject(error);
		}
);

export {
	http
};