import store from '../store/index.js'
// const baseurl = 'http://106.14.208.172:8080/'
const baseurl = 'https://api.aibaidu.com.cn/'

const request = (config) => {
	// 拼接完整的接口路径
	config.url = baseurl + config.url;
	//判断是都携带参数
	if(!config.data){
		config.data = {};
	}
	store.commit('setChatSeq')
	config.header = {
		'content-type': config.header && config.header['content-type'] ? config.header['content-type'] : 'application/x-www-form-urlencoded',
		'chat-token': store.state.chatToken,
		'chat-seq': store.state.chatSeq
	}
	if (!config.timeout) {
		config.timeout = 15000
	}
	let promise = new Promise(function(resolve, reject) {
		uni.request(config).then(responses => {
			// 异常
			if (responses[0]) {
				wx.showToast({
					title: '网络超时',
					icon: 'error',
					duration: 2000
				})
				reject({message : "网络超时"});
			} else {
				let response = responses[1].data; // 如果返回的结果是data.data的，嫌麻烦可以用这个，return res,这样只返回一个data
				console.log('response', response);
				if (response.code === 0) {
					resolve(response);
				} else if (response.code === 10001) {
					store.dispatch('login').then(res => {
						console.log("重新登录：", res);
						if (res.chatToken) {
							config.header['chat-token'] = res.chatToken
							uni.request(config).then((res2) => {
								let res2data = res2[1].data;
								resolve(res2data);
							});
						} else {
							resolve(res);
						}
					}).catch(error => {
						reject(error);
					})
				} else if (response.code === 30004) {
					resolve(response);
				} else {
					wx.showToast({
						title: '网络异常' + response.code,
						icon: 'error',
						duration: 2000
					})
					resolve(response);
				}
			}
		}).catch(error => {
			console.error(error)
			reject(error);
		})
	})
	return promise;
};

export default request;