(function($) {
	function Page(option) {
		this.init();
	}
	function getWechatInfo(){
	    //从后台那边获取签名等信息
	    var params = {};
	    var url1 = window.location.href;
	    params.pageUrl = url1;
	    $.ajax("/wlyy/weixin/getSign", {
	        data: params,
	        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({
	                    appId: appId, // 必填，公众号的唯一标识
	                    timestamp: t, // 必填，生成签名的时间戳
	                    nonceStr: noncestr, // 必填，生成签名的随机串
	                    signature: signature,// 必填，签名，见附录1
	                    jsApiList: [
	                        'chooseImage',
	                        'uploadImage',
	                        'startRecord',
	                        'stopRecord',
	                        'onVoiceRecordEnd',
	                        'playVoice',
	                        'pauseVoice',
	                        'stopVoice',
	                        'onVoicePlayEnd',
	                        'uploadVoice',
	                        'getNetworkType'
	                    ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
	                });
	
	                // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
	                wx.ready(function(){
	                    wx.getNetworkType({
	                        success: function (res) {
	                            networkStatus = res.networkType; // 返回网络类型2g，3g，4g，wifi
	                        }
	                    });
	                });
	            }
	        }
	    });
	}
		
	Page.prototype = {
		//初始化
		init: function() {
			this.initEvent();
			this.getReport();
			getWechatInfo();
		},
		//事件相关处理
		initEvent: function() {
			var self = this;
			$('#textContent').on('click','img',function() {
				var src= $(this).attr('src');
	            var imglist = $('textContent img');
	            var srcs= _.map(imglist,function(img){
	            	return $(img).attr('src')
	            })
	            wx.ready(function(){
	                wx.previewImage({
	                    current: src, // 当前显示图片的http链接
	                    urls: srcs // 需要预览的图片http链接列表
	                });
	            });
      
			})
		},

		//获取报告
		getReport: function() {
			var code = JSON.parse(localStorage.getItem(agentName)).uid;
			var ct_id = this.GetQueryString('ctId');
			var loading = dialog({
				contentType: 'load',
				skin: 'bk-popup'
			});
			var self = this;
			loading.show();
			sendPost(server_jm + "/medicine/physicalExamination/showDetail", {
				patientCode: 'P20161011001',
				ct_id: ct_id
			}, "json", "get", function(res) {
				loading.close();
				dialog({contentType:'tipsbox', skin:'bk-popup' , content:res.msg||"数据请求失败",bottom:true}).show();	
			}, function(res) {
				loading.close();
				if(res.status == 200) {
					self.showConclusionByType(res.recordset)
					self.showConclusionChart(res.recordset)
					self.showNatureChart(res.recordset)
				} else {
					dialog({contentType:'tipsbox', skin:'bk-popup' , content:res.msg,bottom:true}).show();
				}
			});

		},
		//获取浏览器参数
		GetQueryString: function(name) {
			var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
			var r = window.location.search.substr(1).match(reg);
			if(r != null) return unescape(r[2]);
			return null;
		},
		// 根据类型显示体检结论
		showConclusionByType: function(data) {
			var reports = [];
			var _sort = function(chain) {
				return chain.map(function(r) {
					if(r.cl_template) { // 去除所有内嵌样式
						r.cl_template = r.cl_template.replace(/style='[^']*'/ig, '')
					}
					return r;
				}).sortBy(function(r) {
					return (r.cl_sort||0)*1
				}).value()
			}
			
			if(data) {
				reports = [];
				
				// 去除cl_template中可能含有的js脚本
				_.each(data.report||[],function(r) {
					if(r.cl_template) {
						r.cl_template = r.cl_template.replace(/<script.*?>.*?<\/script>/ig, '')
					}
					reports.push(r)
				})
				
				var results = _.chain(reports).groupBy(function(r) { 
					// 根据cl_type分组
					return r.cl_type
				}).map(function(rs,k) { 
					// 将分组后的结果{"类型名（cl_type）": report}转换成数组
					if(k == "状态采集/四诊采集") {
						var images = [], videos = [];
						_.each(rs, function(r) {
							$temp = $('<div>'+r.cl_template+'</div>');
							_.each($temp.find('img'),function(img) {
								images.push($(img).attr('src'))
							});
							_.each($temp.find('video'),function(v) {
								videos.push($(v).attr('src'))
							});
						})
						return {
							type: k,
							images: images,
							videos: videos
						}
					} else if(k == "健康状态要素积分") {
						
						
						return {
							type: k,
							rows: _sort(_.chain(rs).filter(function(r) {
									return /^<tr>/.test(r.cl_template)
								})),
							others: _sort(_.chain(rs).filter(function(r) {
									return !(/^<tr>/.test(r.cl_template))
								}))
						}
					} else {
						return {
							type: k,
							reports: _sort(_.chain(rs))
						}
					}
				}).value();
				
				var html = template('reportsTmpl',{reports: results});
				$('#textContent').html(html);
				$('#textContent *:hidden').show();
			}
		},
		showConclusionChart: function(data) {
			data.reportDetail && conclusionChart.init(data.reportDetail.conclusion)
		},
		showNatureChart: function(data) {
			data.reportDetail && natureChart.init(data.reportDetail.nature)
		}

	};

	$(document).ready(function() {
		var page = new Page();
	});

})(jQuery);

template.helper("setPhoto", function(p) {		
		return getImgUrl(p);
});