import configs from '@/configs/env';
import { tokenList } from '@/configs/whitelist';
import Constants from '@/configs/constant';
import Http from '@/utils/Http/Http';
import MD5 from '@/assets/scripts/md5';
import store from '@/store';

import { redirectToLogin } from '@/common/NavFuncs';

// TOKEN request拦截器
const add_token_to_request_interceptor = function (res) {
	const url = `${res.baseUrl}${res.url}`.replace(configs.baseUrl, '');
	let inWhitelist = false;
	for (let whiteUrl of tokenList) {
		if (url.indexOf(whiteUrl) > -1) {
			inWhitelist = true;
			return res;
		}
	}
	// in white list
	if (inWhitelist) {
		return res;
	}
	// not in white list
	// const token = uni.getStorageSync(Constants.TOKEN);
	const token = store.state.token;
	// console.log(`token: `, token);
    if (!token) {
        redirectToLogin();
		throw new Error('请登录');
    }
	const header = res.header || {};
	res.header = { 'Authorization': `Bearer ${token}`, ...header };
	return res;
}

// params加密拦截器
const params_encryption_request_interceptor = function (res) {
	const url = `${res.baseUrl}${res.url}`.replace(configs.baseUrl, '');
	const { data } = res;
	const keys = [], values = [];
	if (data) {
		for (let key of Object.keys(data)) {
			keys.push(key);
		}
		keys.sort();
		keys.forEach(key => {
			let value = data[key];
			if (typeof value === 'string'
				|| typeof value === 'number') {
				// do nothing
			} else if (typeof value === 'boolean') {
				value = `${value}`;
			} else {
				value = '';
			}
			values.push(value);
		});
	}
	const encryptList = [url, keys, values];
	const VALIDATE = MD5(JSON.stringify(encryptList));
	// console.log(`encrypt=${JSON.stringify(encryptList)}, MD5=${VALIDATE}`);
	const header = res.header || {};
	res.header = { VALIDATE, 'ifLogResponse': '1', ...header };
	return res;
}

// 基础响应成功拦截器
const base_res_resolve_interceptor = function (res) {
	console.log(`http ok: `);
    if (res.data && !res.data.code) {
        if (res.data && res.data.message) {
    		uni.showToast({
    			title: res.data.message,
				icon:'none',
    			position:'bottom'
    		});
        }
        return Promise.reject(res)
    }
    return res.data;
}
// 基础响应拒绝拦截器
const base_res_reject_interceptor = function (err) {
	console.log(`http error: `);
    if (err.data && err.data.message) {
        uni.showToast({
			title: err.data.message,
			icon: 'none',
			position:'bottom'
		});
    } else {
		let errMsg = err.message || '系统错误';
		if (err && err.errMsg) {
			if (err.errMsg.indexOf('fail timeout') > -1) {
				errMsg = '连接超时';
			} else if (err.errMsg === 'request:fail') {
				errMsg = '网络连接失败';
			}
		}
        uni.showToast({
			title: errMsg,
			icon: 'none',
			position:'bottom'
		});
    }
    return Promise.reject(err)
}

const apis = Object.keys(configs.apis).reduce((res, key) => {
	res[key] = new Http({
		baseUrl: `${configs.baseUrl}${configs.apis[key]}`
	});
	//res[key].interceptors.request.add(add_token_to_request_interceptor);
	//res[key].interceptors.request.add(params_encryption_request_interceptor);
	res[key].interceptors.response.add(base_res_resolve_interceptor, base_res_reject_interceptor);
	return res;
}, {});

export default apis;