import Vue from 'vue'
import uni_request from './uni_request.js'
import {
	wxLogin,
} from '../../apis/login.js';

/* 
	线上appid wxd684a5cf4af0a810
	线上接口地址 http://api.woaidakele.cn
	*** index 页面中跳转的url 对应页面 每次上线之前查看 onLoad 中是否注释判断批发商才能注释的代码
*/



// uni.onNetworkStatusChange(res => { $store.commit('device/NETWORKTYPE_CHANGE', res.networkType) }) // 网络类型变化监听
// uni.getNetworkType({ success(res) { $store.commit('device/NETWORKTYPE_CHANGE', res.networkType) }}) // 获取网络类型

const request = uni_request({
	timeout: 123456,
	// baseURL: 'https://api.wd.cliu.cc/api', //正式版
	baseURL:'https://api.app.cliu.cc/api'
	// baseURL: 'http://test.woaidakele.cn/api'  //测式版
})

request.interceptors.request.use(config => {
	config.header.Authorization = 'Bearer ' + uni.getStorageSync('token')
	// config.header.Authorization =
	// 'Bearer  eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvYXBpLmFwcC5qaXV3ZWl5dW4uY25cL2FwaVwvQ3JlYXRlVG9rZW5UZXN0IiwiaWF0IjoxNjYxOTI5OTEwLCJleHAiOjE2NjI3OTM5MTAsIm5iZiI6MTY2MTkyOTkxMCwianRpIjoiZU54MmNJbXNTMFkxMmo1cCIsInN1YiI6MTIzLCJwcnYiOiIyM2JkNWM4OTQ5ZjYwMGFkYjM5ZTcwMWM0MDA4NzJkYjdhNTk3NmY3In0.41f1zNNwfpWtkXiRFC81tKIy8b1SMP4KI9oyMyqwTGA'

	return config
})

function doRequest(response, url) {
	return new Promise((resolve, reject) => {
		uni.login({
			success({
				code
			}) {
				wxLogin({
					wxcode: code
				}).then(res => {
					if (res.code == 200) {
						uni.setStorageSync('token', res.data.token);
						request.get(url).then(res => {
							if (res.code == 200) {
								resolve(res);
							}
						})
					}
				})
			}
		});
	})

}
request.interceptors.response.use(async (response, ...args) => { // 拦截器
	uni.hideLoading()
	const networkType = uni.getNetworkType();
	if (networkType === 'none') {
		uni.showModal({
			content: '暂无网络连接，请检查后再试',
			showCancel: false
		})
		return
	}
	if (['2g', '3g'].includes(networkType)) {
		//当前设备处于弱网环境
		uni.showModal({
			content: '当前网络信号弱，请检查后再试',
			showCancel: false
		})
		return
	}
	if (response.data.code === 50000 || response.statusCode === 401) { //token过期或者没token
		response = await doRequest(response, args[1]);
		return response
	}
	uni.stopPullDownRefresh() // 停止下拉刷新
	if (response.statusCode === 200) {
		return response
	} else {
		return response
	}
	return response
})

request.onerror = (...args) => { // 请求失败统一处理方法
	uni.hideLoading()
	uni.$emit('HIDELOADING') // 隐藏加载
	uni.stopPullDownRefresh() // 停止下拉刷新
	// uni.$emit('TOAST', `网络好像出了点问题`)
}
export default request