import Vue from 'vue'
import uni_request from './uni_request.js'
import {
	wecatLogin
} from '../api/index.js';


const request = uni_request({
	timeout: 123456,
	baseURL: 'https://api.szy.jiuweiyun.cn/api', //线上
	// baseURL: 'http://192.168.0.6:8024/api', //本地
	// baseURL: 'https://apidemo.szy.jiuweiyun.cn/api', //本地
	header: {
		'content-type': 'application/json'
	}
})
// 请求前拦截器
request.interceptors.request.use(config => {
	uni.showLoading({
		title: '加载中',
		mask: true
	})
	config.header.Authorization = 'Bearer ' + uni.getStorageSync("token")
	return config
})

function doRequest(response, url) {
	return new Promise((resolve, reject) => {
		uni.login({
			success({
				code
			}) {
				wx.getLocation({
					success({
						latitude,
						longitude
					}) {
						wecatLogin({
								openid: '',
								avatar: uni.getStorageSync('userInfo').avatar,
								nickname: uni.getStorageSync('userInfo').nickname,
								code: code,
								longitude,
								latitude
							})
							.then(res => {
								if (res.code == 200) {
									uni.setStorageSync('token', res.data.token);
									request.get(url).then(res => {
										if (res.code == 200) {
											if (url == '/user/get_info') {
												uni.setStorageSync('userInfo', res.data);
											}
											resolve(res);
										}
									})
								}
								if (res.code == 300) {
									uni.switchTab({
										url: '../index/index?isPhone=' + true
									})
								}
							})
							.catch(e => {})
					},
					fail(e) {
						uni.showModal({
							content: '不授权将无法获取到您的位置信息',
							showCancel: false
						});
					}
				});
			}
		});
	})

}
// 请求后拦截器
request.interceptors.response.use(async (response, ...args) => { // 拦截器
	uni.hideLoading()
	if (response.data.code === 50000 && uni.getStorageSync('userInfo')) { //token过期
		response = await doRequest(response, args[1]);
		return response
	} else if (response.data.code === 50000 && !uni.getStorageSync('userInfo')) {
		uni.removeStorageSync('token')
		uni.switchTab({
			url: '/pages/index/index'
		})
	} else if (response.data.code === 200 || response.data.code === 300) {
		return response
	} else {
		// uni.showModal({
		// 	content: response.data.message || '请求失败',
		// 	showCancel: false
		// })
		return response
	}
});

request.onerror = (...args) => { // 请求失败统一处理方法
	console.log(args)
	uni.hideLoading()
	uni.showModal({
		title: '请求失败',
		content: '网络出错',
		// content: JSON.stringify(args),
		showCancel: false
	})
	return Promise.reject(args)
}

export default request
