var request = getRequest(),
    patient = request.patient,
    rowInfo = JSON.parse(window.localStorage.getItem('checkRow'));

var Profile = {
	url: '',
	link: '',
	thatBaseInfo: '',
	thatPlus: null,
	thatMui: null,
	thatPromise: null,
	thatTempalteCode: '',
	thatSerial: '',
	thatPageContent: null,
	index: 0,
	firstCode: '',
	profileRes: [],
	dc: [],
	htmlStr:['<div id="no_result_wrap">',
				'<img class="no-result-img" src="img/shujuweikong_img.png" />',
				'<div class="f-fs14 c-323232 c-t-center" style="text-align:center">抱歉，暂未找到符合条件的结果。</div>',
			'</div>'].join(''),
	init: function (ops) {
		var me = this;
		if (!(!!ops && typeof ops === 'object')) {
			alert('参数有误！');
			return;
		}
		ops.cb && ops.cb.call(me);
		me.url = ops.url;
		me.link = ops.link;
		me.thatMui = ops.thatMui;
		me.thatPlus = ops.thatPlus;
		me.thatPromise = ops.thatPromise;
		me.thatBaseInfo = ops.thatBaseInfo;
		me.thatTempalteCode = ops.thatTempalteCode;
		me.thatSerial = ops.thatSerial;
		me.thatPageContent = ops.thatPageContent;
		me.index = 0;
		me.firstCode = '';
		me.profileRes = [];
		me.dc = [];
		window['dataCode']=[];
	},
	//获取模板
	templateRequest: function () {
		var me = this;
		return new me.thatPromise(function(resolve, reject) {
			me.thatMui.ajax( me.link, 
			{ dataType: 'html',
			  type:'GET', 
			  error: function(xht, type, throwErr) {
			  	me.thatMui.toast("档案模板获取失败。");
			  	me.thatPlus.nativeUI.closeWaiting();
			  },
			  success: function(html) {
			  	resolve(html);
			  }
			})
		}).catch(function(e) {
			console.error(e)
		})
	},
	//根据thatTempalteCode获取数据
	profileDataRequest: function () {
		return new Promise(function(resolve, reject) {
			var healthData = {
	      		event: rowInfo.id,
	      		patient: patient,
	      		catalog: rowInfo.catalogCode,
	      		serial: rowInfo.serial || '1'
	        }
			return janchaAPI.getHealthData({data: healthData}).then(function(res) {
				resolve(res)
			})
		}).catch(function(e) {
			console.error(e)
		})
	},
	promiseAll: function () {
		var me = this,
			fistDc = me.thatTempalteCode;
		me.thatPromise.all([ me.templateRequest(), me.profileDataRequest()]).then(function (datas) {
			var html = datas[0];
			me.profileRes.push(datas[1]);
			me.thatPageContent.html(html);
			me.firstCode = me.thatTempalteCode;
			me.dc = window['dataCode'];
			if (me.dc.length > 0) {
				me.reqDataMore(me);
			} else {
				me.changeData(fistDc);
			}
		}).catch(function(e) {
			console.error(e)
		})
	},
	//获取多个数据
	reqDataMore: function (me) {
		me.thatTempalteCode = me.dc[me.index];
		Promise.all([ me.profileDataRequest()]).then(function (datas) {
			me.profileRes.push(datas[0]);
			me.index++;
			if (me.dc.length > me.index) {
				me.reqDataMore(me);
			} else {
				me.changeData(me.firstCode);
			}
		});
	},
	
	changeData: function (fistDc) {
		var me = this,
			jsonData = [];
		me.dc.unshift(me.firstCode);
		$.each( me.profileRes, function (index) {
			jsonData.push(me.selectXmlDom(me.profileRes[index],me.dc[index]));
		});
		console.log(jsonData); 
		if (jsonData.length > 0) {
			if (jsonData.length === 1 && !!!jsonData[0]) {
				me.thatPageContent.html(me.htmlStr);
			} else {
				me.renderProfileTemplate($.extend(true,{},me.mosaicData(jsonData)));
			}
		} else {
			me.thatPageContent.html(me.htmlStr);
		}
//		plus.nativeUI.closeWaiting();
	},
	//渲染模板
	renderProfileTemplate: function (data) {
		this.thatPageContent.removeAttr('avalonctrl').attr('ms-controller',"viewController");
		var vm = avalon.define($.extend({},{"$id": "viewController"},data));
		avalon.scan();
	},
	//获取xml数据
	selectXmlDom: function (profileRes,tempalteCode) {
		var me = this,
			$dom = $(profileRes.data.replace(/<\?xml .*\?>/,'')),
			version = $dom.find(">version").length?$dom.find(">version").attr("code"):$dom.attr('version');
			$.trim(version) || (function () {
				version = $dom.find(">ClinicalDocument").length? '2.0.0.1' : '';
			})();
		if($.trim(version)) {
			var verNum = version.split('.')[0];
			var xmlToJson = window["dsXmlToJson"+tempalteCode+'_'+verNum],
				jsonData = {};
				 
			if(xmlToJson && $.isFunction(xmlToJson)) { 
				if(!profileRes.data || profileRes.data=="[]") {
					if(version=2) {
						profileRes.data = '<?xml version="1.0" encoding="utf-8"?><ClinicalDocument></ClinicalDocument>';
					} else {
						profileRes.data = '<?xml version="1.0" encoding="utf-8"?><root></root>';
					}
				}
				// xml 转 json
				if((typeof profileRes.data=='string')&&profileRes.data.constructor==String) {
					// 去除携带的脚本内容
					profileRes.data = profileRes.data.replace(/<script[^>]*?>[\s\S]*?<\/script>/ig,'');
					jsonData = xmlToJson(profileRes.data.replace(/<\?xml .*\?>/,''));
				}
			}
			return jsonData;
		} 
	},
	//数据拼接
	mosaicData: function (data) {
		for (var i = 1; i < data.length; i++) {
			data[i] && (function () {
				for (key in data[i]['data']) {
					data[0]['data'][key] = data[i]['data'][key];
				}
			})();
		}
		return data[0];
	}
};

var dataCode = [];


// 基本信息（包括userAgent、上个页面传递的数据）
var baseInfo = null,
	// 基础环境信息（包括当前webview）
	baseEnv = null;

var $profileItemList = $('.lin-sel-group'),
	// 搜索无结果时显示
	$noResultWrap = $('#no_result_wrap'),
	$selectedProfileName = $('#selected_profile_name'),
	$pageContent = $('.page-content');

// 分页查询当前页数
var curPage = 1,
	// iscroll 滚动条实例
	iscroller,
	catalogs = [];

var getCatalog = function() {
	var catalog = "";
	if(rowInfo && rowInfo.catalogCode) {
		catalog = rowInfo.catalogCode;
	}
	return catalog;
},
getCatalogName = function() {
	var name = "";
	if(rowInfo && rowInfo.label) {
		name = rowInfo.label;
	}else if(rowInfo && rowInfo.type){
		name = rowInfo.type;
	}
	return name;
},
// 初始化就诊事件列表
initProfileList = function() {
	$selectedProfileName.text(getCatalogName());
	var tempalteCode = getCatalog();
	if(tempalteCode) {
		getProfileTemplateHtml(tempalteCode);
	}
},
getProfileTemplateHtml = function(tempalteCode,serial){
	Profile.init({
		url: "http://www.xmtyw.cn/wlyy/doctor/archives/event/healthData",
		link: 'template/'+tempalteCode+'.html',
		thatMui: jQuery,
		thatPromise: Promise,
		thatBaseInfo: baseInfo,
		thatTempalteCode: tempalteCode,
		thatSerial: serial,
		thatPageContent: $pageContent,
	});
	Profile.promiseAll();
};
// 获取异步请求处理Promise对象
function getReqPromise(url, data,reqType,newWay) {
	return new Promise(function(resolve, reject) {
		sendPost(url, data,
		  	function queryFailed (xht, type, throwErr) {
				// dialog({contentType:'tipsbox', skin:'bk-popup' , content:'加载失败'}).show();
				// mui.toast("程序开了点小差， 请稍后重试！");
				if(type == "error" || type == "parsererror" || type == "null") {
					//mui.toast("程序开了点小差， 请稍后重试！");
					//throw new Error("加载失败");
					showErrorPage("程序开了点小差， 请稍后重试！");
				}
				return true;
		  	}
	  		, function success(res) {
				resolve(res); 
	  		},reqType, '', (newWay===false?false:true));
	});
}
$(function(){
    initProfileList();
});