//切换发布版本 true：正式版，连接生产环境；false：测试版，连接测试环境。
//var publish_version = true;
var publish_version = false;

if(publish_version){
	//正式环境（厦门i健康）
	var server = "http://www.xmtyw.cn/wlyy/";
	var appId = "wxad04e9c4c5255acf";
	var urlName = "wlyy";
	var weixinUrl = "www.xmtyw.cn";
	var agentName = "wlyyAgent";
	var agentName1 = "wlyyAgent1";
	var OpenidAgent = "OpenidAgent";
	var judgeAgent = "judgeAgent";
	var pageName = "pageurl";
	var wxurl = "http%3a%2f%2fwww.xmtyw.cn%2fwlyy%2fwx%2fhtml";
	var imurl="http://120.41.253.95:3000";
	var imurl="http://27.155.101.77:3000";
	var imgUrlDomain = 'http://www.xmtyw.cn/';
}else{
	//测试环境（健康之路i厦门）
	//var server_jm = "http://ehr.yihu.com/wlyy_jm/";// 集美中医体检
//	var server = "http://ehr.yihu.com/wlyy/"; 
	var server = "http://172.19.103.88:9092/wlyy/";
//	var server = "http://192.168.131.154:8080/";//张丹
//	var server = "http://192.168.131.24:8080/";//仕杰
//	var server = "http://192.168.131.127:8060/";//逸祥
//	var server = "http://192.168.131.133:8080/";//文杰
//	var server = "http://192.168.131.113:8080/";//俊杰

	
	var appId = "wx1f129f7b51701428";
	var urlName = "wlyy";
	var weixinUrl = "ehr.yihu.com";
	var agentName = "wlyyAgent";
	var agentName1 = "wlyyAgent1";
	var OpenidAgent = "OpenidAgent";
	var judgeAgent = "judgeAgent";
	var pageName = "pageurl";
	var wxurl = "http%3a%2f%2fehr.yihu.com%2fwlyy%2fwx%2fhtml";
	var wsurl = 'ws://172.19.103.76:3030/netex';
	var imgUrlDomain = "http://172.19.103.54/";//添加图片服务器路径；
	var imurl="http://172.19.103.88:3000";
	
	var articleUrl = "http://172.19.103.87:9088"//健康教育文章详情
	
//	var imurl="http://192.168.131.24:3000";//仕杰
	//var imurl="http://192.168.131.127:3000";//逸祥
	
	//测试环境（健康之路当阳）
	//var server = "http://weixin.xmtyw.cn/wlyy-dev/";
	//var appId = "wxd03f859efdf0873d";
	//var urlName = "wlyy-dev";
	//var weixinUrl = "weixin.xmtyw.cn";
	//var agentName = "wlyyAgent_test";
	//var agentName1 = "wlyyAgent_test1";
	//var OpenidAgent = "OpenidAgent_test";
	//var judgeAgent = "judgeAgent_test";
	//var pageName = "pageurl_test";
	//var wxurl = "http%3a%2f%2fweixin.xmtyw.cn%2fwlyy-dev%2fwx%2fhtml";
	//var wsurl = 'ws://172.19.103.76:3030/netex';
	//var imurl="http://172.19.103.29:3008";
}
////保存userAgent
//function wxSaveUserAgent(id, uid, openid, token) {
//  if(window.localStorage.getItem(agentName)){
//      window.localStorage.removeItem(agentName);
//  }
//  var userAgent = "{\"id\":" + id + ",\"uid\":\"" + uid + "\",\"openid\":\"" + openid + "\",\"token\":\"" + token + "\",\"platform\":3}";
//  window.localStorage.setItem(agentName, userAgent);
//  return userAgent;
//}

//添加openid白名单，只有这个名单内的openid才可以在线支付
var openidList = [];

//设置变量，控制是否可以在线支付
var canPayOnline = true;
if(GetRequest().openid){
    checkCanPayOnline(GetRequest().openid);
}

//添加处方功能的openid白名单
var prescriptionOpenidList = ['123456'];
var canPrescription = true;
if(GetRequest().openid){
    checkCanPrescription(GetRequest().openid);
}

//保存userAgent
function wxSaveUserAgent(id, uid, openid, token,lastUid) {
    if(window.localStorage.getItem(agentName)){
        window.localStorage.removeItem(agentName);
    }
    var userAgent = {
        id: id,
        uid: uid,
        openid: openid,
        token: token,
        lastUid: (lastUid ? lastUid:""),
        platform: 3
    }
    userAgent = JSON.stringify(userAgent);
//  var userAgent = "{\"id\":" + id + ",\"uid\":\"" + uid + "\",\"openid\":\"" + openid + "\",\"token\":\"" + token + "\",\"lastUid\":\"" + (lastUid ? lastUid:"") + "\",\"platform\":3}";
    window.localStorage.setItem(agentName, userAgent);
    return userAgent;
}

//保存userAgent1
function wxSaveUserAgent1(uid, name, photo) {
    if(window.localStorage.getItem(agentName1)){
        window.localStorage.removeItem(agentName1);
    }
    var userAgent = {
        uid: uid,
        name: name,
        photo: photo
    }
    userAgent = JSON.stringify(userAgent);
//  var userAgent = "{\"uid\":" + uid + ",\"name\":\"" + name + "\",\"photo\":\"" + photo + "\"}";
    window.localStorage.setItem(agentName1, userAgent);
    return userAgent;
}
//保存openid
function saveAgentOpenid(openid){
    if(window.localStorage.getItem(OpenidAgent)){
        window.localStorage.removeItem(OpenidAgent);
    }
    var agentOpenid = "{\"openid\":\"" + openid + "\"}";
    window.localStorage.setItem(OpenidAgent, agentOpenid);
}
//保存页面跳转值
function saveAgentJudge(judge){
    if(window.localStorage.getItem(judgeAgent)){
        window.localStorage.removeItem(judgeAgent);
    }
    var agentJudge = "{\"judge\":" + judge + "}";
    window.localStorage.setItem(judgeAgent, agentJudge);
}
//保存跳转页面到agent
function saveAgentPage(pageurl){
    if(window.localStorage.getItem(pageName)){
        window.localStorage.removeItem(pageName);
    }
    var agentPage = "{\"pageurl\":\"" + pageurl + "\"}";
    window.localStorage.setItem(pageName, agentPage);
    
    //如果页面中有code这个参数，及微信授权返回的code，将这个code保存在storage中
    if(pageurl.indexOf("code=") > -1){
        var arr = pageurl.split("code=");
        var code = arr[1].split("&")[0];
        window.localStorage.setItem("weixinCode", code);
    }
}
//清空所有的agent
function clearAgent(){
    if(window.localStorage.getItem(agentName)){
        window.localStorage.removeItem(agentName);
    }
    if(window.localStorage.getItem(agentName1)){
        window.localStorage.removeItem(agentName1);
    }   
    
    window.localStorage.removeItem("weixinCode"); //清楚缓存的code
//  if(window.localStorage.getItem(OpenidAgent)){
//      window.localStorage.removeItem(OpenidAgent);
//  }
}

//获取链接上的参数
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]);
      }
   }
   //添加toName的信息
   if(theRequest.toName){
       localStorage.setItem("toName", theRequest.toName);
   }
   return theRequest;
}
//新的判断用户是否登录的方法，先校验openid是否一致
function checkUserAgent(){
    var Request = new Object();
    Request = GetRequest(); 
    var code = Request["code"];
    var userAgent = window.localStorage.getItem(agentName);
    var agentCode = localStorage.getItem("weixinCode");
    if(code == "" || code == null || code == undefined){
        if(agentCode){
            //存在agentCode，说明一定获取openid成功过。
            if(!userAgent){
                var agentOpenids = window.localStorage.getItem(OpenidAgent);
                agentOpenids = JSON.parse(agentOpenids);
                window.location.href = "../../home/html/zhmm-login.html?type=" + pagetype + "&openid=" + agentOpenids.openid;
            }else{
                try{
                    var agentOpenids = window.localStorage.getItem(OpenidAgent);
                    if(agentOpenids){
                        agentOpenids = JSON.parse(agentOpenids);
                        checkCanPayOnline(agentOpenids.openid);
                        checkCanPrescription(agentOpenids.openid);
                    }
                    queryInit();
                }catch(e){
                    
                }
            }
        }else{
            if(!userAgent){
                d.close();
    //          dialog({contentType:'tipsbox', skin:'bk-popup' , content:'授权失败',bottom:true}).show();
                //模板消息的情况，模板消息带上openid的值给页面
                var openid = Request['openid'];
                saveAgentOpenid(openid);
                window.location.href = "../../home/html/zhmm-login.html?type=" + pagetype + "&openid=" + openid;
            }else{
                try{
                    checkCanPayOnline(Request['openid']);
                    checkCanPrescription(Request['openid']);
                    queryInit();
                }catch(e){
                    
                }
            }
        }
    }
    else{
        //校验code与缓存中的code是否一致，一致的话则不再向后端获取openid，因为code只能使用一次
        if(agentCode && (code == agentCode)){
            try{
                var agentOpenids = window.localStorage.getItem(OpenidAgent);
                if(agentOpenids){
                    agentOpenids = JSON.parse(agentOpenids);
                    checkCanPayOnline(agentOpenids.openid);
                    checkCanPrescription(agentOpenids.openid)
                }
                queryInit();
            }catch(e){
                
            }
        }else{
            //校验登录的openid是否与缓存中存在的一致
            d.show();
            sendPost('weixin/getOpenidByCode', {code: code}, 'json', 'post', openidFailed, function(res){
                if (res.status == 200) {
                    d.close();
                    localStorage.setItem("weixinCode", code);
                    var openid = res.openid,
                        agentOpenids = window.localStorage.getItem(OpenidAgent),
                        agentOpenid = agentOpenids && JSON.parse(agentOpenids).openid;
                    saveAgentOpenid(openid);
                    if( agentOpenid == openid){
                        if(!userAgent){
                            window.location.href = "../../home/html/zhmm-login.html?type=" + pagetype + "&openid=" + openid;
                        }else{
                            try{
                                checkCanPayOnline(openid);
                                checkCanPrescription(openid);
                                queryInit();
                            }catch(e){
                                
                            }
                        }
                    }else{
                        window.location.href = server + "wx/html/home/html/zhmm-login.html?type=" + pagetype + "&openid=" + openid;
                    }
                } else {
                    openidFailed(res);
                }
            });
        }
    }
}

//判断用户是否登录
function checkUserAgent1(){
    var userAgent = window.localStorage.getItem(agentName);
    if(!userAgent){  
        var agentOpenid = window.localStorage.getItem(OpenidAgent);
        if(!agentOpenid||agentOpenid=="undefined"){
            var Request = new Object();
            Request = GetRequest(); 
            var code = Request["code"];
            if(code == "" || code == null || code == undefined){
                d.close();
                dialog({contentType:'tipsbox', skin:'bk-popup' , content:'授权失败',bottom:true}).show();
            }
            else{
                d.show();
                var data = {};
                data.code = code;
                sendPost('weixin/getOpenidByCode', data, 'json', 'post', openidFailed, openidSuccess);
            }  
        }
        else{
            var jsonstr = $.parseJSON(agentOpenid);
            var openid = jsonstr.openid;
            if((pagetype>=20&&pagetype<=27) || pagetype=='-1' || pagetype==3 || !pagetype){
                pagetype = 0;
                window.localStorage.setItem(pageName, JSON.stringify({pageurl: location.href}))
            }
                
//          window.location.href = server + "wx/html/home/html/zhmm-login.html?type=" + pagetype + "&openid=" + openid;
            window.location.href = "../../home/html/zhmm-login.html?type=" + pagetype //+ "&openid=" + openid;
       }        
    }
    else{
        try{
            queryInit();
        }catch(e){
            
        }
    }
}
//判断openid是否在可以在线支付的白名单里面
function checkCanPayOnline(id){
    if(id && openidList.indexOf(id)>-1){
        canPayOnline = true;
    }
}
//判断openid是否在可以开启处方功能的白名单中
function checkCanPrescription(id){
    if(id && prescriptionOpenidList.indexOf(id)>-1){
        canPrescription = true;
    }
}

//成功
function openidSuccess(res) {
    if (res.status == 200) {
        var openid = res.openid;
        saveAgentOpenid(openid);
        window.location.href = server + "wx/html/home/html/zhmm-login.html?type=" + pagetype + "&openid=" + openid;     
    } else {
        openidFailed(res);
    }
}

//失败
function openidFailed(res) {
    d.close();
//  if(window.localStorage.getItem(OpenidAgent)){
//      window.localStorage.removeItem(OpenidAgent);
//  }
    if (res && res.msg) {
        dialog({contentType:'tipsbox', skin:'bk-popup' , content:res.msg,bottom:true}).show();      
    } else {
        dialog({contentType:'tipsbox', skin:'bk-popup' , content:'获取认证信息失败',bottom:true}).show(); 
    }
}

//判断用户是否有签约
function checkSign(type){   
    d.show();
    var userAgent = window.localStorage.getItem(agentName);
    if(userAgent){
        var data = {};
        $.ajax(server + "patient/is_sign", {
            data: data,
            type: 'POST',
            dataType: 'json',
            beforeSend: function(request) {
                request.setRequestHeader("userAgent", userAgent);
            },
            error: function(res) {
                d.close();
                if(res.status == 999 || res.status == 998 || res.status == 997){
                    loginUrl(res.status);
                    return;
                }
                dialog({contentType:'tipsbox', skin:'bk-popup' , content:'校验失败',bottom:true}).show();
            },
            success: function(res) {
                d.close();
                if(res.status == 999 || res.status == 998 || res.status == 997){
                    loginUrl(res.status);
                }
                else if (res.status == 200) {                   
                    var is_sign = res.data;//0未签约，1已签约
                    if(is_sign == 0){                       
                        dialog({
                            title: '提示',
                            content: '您还未签约,请先签约,谢谢！',
                            okValue:'签约',
                            ok: function (){                                    
                                window.location.href = server + "wx/html/ssgg/html/choose-region.html";
                            },
                            cancelValue: '不了',
                            cancel: function () {
                                return;
                            }
                        }).showModal();
                    }else{
                        if(type == 1){
                            window.location.href = server + "wx/html/zxwz/html/teachers-consult-commit.html";
                        }
                    }
                } else {
                    dialog({contentType:'tipsbox', skin:'bk-popup' , content:res.msg,bottom:true}).show();
                }
            }
        }); 
    }
    else{
        dialog({contentType:'tipsbox', skin:'bk-popup' , content:'用户信息错误',bottom:true}).show();
    }
}


var toUsers  =  localStorage.getItem("toUser");
var curId  =  localStorage.getItem("id");
var toName = localStorage.getItem("toName");
var consultCode = localStorage.getItem("consultCode");

var pageUrl  = {
/**通用跳转**/        0:function(){
                        var pageurl = "";
                        var agentPage = window.localStorage.getItem(pageName);
                        if(agentPage){
                            var jsonstr = $.parseJSON(agentPage);
                            pageurl = jsonstr.pageurl;
                        }
                        return pageurl;
                     }(),
/**签约管理首页**/  "-1":"../../qygl/html/signing-doctors.html",//签约管理首页
/**医生咨询首页**/     1:"../../yszx/html/doctor-consultation.html",
/**医生指导首页**/     3:"../../yszd/html/doctor-guidance.html",//医生指导首页
/**疾病社区首页**/     4:"../../jbsq/html/disease-community.html",//疾病社区首页
/**健康记录首页**/     5:"../../jkjl/html/health-record.html",//健康记录
/**我的设备首页**/     6:"../../wdsb/html/my-equipments.html",//我的设备
/**我的资料首页**/    11:"../../grzx/html/my-detail.html",
/**我的设备首页**/    15:"../../wdsb/html/my-equipments.html",
/**签约选择医生**/    16:"../../qygl/html/select-doctor.html",
/**签约搜索医生**/    17:"../../qygl/html/search-doctor.html",
/**签约医生主页**/    18:function(){
                            var doctor  =  localStorage.getItem("doccode");
                            return "../../ssgg/html/doctor-homepage-new.html?openid="+0+"&state="+doctor;
                      }(),
/**我的预约首页**/    20:"../../wdyy/html/my-appointment.html",
/**预约挂号提交**/    21:"https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appId+"&redirect_uri="+wxurl+"%2fwdyy%2fhtml%2finfo-confirm.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect",      
                     22:"../../jtgx/html/family.html",
/**预约详情首页**/    23:"../../wdyy/html/detail-appointment.html?openid="+0+"&toUser="+toUsers+"&id="+curId+"&toName="+toName,
/**医生咨询详情**/    24:"../../yszx/html/consulting-doctor.html?openid="+0+"&toUser="+toUsers+"&consult="+consultCode+"&toName="+toName,
/**医生指导详情**/    25:"../../yszd/html/guidance-detail.html?openid="+0+"&toUser="+toUsers+"&id="+curId+"&toName="+toName,
/**健康教育**/        26:"../../jkjy/html/article_list.html",      
/**健康详情**/        27:function(){
	                        var artoUser  =  localStorage.getItem("toUser");
	                        var article  =  localStorage.getItem("article");
	                        return "../../jkjy/html/article.html?dataId="+article+"&toUser="+artoUser+"&toName="+toName;
	                    }(),
 /**新的健康详情**/    50:function(){
                        var artoUser  =  localStorage.getItem("toUser");
                        var article  =  localStorage.getItem("article");
                        return "../../jkjy/html/article2.html?dataId="+article+"&toUser="+artoUser+"&toName="+toName;
                    }(),
                      28:"../../jkda/html/jiuzhenjilu.html",
                      29:"../../jkda/html/jianchajianyan.html",
                      30:"../../survey/html/survey_info.html?openid="+0+"&toUser="+toUsers+"&toName="+toName+"&survey_id="+localStorage.getItem("survey_id"),
/**签约管理首页2**/    31:"../../qygl/html/signing_management.html",//签约管理首页
/*社区体检*/           32: "../../jkda/html/jiankangtijian.html",
/*续签页面*/           33: "../../xuqian/html/information.html",
/**意见反馈**/         34:"../../yjfk/html/feedback.html",
/**公共咨询**/        36:"../../jbsq/html/public-consult-detail.html",
/*处方记录 */         38: "../../prescription/html/prescription_records.html",
/*续方订单跟踪页*/     41: '../../prescription/html/order_tracking.html?openid='+0+'&toUser='+toUsers+'&toName='+toName+'&code='+window.localStorage.getItem("prescriptionCode"),
///*续方记录页*/         42: '../../prescription/html/re-prescription_info.html?openid='+0+'&toUser='+toUsers+'&toName='+toName+'&code='+window.localStorage.getItem("prescriptionCode"),
	 /*孕检计划*/      45: "../../fybj/html/yunjianjihua.html",
	 /*免疫计划*/      46: "../../fybj/html/mianyijihua.html",
	/*慢病管理修改*/	   47: "../../jbsq/html/slow-disease-manage.html",
	/**免疫预约首页**/    48:"../../wdyy/html/immune-appointment.html",
	/**免疫预约详情页**/    49:"../../wdyy/html/detail-immune-appointment.html"
}

Date.prototype.Format = function(formatStr)   
{   
    var str = formatStr;   
    var Week = ['日','一','二','三','四','五','六'];  
  
    str=str.replace(/yyyy|YYYY/,this.getFullYear());   
    str=str.replace(/yy|YY/,(this.getYear() % 100)>9?(this.getYear() % 100).toString():'0' + (this.getYear() % 100));   
  
    str=str.replace(/MM/,this.getMonth()>8?(this.getMonth()+1).toString():'0' + (this.getMonth()+1)); 
    str=str.replace(/M/g,this.getMonth()+1);
  
    str=str.replace(/w|W/g,Week[this.getDay()]);   
  
    str=str.replace(/dd|DD/,this.getDate()>9?this.getDate().toString():'0' + this.getDate());   
    str=str.replace(/d|D/g,this.getDate());   
  
    str=str.replace(/hh|HH/,this.getHours()>9?this.getHours().toString():'0' + this.getHours());   
    str=str.replace(/h|H/g,this.getHours());   
    str=str.replace(/mm/,this.getMinutes()>9?this.getMinutes().toString():'0' + this.getMinutes());   
    str=str.replace(/m/g,this.getMinutes());   
  
    str=str.replace(/ss|SS/,this.getSeconds()>9?this.getSeconds().toString():'0' + this.getSeconds());   
    str=str.replace(/s|S/g,this.getSeconds());   
  
    return str;   
} 

var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");
//document.write(unescape("%3Cspan style='display:none' id='cnzz_stat_icon_1265315380'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s22.cnzz.com/z_stat.php%3Fid%3D1265315380' type='text/javascript'%3E%3C/script%3E"));