import netConfig from './config.js'
import {
	getToken
} from '@/utils/auth'
import { logout } from '@/api/common.js'

const errorCode = {
	'401': '认证失败，无法访问系统资源',
	'403': '当前操作没有权限',
	'404': '访问资源不存在',
	'500': '服务器错误',
	'default': '系统未知错误，请反馈给管理员'
}

const requestUrls = {};

// 请求拦截
uni.addInterceptor('request', {
	invoke(config) {
		if (config.method == 'GET' && config.data) {
			const queryStr = joinGetQuery(config.url, config.data);
			config.url += queryStr;
		}
	}
})

function request (options, config) {
	return checkNetworkStatus()
		.then(res => {
			return requestFun(options, config)
		})
		.catch(error => {
			uni.showToast({
				icon: 'error',
				title: error.msg
			})
		})
}

// 请求函数
function requestFun ({ url, method, data = {} }, config = { loading: true }) {
	url = netConfig.baseUrl + url;
	const header = {
		// 'Authorization': 'Bearer ' + getToken()
	}
	
	// 合并请求头
	config.header = Object.assign({}, header, config.header);
	
	// 终止重复请求
	const abortObj = requestUrls[url];
	if (abortObj && abortObj.method == method) {
		abortObj.task.abort && abortObj.task.abort();
		delete requestUrls[url];
	}
	
	const requestConfig = Object.assign({}, config);
	delete requestConfig.loading;
	
	config.loading && uni.showLoading({ mask: true })
	
	return new Promise((resolve, reject) => {
		const task = uni.request({
			url,
			method,
			data,
			...requestConfig,
			success: res => {
				const {
					code = 200,
					data = {},
					rows = [],
					msg = '请求错误'
				} = res.data;
				
				if (code == 0) {
					uni.showToast({
						icon: 'error',
						title: msg
					})
					reject(msg)
					return false
				}
				
				resolve(data)
			},
			fail: (error) => {
				console.log('Request Error', error);
				uni.showToast({
					icon: 'error',
					title: '请求失败'
				})
				reject(error);
			},
			complete: () => {
				delete requestUrls[url];
				if (Object.keys(requestUrls).length <= 0) {
					config.loading && uni.hideLoading();
				}
			}
		})
		
		requestUrls[url] = {
			task,
			method
		}
	})
}

export default request

// 处理401状态码
function dispose401 (response) {
	logout().then(() => {
		uni.showModal({
			title: '提示',
			content: '登录已超时，请重新登录！',
			confirmText: '去登录',
			success: function({
				cancel
			}) {
				// if (cancel) return false;
				uni.navigateTo({
					url: '/pages/login/login'
				})
			}
		});
	}).catch(() => {})
}

// 处理500状态码
function dispose500 (response, reject) {
	const msg = response.data.msg || errorCode[500];
	uni.showToast({
		title: msg,
		icon: 'error',
		complete: () => {
			reject(new Error(msg))
		}
	})
}

// 处理其他状态码
function disposeOther (response, reject) {
	const msg = response.data.msg || errorCode['default'];
	uni.showToast({
		title: msg,
		icon: 'error',
		complete: () => {
			reject(new Error(msg))
		}
	})
}

/**
 * get请求拼接参数
 * @param {Object} query
 */
function joinGetQuery(url, query) {
	let queryStr = '';
	const firstSing = url.includes('?') ? '&' : '?'
	Object.keys(query).forEach((key, index) => {
		queryStr += index === 0 ? `${firstSing}${key}=${query[key]}` : `&${key}=${query[key]}`
	});

	return queryStr;
}

// 检查网络状态
function checkNetworkStatus () {
	return new Promise((resolve, reject) => {
		uni.getNetworkType({
			success (res) {
				const { networkType } = res;
				networkType === 'none' ? reject({status: false, msg: '无网络连接'}) 
																: resolve({ status: true, msg: '网络连接正常' })
			},
			fail (err) {
				reject({ status: false, msg: err.msg || '网络错误' });
			}
		})
	})
}
