/**
 * @Method Description
 * @Author: zjd@
 * @Description: 数据请求整合 处理
 * @BASE_URL server 
 * @param {a===Object||file} 传给后台参数Method 请求方法   url  所请求的接口路径
 * @return  Promise对象  所有数据信息
 * @createTime: 2024-7-22 15:05:06
 */
import BASE_URL from "./config.js";
import version from '@/utils/version.js'
import client_type from "@/utils/client_type.js"
export const request = (url, data = {}, method = 'post', loading = false, contentType =
	'application/json',extraHeader={},responseType=false) => {
	if (loading) {
		uni.showLoading({
			title: '加载中',
			mask: true
		})

	};
	
	let token = '';
	if (process.env.UNI_PLATFORM == "h5") {
		if (window.location.href.indexOf('//.igandan.com') > -1) {
			token = uni.getStorageSync('AUTH_TOKEN_App');
		} else {
			token = uni.getStorageSync('DEV_AUTH_TOKEN_App');
		}
	} else if(process.env.UNI_PLATFORM == "mp-weixin") {
		const {
			envVersion
		} = uni.getAccountInfoSync().miniProgram;
		if (envVersion == "release") {
			token = uni.getStorageSync('AUTH_TOKEN_App');
		} else {
			token = uni.getStorageSync('DEV_AUTH_TOKEN_App');
		}
	}else{
		token = uni.getStorageSync('AUTH_TOKEN_App');
		
	}

	let header = {
		'content-type': contentType,
	}
	let defaultData={}
	
	let freeList=['/manager/getSystemTimeStamp','/expertAPI/smsLogin','/login/mobile','/expertAPI/login','/expertAPI/index','/expertAPI/wechatLogin']
	 let postData={
		 ...data
	 }
	if(freeList.indexOf(url)!=-1){
		if(freeList[4].indexOf(url)!=-1){
			 if(!token){
				 header['Authorization']='Bearer ' + ''
			 }else{
				  header['Authorization']='Bearer ' + token;
				  let userInfo= uni.getStorageSync('userInfo')
				  defaultData = {
				  			 mini_version: version,
							 version: uni.getStorageSync('app_version'),
				  			user_uuid:userInfo.uuid,
				  			client_type:client_type,
							timestamp:new Date().getTime(),
							
				  		}
				postData={
						 ...data,
						 ...defaultData
				}
			 }
		}
	}else{
			if(token){
				 header['Authorization']='Bearer ' +token;
				 let userInfo= uni.getStorageSync('userInfo')
				 console.log(userInfo)
				   defaultData = {
					        mini_version: version,
					        version: uni.getStorageSync('app_version'),
				 			user_uuid:userInfo.uuid,
				 			client_type:client_type,
							timestamp:new Date().getTime()+""
				 	}
				
					postData={
							 ...data,
							 ...defaultData
					}
			}
   }
	
      
	console.log(postData);
	return new Promise(function(e, n) {
		let timestamp = Date.now();
		uni.request({
			data: postData,
			url: url.indexOf('http') != -1 ? url : encodeURI(BASE_URL + url),
			method: method,
			sslVerify: false,
			header:{...header,...extraHeader},
			responseType:responseType?responseType:"text",
			timeout: 100000,
			success: async (res) => {
				console.log(222222222)
				console.log(res)
				var Authorization_token = res.header.Authorization;
				if (Authorization_token) {
					uni.setStorageSync('AUTH_TOKEN_App', Authorization_token);
				}
				if (loading) {
					uni.hideLoading();
				};
				if(url.indexOf('manager/getSystemTimeStamp')!=-1){
					e(res)
				}else if (res.data.code == 200 || res.data.code == 1 || res.data.code == "1" || res.data.code == "200" ){
					e(res.data)
				}else if (res.data.code == 401 || res.data.code == 403 || res.data.code ==
					405 || res.data.code == 406 || res.data.code == 37006 || res.data.code == 35002) {
						uni.hideLoading();
						if(process.env.UNI_PLATFORM == "mp-weixin"){
							uni.redirectTo({url:'/pages_app/login/login'})
						}
		// else{
		// 					uni.navigateTo({url:'/pages_app/login/login'})
		// 				}
					 uni.sendNativeEvent('getNewToken', {
						msg: 'getNewToken'
					 },ret => {
						console.log('ret数据');
					console.log(ret);
					uni.setStorageSync('AUTH_TOKEN_App', ret);
					let pages = getCurrentPages();
					let len = pages.length
					let curParam = pages[len - 1].options //获取当前页面参数
					let param = []
					for (let key in curParam) { //获取key=value键值对格式数组
					param.push(key + '=' + curParam[key])
					}
					let _url = '' //除去第一个参数拼接后面参数
					param.forEach((item, i) => {
					if (i != 0) { //拼接&符号，由于第一组前拼接的是？所有第一组需要单独处理
					_url += '&' + item
					}
					})
					
					let redirectUrl = '/' + pages[len - 1].route + '?' + param[0] + _url //最终格式**/pages/index/index/?id=11&name='boyyang'&sex='man'**
					console.log('redirectUrl');
					console.log(redirectUrl);
					uni.redirectTo({
						url: redirectUrl
					})
					 })
					
					

					// uni.redirectTo({
					// 	url: '/pages_app/login/login'
					// });
					

				} else if (res.data.code == 500) {

					uni.showToast({
						title: res.data.message,
						icon: 'none',

					})
					n(res)
				} else {
					
					if(url.indexOf('addOutPatientA')!=-1 || url.indexOf('checkVersion')!=-1){
						e(res.data)
					}else if(url.indexOf('downloadGanDanFile')!=-1){
						console.log(res)
						e(res.data)
					}else if(res.data.code==35002){
						n(res)
						uni.sendNativeEvent('goTabbarPage', {
							msg: 'home'
						},ret => {
							console.log(ret);
						})
					   plus.runtime.quit();
					   
					}else if(res.data.code==106){
                          e(res.data)
					}else if(res.data.code==202){
						e(res.data)
				  }else{
						uni.showToast({
							title: res.data.message,
							icon: 'none'
						});
					     n(res)


				}
				}
			},
			fail: function(err) {
				console.log(444444444)
				console.log(err)
				"request:fail " === err.errMsg && msg("请求数据失败！"), n(err.data);
			}
		});
	});
}