var patientCode = "",
	self = null,
	tagType = '';//tab标签初始
var $tizhengList = $('#tizhengList'),
	$baojianList = $('#baojianList');
var xuetangRecord = null,
	xuyaRecord = null,
	tizhongRecord = null,
	yaoweiRecord = null,
	yundongRecord = null,
	yongyaoRecord = null,
	yinshiRecord = null,
	tzSta = false,
	xtdt = '',
	xydt = '',
	tzdt = '',
	ywdt = '',
	yddt = '',
	yydt = '',
	ysdt = '';
var xuetangDuring = ['','早餐前', '早餐后', '午餐前', '午餐后', '晚餐前', '晚餐后', '睡前'];
mui.plusReady(function() {
	self = plus.webview.currentWebview();
	tagType = self.tagType?self.tagType:0;
	patientCode = self.patientCode;
	bindEvents();
	if(tagType == 1){
		$('.j-tab-select li').eq(1).addClass('hit');
		$('.pt-tab-list').eq(1).addClass('hit');
		$('.icon-share').hide();
		$('.header-group').hide();
	}else{
		$('.j-tab-select li').eq(0).addClass('hit');
		$('.pt-tab-list').eq(0).addClass('hit');
	}
	//体征记录
	getRecentDataPromise().then(function(res) {
		xuetangRecord = _.find(res.data,function(o){
			var d = new Date(o.recordDate.replace(/\-/g, "/"));
			o.recordDate = d.getFullYear() + '-' + checkDate(d.getMonth() + 1) + '-' + checkDate(d.getDate());
			return o.type =="1";
		}) || {};
		xuyaRecord = _.find(res.data,function(o) {
			return o.type =="2";
		}) || {};
		tizhongRecord = _.find(res.data,function(o) {
			return o.type =="3";
		}) || {};
		yaoweiRecord = _.find(res.data,function(o) {
			return o.type =="4";
		}) || {};
		var xuetangValue = "";
		var xuetangValueIndex;
		var during = _.find(xuetangDuring,function(v,i){
			xuetangValue = xuetangRecord['value'+[i]];
			xuetangValueIndex = i;
			return i>0&&xuetangValue;
		});
		
		xtdt = xuetangRecord.recordDate || '';
		xydt = xuyaRecord.recordDate || '';
		tzdt = tizhongRecord.recordDate || '';
		ywdt = yaoweiRecord.recordDate || '';
		var duringIndex = xuetangRecord.value2 ? xuetangRecord.value2 : 0;
		return {
		    //血糖中,value1返回最新的值,value2表示当前值对应的时间段的值(1-7)
			xuetang: $.extend({},xuetangRecord,{
				during: duringIndex ? xuetangDuring[duringIndex] : '',
				value: xuetangValue,
				levelClazz: (function() {
					// 不同时间段对应不同的血糖范围
//					var levels = [[],[7.0, 3.9],[11.1, 4.0],
//								[7.0, 3.9],[11.1, 4.4],
//								[7.0, 3.9],[11.1, 4.4],
//								[7.0, 3.9]][xuetangValueIndex];
                    var levels = [[],[7.0, 3.9],[11.1, 4.0],
                                [7.0, 3.9],[11.1, 4.0],
                                [7.0, 3.9],[11.1, 4.0],
                                [7.0, 3.9]][duringIndex]
					return getLevelClazz(xuetangValue, levels[0],levels[1])
				})(),
				recordType: getRecordType(xuetangRecord.deviceSn)
			}),
			xueya: $.extend({},xuyaRecord,{
				levelClazz: getLevelClazz(xuyaRecord.value1, 139, 90)||getLevelClazz(xuyaRecord.value2, 89, 60),
				recordType: getRecordType(xuyaRecord.deviceSn)
			}),
			tizhong: $.extend({},tizhongRecord,{
				recordType: getRecordType(tizhongRecord.deviceSn)
			}),
			yaowei:  $.extend({},yaoweiRecord,{
				recordType: getRecordType(yaoweiRecord.deviceSn)
			})
		}
	}).then(function(data) {
		var html = template('tizheng_list_temp',data);
		$tizhengList.html(html)
	}).then(function() {
		//保健记录
		getBJRecentDataPromise().then(function (res){
			yundongRecord = res.data.sprot;
			yongyaoRecord = res.data.medication;
			yinshiRecord = res.data.diet;
			
			yddt = yundongRecord.recordDate;
			yydt = yongyaoRecord.recordDate;
			ysdt = yinshiRecord.recordDate;
			return {
				yundong: (function () {
					yundongRecord.recordType = getBJRecordType(yundongRecord.source);
					return yundongRecord;
				})(),
				yongyao: (function () {
					yongyaoRecord.recordType = getBJRecordType(yongyaoRecord.source);
					return yongyaoRecord;
				})() ,
				yinshi: (function () {
					yinshiRecord.recordType = getBJRecordType(yinshiRecord.source);
					return yinshiRecord;
				})()
			};
		}).then(function (data) {
			var html = template('baojian_list_tmp',data);
			$baojianList.html(html);
		}).then(function(){
			getEquipments()
		})
	})
	.catch(function(e) {
		console && console.error(e)
	})	
})
function getEquipments(){
	var params = {
		page:1,
		pagesize:100,
		patient:patientCode
	}
	sendGet("doctor/device/PatientDeviceList",params,function(){
		mui.toast('请求失败')
	},function(res){
		if(res.status==200){
			if(res.data&&res.data.length>0){
				$("#equip-list").empty();
				$(".div-no-info").hide();
				for(var i in res.data){
					showList(res.data[i]);
				}
				$("#equip-list").show();
			}else{
				sendGet("doctor/is_patient_signed",{patient:patientCode},function(res){
					mui.toast("请求失败");
				},function(res){
					if(res.status==200){
						if(res.data==1){
							$(".div-tishi-info").html("该居民还未绑定体征设备");	
						}else{
							$(".div-tishi-info").html("您还未帮该居民绑定过体征设备");
						}
						$(".div-no-info").show();
						$("#equip-list").hide();
					}else{
						mui.toast("签约关系获取失败");
					}
				})		
			}
		}else{
			mui.toast("加载设备列表失败")
		}
	})
}
function showList(rowData){
	var img='xuetangyi_icon.png';
	if(rowData.categoryCode==2){
		img='xueyaji_icon.png';
	}
	var bindUser ="患者绑定";
	if(!!rowData.doctor){
		bindUser = rowData.doctorName;
	}
	var	showDomLi = '
'+
						''+
							'

'+
						'
 '+
						''+rowData.deviceName+'
'+
						'• 绑定时间:'+rowData.czrq+'
'+
						'• 绑定人:'+bindUser+'
'+
					'';
	$("#equip-list").append(showDomLi);
}
function getBJRecordType(isDevice) {
	return isDevice === 0 ? "手动记录" : isDevice == 1 ? "设备上传" : '';
}
function checkDate (v) {
	return (v < 10 ? '0' + v : v);
}
//获取最新的体征记录
function getRecentDataPromise() {
	return new Promise(function(resolve, reject) {
		sendGet("doctor/health_index/last", {patient:patientCode}, function (res) {
				resolve(res)
		}, function(res){
			if(res.status == 200) {
				resolve(res)
			} else {
				mui.toast('数据查询失败')
			}
		})
	})
}
//获取最新保健记录
function getBJRecentDataPromise () {
	return new Promise(function( resolve, reject){
		sendGet("doctor/health_record/recent", {patient:patientCode}, function (res) {
				resolve(res)
		}, function(res){
			if(res.status == 200) {
				resolve(res)
			} else {
				mui.toast('数据查询失败')
			}
		})
	})
}
function getLevelClazz(value,max,min) {
	if(!value||(!max && !min)) {
		return '';
	}
	
	var value = parseFloat(value);
	if(value < min) {
		return 'low';
	} else if(value > max) {
		return 'high';
	} else {
		return ''
	}
}
function bindEvents() {
	$("#tzyj_btn").on("click", function() {
		mui.openWindow('../../huanzhe/html/tzyj.html', 'tzyj', {
			extras: {
				code: patientCode
			}
		})
	})
	//标签切换
	$(".pt-tab li").click(function() {
		var id = $(this).attr("id");
		$(".pt-tab li").removeClass("hit");
		$(this).addClass("hit");
		if(id == "tizhengLi") {
			$("#tizhengList").show();
			$("#baojianList").hide();
			$("#equipment").hide();
			$('.icon-share').show();
			$('.header-group').show();
		}else if(id == "healthLi"){
			$("#tizhengList").hide();
			$("#baojianList").show();
			$("#equipment").hide();
			$('.icon-share').show();
			$('.header-group').show();
		}else if(id == "equipLi"){
			$("#tizhengList").hide();
			$("#baojianList").hide();
			$("#equipment").show();
			$('.icon-share').hide();
			$('.header-group').hide();
		}
	})
	$(".icon-share").on("click", function() {
		var msg = {
			"title": "健康记录",
			"id": patientCode,
			"type": 1,
			"content": "这是" + self.patientName + "的历史体征指标及保健记录,请点击查看"
		}
		mui.openWindow({
			url: "../../message/html/zhuanfa.html",
			id: "zhuanfa.html",
			extras: {
				imMessages: [{
					content: JSON.stringify(msg),
					type: 4
				}]
			}
		})
	})
	
	$('#tizhengList').on('click','li',function() {
		var index = $(this).index();
		var dat = new Date(),
			nowD = dat.getFullYear() + '-' + (dat.getMonth() + 1) + '-' + dat.getDate();
		if(index == 0) {
			mui.openWindow('../html/xuetang-view.html', 'xuetang-view.html', {
				extras: {
					code: patientCode,
					dateT: (xtdt || nowD)
				}
			});
		}
		if(index == 1) {
			mui.openWindow('../html/xueya-view.html', 'xueya-view.html', {
				extras: {
					code: patientCode,
					dateT: (xydt || nowD)
				}
			});
		}
		if(index == 3) {
			mui.openWindow('../html/tizhong-view.html', 'tizhong-view.html', {
				extras: {
					code: patientCode,
					dateT: (tzdt || nowD)
				}
			});
		}
		if(index == 2) {
			mui.openWindow('../html/yaowei-view.html', 'yaowei-view.html', {
				extras: {
					code: patientCode,
					dateT: (ywdt || nowD)
				}
			});
		}
	})
	$('#baojianList').on('click','li',function() {
		var index = $(this).index();
		var dat = new Date(),
			nowD = dat.getFullYear() + '-' + (dat.getMonth() + 1) + '-' + dat.getDate();
		if(index == 0) {
			mui.openWindow('../html/yundong-view.html', 'yundong-view.html', {
				extras: {
					code: patientCode,
					dateT: (yddt || nowD)
				}
			});
		}
		if(index == 1) {
			mui.openWindow('../html/yongyao-view.html', 'yongyao-view.html', {
				extras: {
					code: patientCode,
					dateT: (yydt || nowD)
				}
			});
		}
		if(index == 2) {
			mui.openWindow('../html/yinshi-view.html', 'yinshi-view.html', {
				extras: {
					code: patientCode,
					dateT: (ysdt || nowD)
				}
			});
		}
	})
	//**************体征设备
	//新增按钮事件
	$(".div-add-btn").on("click",function(){
		$(this).hide();
		if($(this).hasClass("active")){
			$(".modal-overlay").trigger("click");
		}else{
			$(this).addClass("active");
			$(".modal-overlay").addClass("modal-overlay-visible");
			$(".div-dialog-content").show();
		}
	})
	
	//点击遮罩事件
	$(".modal-overlay").on("click",function(){
		$(".modal-overlay").removeClass("modal-overlay-visible");
		$(".div-dialog-content").hide();
		$(".div-add-btn").removeClass("active");
		$(".div-add-btn").show();
   })
   
   //取消事件
   	$(".quxiao").on("click",function(){
   		$(".modal-overlay").trigger("click");
   	 })
   
   //点击血糖仪事件
   $(".xuetangyi-icon").on("click",function(){
   		$(".quxiao").click();
   		mui.openWindow('../../wdsb/html/list-xuetangyi.html', 'list-xuetangyi.html', {
			extras: {
				category_code: 1,
				patient:patientCode
			}
		})
   	})
   	
   	 //点击血压计事件
   $(".xueyaji-icon").on("click",function(){
   		$(".quxiao").click();
   		mui.openWindow('../../wdsb/html/list-xueyaji.html', 'list-xueyaji.html', {
			extras: {
				category_code: 2,
				patient:patientCode
			}
		})	
   })
   //绑定编辑和删除事件
	$("#equip-list").on("click","li",function(){
		var code = $(this).attr("data-id");
		var deviceId = $(this).attr("device-id");
		var type = $(this).attr("data-type");
		var role = $(this).attr("data-role");
		if(type==1){
			mui.openWindow('../../wdsb/html/view-xuetangyi.html', 'view-xuetangyi.html', {
				extras: {
					deviceId: deviceId,
					dataId:code,
					patient:patientCode,
					role:role
				}
			})	
		}else if(type==2){
			mui.openWindow('../../wdsb/html/view-xueyaji.html', 'view-xueyaji.html', {
				extras: {
					deviceId: deviceId,
					dataId:code,
					patient:patientCode,
					role:role
				}
			})
		}
	})
	
}
function getRecordType(isDevice) {
	return isDevice === null ? "手动记录" :  isDevice != null ? "设备上传" : '';
}
var html = template('tizheng_list_temp',{
	xuetang:{},
	xueya:{},
	tizhong:{},
	yaowei:{}
});
$tizhengList.html(html);
//页面局部刷新
window.addEventListener("refreshEquipment", function(){
	getEquipments()
})