var d = dialog({contentType:'load', skin:'bk-popup'});
var d1 = dialog({contentType:'load', skin:'bk-popup',content:'退出中..'});
var pagetype = 11;
var openid =null;
var userAgent = window.localStorage.getItem(agentName);
var firstUid = window.localStorage.getItem("firstUid");
if(firstUid == null || firstUid == undefined){
	document.getElementById("divChangeLogin").style.display='none';
}

var bindCardUrl = "",
    bindCardStatus;

if(userAgent){
	var jsonstr = $.parseJSON(userAgent);
	openid = jsonstr.openid;
}
$(function() {	
	checkUserAgent();
});	

appendFamilyMember($('#memberContainer'),function(){
	queryInit();
	clearCommittee()
	var jsonstr = $.parseJSON(window.localStorage.getItem(agentName));
	if(jsonstr.uid == jsonstr.represented){
		$('#divChangeLogin').show()
		//判断是否可以在线支付
        if(canPayOnline){
            $("#elecard").show();
        }else{
            $("#elecard").hide();
        }
	}else{
		$('#divChangeLogin').hide()
		$("#elecard").hide();
	}
},function(){
	//判断有授权家人，修改样式
	if($('#memberContainer').is(':hidden')){
		$('#content').css('padding-top','0px');
	}else{
		$('#content').css('padding-top','90px');
	}
});

function queryInit(){
	d.show();
	
	isRepresent(function() {
		//查询用户信息
		query();
		
	    getWeixinSign();
	    bindEvents();
	    //选择居委会
	    selectCommittee()
	})
    
}
//获得微信sdk信息
function getWeixinSign(){
    var params1 = {};
    params1.pageUrl = server + "wx/html/grzx/html/my-detail.html&state=STATE";
    
    $.ajax(server + "weixin/getSign", {
        data: params1,
        dataType: "json",
        type: "post",
        success: function(res){
            if (res.status == 200) {
                var t = res.data.timestamp;
                var noncestr = res.data.noncestr;
                var signature = res.data.signature;
                wx.config({     
                    //debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId: appId, // 必填，公众号的唯一标识
                    timestamp: t, // 必填，生成签名的时间戳
                    nonceStr: noncestr, // 必填，生成签名的随机串
                    signature: signature,// 必填，签名，见附录1
                    jsApiList: [
                        'chooseImage',
                        'uploadImage'
                    ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                });
            } 
        }
    }); 
}

//跳转到三师信息
function changeSanshi(){
	window.location.href = "../../qygl/html/signing-doctors.html";
}
//跳转到家庭签约信息
function changeJtqy(signedStatus){
	if(signedStatus) {
		window.location.href = "../../ssgg/html/doctor-homepage-new.html"
	} else {
		window.location.href = "../../qygl/html/signing-doctors.html"
	}
}

//查询列表
function query() {
//	var data={};
//	sendPost('patient/baseinfo', data, 'json', 'post', queryFailed, querySuccess);
    //初始查询患者基本信息，然后调用接口判断该患者是否已绑定电子社保卡
    var reqParams = [{
        url: "patient/baseinfo",
        data: {},
        reqType: 'post'
    },{
        url: "/patient/bindCard",
        data: {},
        reqType: 'post'
    }]
    getReqPromises(reqParams).then(function(ress){
        querySuccess(ress[0]);
        //处理绑卡
        var res2 = ress[1];
        if(res2.data.bindStatus == '030007'){
            bindCardStatus = false;
            bindCardUrl = res2.data.sicardUrl;
        }else if(res2.data.bindStatus == '000000'){
            bindCardStatus = true;
            bindCardUrl = res2.data.sicardUrl;
        }else{
            dialog({contentType:'tipsbox', skin:'bk-popup' , content:res2.msg}).show();
        }
        //判断是否可以在线支付
        if(canPayOnline){
            $("#elecard").show();
            $("#elecardStatus").text(bindCardStatus? "已绑定" : "未绑定");
        }else{
            $("#elecard").hide();
        }
    });
}

function queryFailed(res) {
	d.close();
	if (res && res.msg) {
		dialog({contentType:'tipsbox',bottom:true, skin:'bk-popup' , content:res.msg}).show();      
	} else {
		dialog({contentType:'tipsbox',bottom:true, skin:'bk-popup' , content:'初始化失败'}).show(); 
	}
}

function querySuccess(res) {
	d.close();
	if (res.status == 200) {
		setValue(res.data);	
		if($("#ssc").val() != ""){
			$("#ssc").attr("readonly","readonly");
		}
		//取药码
		if(res.data.prescription == 1){
			$('#myMedicine').show()
		}else{
			$('#myMedicine').hide()
		}
	}
}

function  bindEvents(){
    $("#backLogin").click(function (){
        dialog({
            content:'您确定继续退出登录吗?',
            ok: function (){
                d1.show()
                sendPost("patient/wxloginout",{},"JSON","POST",function(res){
                    d1.close()
                    if (res && res.msg) {
                        dialog({contentType:'tipsbox',bottom:true, skin:'bk-popup' , content:res.msg}).show();      
                    } else {
                        dialog({contentType:'tipsbox',bottom:true, skin:'bk-popup' , content:'退出登录失败！'}).show(); 
                    }
                },function(res){
                    d1.close()
                    if(res.status==200){
                        clearAgent();
                        window.localStorage.removeItem("isTiXingVideoFaSong");//清除咨询详情移动网络下，用户点击不再提醒后的处理，换账号登陆后，还可以重新提醒
                        location.replace("../../home/html/zhmm-login.html?type=11&openid="+openid);
                    }else{
                        if (res && res.msg) {
                            dialog({contentType:'tipsbox',bottom:true, skin:'bk-popup' , content:res.msg}).show();      
                        } else {
                            dialog({contentType:'tipsbox',bottom:true, skin:'bk-popup' , content:'退出登录失败！'}).show(); 
                        }   
                    }
                })
            
            },
            cancel: function () {
                return;
            }
        }).showModal();
    });
    
    //绑定电子社保卡
    $('#elecard').on('tap',function(){
        if(!bindCardStatus){
            dialog({
                content: '当前未绑定电子社保卡，无法进行线上缴费，是否立即绑定',
                cancelValue: '不了，谢谢',
                cancel: function () {},
                okValue:'是',
                ok: function (){
                    window.location.href = bindCardUrl;
                }
            }).showModal();
        }else {
            window.location.href = bindCardUrl;
        }
    });
    
    //电子健康卡点击事件
    $("#healthcard").on('tap', function(){
    	window.location.href = "my-health-card.html"
//      d.show();
//      var url = "/patient/ehc/redirecturl";
//      sendPost(url, {}, 'json', 'post', queryFailed, function(res){
//          if(res.status == 200){
//              d.close();
//              window.location.href = res.data;
//          }else{
//              queryFailed(res);
//          }
//      })
    })
}
//初始化页面数据
function setValue(data){
	var photo = data.photo;
	var name = data.name;
	var sex = data.sex;
	var mobile = data.mobile;
	var idcard = data.idcard;
	var ssc = data.ssc;
	var address = data.address;
	var medicareNumber = data.medicareNumber || "";
	var sign = Number(data.sign);
	
	var sexName = "女";
	if(sex == 1) {
		sexName = "男";
	}
	if(!photo){
		photo = "../../../images/p-default.png";
	}	
	if(!name) name = "";
	if(!mobile) mobile = "";
	if(!idcard) idcard = "";
	if(!ssc) ssc = "";
	if(!address) address = "";
	
	document.getElementById("photo").src = getImgUrl(photo);
	document.getElementById("name").value = name;			
	document.getElementById("sex").innerHTML = sexName;
	document.getElementById("mobile").innerHTML = mobile;
	document.getElementById("idcard").innerHTML = idcard;
	document.getElementById("medicareNumber").innerHTML = medicareNumber;
	document.getElementById("ssc").value = ssc;
	document.getElementById("address").innerHTML = address;
	$('#committee').text(data.countryName);
}

// 添加文件
function appendFile(p) {
	document.getElementById("photo").src = p;
	$("#photo").attr("data-src",p);
}
//获取需要上传的图片
function getImages() {
	var images = [];
	var imgSrc = $("#photo").attr("data-src");
	images.push(imgSrc);
	return images;
}
//剪切图片
function clip_photo(){
    $("#content").addClass("c-hide");
    $("#clipPanel").removeClass("c-hide");
    var photo = document.getElementById('file_head');
    lrz(photo.files[0]).then(function (rst) {
        var url = rst.base64;
        new AlloyCrop({
            image_src: url,
            width: document.documentElement.clientWidth,
            height: document.documentElement.clientWidth,
            ok_text: "保存",
            cancel_text: "取消",
            ok: function (base64, canvas) {
                $("#content").removeClass("c-hide");
                var data=base64.split(',')[1];
                data=window.atob(data);
                var ia = new Uint8Array(data.length);
                for (var i = 0; i < data.length; i++) {
                    ia[i] = data.charCodeAt(i);
                }
                var blob=new Blob([ia],{type:"image/png",endings:'transparent'});
                var fd=new FormData();
                fd.append('file',blob,'image.png');
                
                var new_url = URL.createObjectURL(blob);
                appendFile(new_url);
                $.ajax(server + 'upload/image', {
                    data: fd,
                    dataType: 'json',
                    contentType: false,
                    cache: false,
                    processData: false,
                    beforeSend: function(request) {
                        request.setRequestHeader("userAgent", userAgent);
                    },
                    type: 'post',
                    error: function(res) {
                        if(res.status == 999 || res.status == 998 || res.status == 997){
                            loginUrl(res.status);
                            return;
                        }
                        clickCount = 0;
                    },
                    success: function(res) {
                        if(res.status == 999 || res.status == 998 || res.status == 997){
                            loginUrl(res.status);
                            return;
                        }
                        var params = {};
                        params.photo = res.urls;
                        var patientUrl = res.urls;
                        sendPost('patient/save', params, 'json', 'post', submitFailed, submitSuccess);
                        clickCount = 0;
                    }
                });
            },
            cancel: function () {
                $("#content").removeClass("c-hide");
            }
        });
    })
    .catch(function (err){
        // 处理失败会执行
        console.log(err);
    });
    
}
// 上传头像
var serverId = "";
function chooseImage(){
	wx.chooseImage({
	  count: 1, 
      success: function (res) {
      	appendFile(res.localIds[0]);
        uploadImage();
      }
    });
}	
//获取微信上传图片的媒体ID
function uploadImage(){
	var images = getImages();
	if (images.length == 0) {
      return;
    }
    var i = 0, length = images.length;
    serverId = "";
    function upload() {
      wx.uploadImage({
        localId: images[i],
        success: function (res) {
          i++;
          if(serverId.length == 0){
          	serverId = res.serverId;
          }
          else{
          	serverId =serverId + "," + res.serverId;
          }          
          if (i < length) {
            upload();
          }
          if(i == images.length){
          	update_photo();
          }          
        },
        fail: function (res) {
          alert(JSON.stringify(res));
        }
      });
    }
    upload();
}	
//上传图片到服务器上
function update_photo(){
	var params = {};
	params.mediaIds = serverId;	
	sendPost('patient/save', params, 'json', 'post', submitFailed, submitSuccess);
}
//上传失败
function submitFailed(res) {
	if (res && res.msg) {
		dialog({contentType:'tipsbox',bottom:true, skin:'bk-popup' , content:res.msg}).show();      
	} else {
		dialog({contentType:'tipsbox',bottom:true, skin:'bk-popup' , content:'上传失败'}).show(); 
	}
}
//上传成功
function submitSuccess(res) {
	if (res.status == 200) {
	    $("#content").removeClass("c-hide");
	    $("#clipPanel").addClass("c-hide");
	} else {
		submitFailed(res);
	}
}	
//查看图片
function viewImg(dom) {
	var $img = $(dom);
	var thissrc = $img.attr("data-src");
	var mWid = $(window).width();
	var mHei = $(window).height();
	var nHtml = '<div class="delimgpop"><div class="del-img-box"><div class="del-img-con"><img class="del-pop-img" src="' + thissrc + '" style="max-width:' + mWid + 'px; max-height:' + mHei + 'px;"></div></div></div>';
	$("body").append(nHtml);
	$(".delimgpop").click(function() {
		$(this).remove()
	});
};

function myMedicine(){
	window.location.href = "../../prescription/html/my-medicine-code.html";
}

function myFeedback(){
	window.location.href = "../../yjfk/html/feedback.html";
}

function updatePwd(){
	var mobile = $('#mobile').html();
	window.location.href = "shezhimima.html?type=" + pagetype + "&openid=" + openid + "&mobile="+ mobile + "&1=1";
}

function updateAddress(){
	var address = $('#address').html();
	var paramAgent = "{\"type\":" + pagetype + ",\"openid\":\"" + openid + "\",\"address\":\"" + encodeURI(address) + "\"}";
	window.localStorage.setItem("paramAgent", paramAgent);
	window.location.href = "xiugaidizhi.html?type=" + pagetype + "&openid=" + openid + "&mobile="+ mobile + "&1=1";
}

function updateMobile(){
	var mobile = $.trim($('#mobile').html());
	if(mobile.length==0)
		window.location.href = "bangdingsj.html?type=" + pagetype + "&openid=" + openid + "&1=1";
	else
		window.location.href = "shenfenyz.html?type=" + pagetype + "&openid=" + openid + "&mobile="+ mobile + "&1=1";
}
