// http封装库
import axios from 'axios';
import { getEnvConfig, removeStorage, storageKey, getMid, getUserInfo, appVersionCode } from '../utils/help';
// 测试数据(需手动开启关闭)
// import '../mockjs/index';

// axios config
const { host } = getEnvConfig();
const instance = axios.create({
	baseURL: host,
	timeout: 240000,
	headers: {
		'content-type': 'application/json',
		Accept: 'application/json',
	},
});

// 响应拦截器
instance.interceptors.response.use(
	(res) => {
		if (res.data.code === -107) {
			// token失效
			removeStorage(storageKey.userInfo);
			location.reload();
		} else {
			return res.data;
		}
	},
	function (err) {
		return Promise.reject(err);
	}
);

export const postRequest = (url, params = {}, config = null) => {
	const myConfig = {};
	const userInfo = getUserInfo();
	if (config) {
		Object.assign(myConfig, config);
	}
	let isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
	params = Object.assign(
		{
			baseInfo: {
				mid: getMid(),
				machineCode: getMid(),
				loginUid: (userInfo && userInfo.uid) || '',
				token: (userInfo && userInfo.accessToken) || '',
				appType: isMobile ? 2 : 1,
				appVersionCode,
			},
		},
		params
	);

	return instance
		.post(url, params, myConfig)
		.then((res) => {
			return res;
		})
		.catch((err) => {
			return err;
		});
};

export const getRequest = (url, params = {}, config = null) => {
	const myConfig = Object.assign({}, { params: Object.assign({}, params) });
	if (config) {
		Object.assign(myConfig, config);
	}

	return instance
		.get(url, myConfig)
		.then((res) => {
			return res;
		})
		.catch((err) => {
			return err;
		});
};
