import app from '@/App'
import {goLogin} from '@/utils/util.js'

/**统一请求接口
* 请示示例：const json = await this.api.getOpenId({m:'get',q:{jsCode:jsCode},loading:false,toast:false},)
* 参数说明：getOpenId 请求路径.{{m:'get' 请求方式 不传为post, q:{} 请求参数}, loading:false 是否显示loading 不传显示, toast:false 是否显示toast 不传显示} 
**/
const uniRequest = async (params={},url) => {
		let getNetworkType = await uni.getNetworkType({})
		if(getNetworkType[1].networkType === 'none'){
			uni.showToast({title:'网络未连接',icon:'none'})
			return
		}
		if (typeof(params.loading)=='undefined') {
				uni.showLoading({title: 'Loading...',mask: true})
		}
		let query = params.q || {}
		let res = await uni.request({
			   header: {
							"Content-Type": "application/x-www-form-urlencoded",
							"memid": app.globalData.userInfo==null?'':app.globalData.userInfo.id,
							"token": app.globalData.userInfo==null?'':app.globalData.userInfo.token
						},
						url: url, 
						method: params.m || 'POST',
						data: query,
						timeout: 10000,
		})
		if(res[1]){
			  uni.hideLoading() 
					if(res[1].data.code==0){
							return res[1];
					}else{
						 if(res[1].data.code==100 || res[1].data.code==101){ //未登录，或登录失效
								  uni.showModal({
												  title:"温馨提示",
													 content:res[1].data.msg,
														success(res){
															  if(res.confirm){
																		 goLogin();
																	}
														}												
								  })
								  return res[1]
							}else{
								  if (typeof(params.loading)=='undefined') {
												uni.showToast({title:res[1].data.msg,icon:'none'})
										}
										return res[1]
							}
					}
		}else{
			uni.showToast({title:'网络请求超时！',icon:'none'})
			setTimeout(()=>{uni.hideLoading()},1500)
		}
	}
	
module.exports = { uniRequest };
