//切换发布版本 true：正式版，连接生产环境；false：测试版，连接测试环境。
var isInner = false; //发布线上后有内外网的配置
var publish_version = false;
// var publish_version = false;

//接口服务器
var server;
var isLoginOut;//退出
var agentName = 'wlyyAgent';

if(publish_version == true) {
	//接口服务器
	server = "http://www.xmtyw.cn/wlyy/";
	//图片文件的服务器路径
    var imgUrlDomain = "http://www.xmtyw.cn/";
    
    if(isInner){
		server = "http://10.95.22.10:8011/wlyy/"
		imgUrlDomain = "http://10.95.22.10:8011/";
	}
}else {
	//接口服务器
	server = "http://172.19.103.88:9092/wlyy/";	 
//	server = "http://192.168.131.24:8080/";//仕杰
//	server = "http://192.168.131.113:8080/";//俊杰
//	server = "http://192.168.131.102:8080/";//伟达
//	server = "http://192.168.131.133:8080/";//文杰
//	server = "http://192.168.131.131:8080/";//文彬
//	server = "http://192.168.131.127:8060/";//逸祥
    //图片文件的服务器路径
    var imgUrlDomain = "http://172.19.103.54/";
}

//弹出框通用
function ask(message,ok,cancel) {
	if(!ok){ok = function(){return;}}
	art.dialog({lock: true,artIcon: 'ask',opacity: 0.4,width: 250,title: '提示',content: message,ok:ok,cancel:cancel})
}
function loading(message){
	if(!message){message="数据加载中，请稍候..."}
	return art.dialog({lock: true,show:true,content: '<img src="../widget/artDialog/4.1.7/images/loading.gif" class="mr10"/>'+message , tips:true})
}
function tip(message,icon) {
	if(!icon){icon='error'}
	art.dialog({lock: true,artIcon: icon,title: '提示',opacity: 0.4,width: 250,content: message,time:2})
}

//newWay 新的处理错误请求的标识
function sendGet(url, params, custError, custSuccess,newWay,timeOut){
	sendPost(url, params, custError, custSuccess, "GET", timeOut, newWay);
}

//设备号
var IMEI = localStorage.getItem('WLYY_IMEI') || uuid(16, 16)
localStorage.setItem('WLYY_IMEI', IMEI)

//请求头去除中文信息
var userAgent = window.localStorage.getItem(agentName)
var sendHead = null
if(userAgent){
	var agentObj = JSON.parse(userAgent)
	agentObj.imei = localStorage.getItem('WLYY_IMEI')
	agentObj.platform = 4
	delete agentObj.name;
	delete agentObj.hospitalName;
	delete agentObj.currentUserRole.name;
	$.each(agentObj.userRole,function(i,o){
		delete o.name
	})
	sendHead = agentObj
}

/**
 * 统一请求ajax发送方法
 * url 请求地址：例如：patient/health_index/add
 * params 请求参数
 * dataType 数据类型：json等
 * reqType 请求方式:get 或 post
 * error 请求失败处理方法
 * success 请求成功处理方法
 * newWay 新的处理错误请求的标识
 */
function sendPost(url, params, custError, custSuccess,dataType, timeOut, newWay) {
	if(dataType==undefined){
		dataType="POST"
	}
	if(isLoginOut) {
		return
	}
	//发送ajax请求
	console.log(server+url);
	// 增加绝对URL（含有http://及https://）的判断，以满足跨域请求（yzh）
	var reqUrl = server + url;
	if(url&&(url.indexOf("http://")>-1 || url.indexOf("https://")>-1)) {
		reqUrl = url;
	}
	$.ajax(reqUrl,$.extend({},{
		data:params || {},
		dataType: 'json',
		type: dataType,
		beforeSend: function(request) {
			var agent = sendHead || {
                imei: localStorage.getItem('WLYY_IMEI'),
                platform: 4
            }
			request.setRequestHeader("userAgent", JSON.stringify(agent));
		},
		timeout: timeOut || 60000, 
		error: function(xht, type, throwErr) {
			console.log(type + " : " + throwErr);
			if(type=="timeout"){
				if(custError){
					custError(type);
					return ;
				}
			}
			if(custError && $.isFunction(custError)) {
				var flag = custError(xht, type, throwErr);
				if(!flag) {
					return ;
				}
			}
			if(newWay == undefined){ //旧的处理逻辑
				if(type == "timeout" || type == "abort") {				
//					alert("程序开了点小差， 请稍后重试！")
				} else if(type == "error" || type == "parsererror" || type == "null") {
//					setTimeout(function() {
//						alert("程序开了点小差， 请稍后重试！")
//					},0);
				}
			}else if(newWay){
			    alert("数据加载失败，请检查网络无误后下拉刷新。");
			}
		},
		success: function(res) {
			var tip = "";
			if(res.status == 999) {
				tip = "此账号已在别处登录，请重新登录";
				goToLogin(tip)
				return;
			} else if(res.status == 998) {
				tip = "登录超时，请重新登录";
				goToLogin(tip)
				return;
			} else if(res.status == 997) {
				tip = "此账号未登录，请先登录";
				goToLogin(tip)
				return;
			}else{
				custSuccess(res);
			}
		}
	}))
}
//跳转登录页
function goToLogin(message){
//	window.localStorage.removeItem(agentName)
	top.ask(message,function(){
		top.location.href='/health-education/login.html'
	})
}

function uuid(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [],
        i;
    radix = radix || chars.length;
    if(len) {
        for(i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
        var r;
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';
        for(i = 0; i < 36; i++) {
            if(!uuid[i]) {
                r = 0 | Math.random() * 16;
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
        }
    }
    return uuid.join('');
}

function getSysDate(plus) {
	var d = new Date();
	var year = d.getFullYear();
	var month = d.getMonth() + 1;
	var day = d.getDate();
	var h = d.getHours();
	var mins = d.getMinutes();
	var s = d.getSeconds();
	if(month < 10) month = "0" + month;
	if(day < 10) month = "0" + day;
	if(h < 10) h = "0" + h;
	if(mins < 10) mins = "0" + mins;
	if(s < 10) s = "0" + s;
	if(!plus) {
		return year + "-" + month + "-" + day + "" + h + ":" + mins + ":" + s;
	} else {
		return(year + 1) + "-" + month + "-" + day + "" + h + ":" + mins + ":" + s;
	}
}

function getSysDatePlus(plus) {
	var now = new Date();
	var d = new Date(now.getTime() + plus * 24 * 3600 * 1000);
	var year = d.getFullYear();
	var month = d.getMonth() + 1;
	var day = d.getDate();
	if(month < 10) month = "0" + month;
	if(day < 10) day = "0" + day;
	return year + "-" + month + "-" + day
}

//获取链接上的参数
function GetRequest() {  
   var url = location.search; //获取url中"?"符后的字串
   var theRequest = new Object();
   if (url.indexOf("?") != -1) {
      var str = url.substr(1);
      strs = str.split("&");
      for(var i = 0; i < strs.length; i ++) {
         theRequest[strs[i].split("=")[0]]=(strs[i].split("=")[1]);
      }
   }
   return theRequest;
}
var Request = GetRequest();
/*
 * 获取图片路径
 */
function getImgUrl(str){
	if(typeof str != 'string'){
	    return "";
	}
	if(str.length == 0){
        return "";
    }else{
        if(str.indexOf("../../../")>-1){
            //访问本地路径
            return str.replace('../../.','');
        }else if((str.indexOf("http://")>-1) || (str.indexOf("https://")>-1)){
            return str;
        }else{
            //服务器上的图片路径
            return imgUrlDomain + str
        }
    }
}