 const baseUrl = 'http://58.56.15.138:20189/' 
 

//const baseUrl = 'https://api.dms.66km.com/'
 
import md5 from './MD5.js'



const http = (url = '', date = {}, type = 'POST', header = {
}) => {
    return new Promise((resolve, reject) => {
		//console.log(burl2 + url)
		header={};
		const logInData = uni.getStorageSync("logInData");
		header['token']=logInData.token;
		header['uid']=logInData.uid; 
		// header['token']='BA205B2ABFE4445EA5D111042E7BCE56';
		// header['uid']='BE98A41B9E0C44C1B5EDCBCE39D550D0'; 
		header['Content-Type']='application/x-www-form-urlencoded';
		//console.log(header)
        uni.request({
            method: type,
            url: baseUrl + url,
            data: date,
            header: header,
            dataType: 'json',         
        }).then((response) => {
           /* setTimeout(function() {
                uni.hideLoading();
            }, 200); */
			uni.hideLoading();
            let [error, res] = response;
			
			if(res.data.code==1){
				 uni.showToast({
				     title: res.data.msg ? res.data.msg : '接口错误',
				 	 icon:'none',
				     duration: 2000,
				 });
				
			}
			else if(res.data.code==401){
				 uni.showToast({
				     title: res.data.msg,
				 	 icon:'none',
				     duration: 3000,
				 });
				uni.clearStorageSync()
				 uni.navigateTo({
					url:'../logIn/logIn'
				 })
			}else if(res.data.code==0){
				// 正常
				 resolve(res.data);
			}
            
        }).catch(error => {
            let [err, res] = error;
            reject(err)
        }) 
    });
}

function getToken(url,date,type,header){
	var header={};
    //var userId=uni.getStorageSync("devData").userId;
	//var devData=uni.getStorageSync("devData")
	header['Content-Type']='application/x-www-form-urlencoded';
	uni.request({
	    method: "POST",
	    url: burl2 + '/sys/getTokenByUserID',
	    data: {
			userId:userId
		},
	    header: header,
	    dataType: 'json',         
	}).then((response) => {
	    let [error, res] = response;
		var accessToken=res.data.data.accessToken.accessToken;
		devData.accessToken=accessToken;
		uni.setStorage({
			   key: 'devData',
			   data:devData,
			   success: function () {
				   refresh(url,date,type,header) //刷新接口
			   }
		 });
		  // console.log(accessToken)
	}).catch(error => {
	   
	}) 
}

function refresh(url,date,type,header){
	uni.request({
	    method: type,
	    url: burl2 + url,
	    data: date,
	    header: header,
	    dataType: 'json',         
	}).then((response) => {
	   setTimeout(function() {
	        uni.hideLoading();
	    }, 200); 
	    let [error, res] = response;
	  
		if(res.data.code==403){
			uni.showToast({
			     title: res.data.msg,
			 	 icon:'none',
			     duration: 3000,
			 });
			 uni.navigateTo({
				url:'../login/login'
			}) 
		}
	    resolve(res.data);
	}).catch(error => {
	    let [err, res] = error;
	    reject(err)
	})
}

export default {
	http,baseUrl
}