// 基本信息（包括userAgent、上个页面传递的数据）
var request = getRequest(),
    patient = request.patient,
    rowInfo = JSON.parse(window.localStorage.getItem('checkRow')),
    userAgent = JSON.parse(window.localStorage.getItem('userAgent'));

	
var $time = $('#time'),
	$type = $('#type'),
	$deptDoctor = $('#dept_doctor'),
	$org = $('#org'),
	$diagnosis = $('#diagnosis');

var gallery = null;

// 获取基本信息（包括userAgent、上个页面传递的数据）
var getBaseInfo = function() {
	return {
		userAgent: userAgent,
		eventInfo: rowInfo,
		patiInfo: rowInfo
	}
},
// 获取基础环境信息
getBaseEnvPromise = function () {
	
	var env = {
		webview: plus&&plus.webview.currentWebview()
	};

	return Promise.resolve().then(function(res) {
		return env;
	});
},
getDetailPromise = function() {
	var data={
		event: rowInfo.id
	}
	janchaAPI.getEventDetail({data: data}).then(function(res) {
		var data = {},
			imgsMap = {};
		if(res.status==200) {
			data = res.data;
			var eventName = getEventTypeName(data.eventType);
			$type.text(eventName);
			showDeptDoctor(data.deptName,data.doctorName);
			$time.text(data.eventDate.substr(0,10));
			if(data.orgName) {
				$org.text(data.orgName);
				$org.parent().show();
			}
			
			$diagnosis.text(data.dianosis);
			imgsMap = _.groupBy(data.eventImg, function(v) {
				return v.imgType;
			});
			_.mapObject(imgsMap,function(val, key) {
				var catalog = key? key: "未分类";
				var $wrap = $('div[data-type="'+catalog+'"]'),
					$ul = $wrap.find('.img-list').eq(0);
					html = template('li_tmpl',{list: val});
				$ul.html(html);
				$wrap.show();
			});
		}
	})
	.then(function() {
		var $imgs = $('img.preview-img');
		$imgs.on('click',function() {
			var idx = $imgs.index(this);
			var length = $imgs.length;
			updateCatalogNameTip(this);
			$('#page_counter').text('('+(idx+1)+'/'+length+')')
			previewImage(idx);
			gallery.listen('afterChange', function() {
				var imgIdx = gallery.getCurrentIndex();
				var $img = $imgs.eq(imgIdx);
				updateCatalogNameTip($img);
				$('#page_counter').text('('+(imgIdx+1)+'/'+length+')')
				updateCatalog($img);
			});
			updateCatalog(this);
		});
	})
};

function getEventTypeName(type) {
	if(type=="1") {
		return "门诊";
	} else if(type=="2"){
		return "住院";
	} else if(type == "3"){
		return "体检";
	}
}

function showDeptDoctor(dept,doctor) {
	if(!dept&&!doctor) {
		return ;
	} else if(dept&& doctor) {
		$deptDoctor.html('<label>科室/医生：</label>'+dept+'/'+doctor);
	} else if(dept) {
		$deptDoctor.html('<label>科室：</label>'+dept);
	} else if(doctor) {
		$deptDoctor.html('<label>医生：</label>'+doctor);
	}
	$deptDoctor.show();
}

function updateCatalogNameTip(img) {
	var catalog = $(img).attr('data-catalog')||"";
	var subCatalog = $(img).attr('data-sub-catalog')||"";
	var catalogName = catalog;
	if(subCatalog) {
		catalogName = catalogName + '_' + subCatalog;
	}
	$('#catalog_name').text(catalogName);
}

function updateCatalog(img) {
	var catalog = $(img).attr('data-catalog')||"";
	var subCatalog = $(img).attr('data-sub-catalog')||"";
	$('.img-catalog').find('a.c-btn-icon[data-type="'+catalog+'"]').trigger('click',[false]);
	$('.sub-catalog').find('a.c-btn-icon[data-type="'+subCatalog+'"]').trigger('click',[false]);
}

/*
 * 获取图片路径
 */
function getImgUrl(str){
	if(typeof str != 'string'){
	    return "";
	}
	if(str.length == 0){
        return "";
    }else{
        if(str.indexOf("../")>-1){
            //访问本地路径
            return str;
        }else if((str.indexOf("http://")>-1) || (str.indexOf("https://")>-1)){
            return str;
        }else{
            //服务器上的图片路径
            return imgUrlDomain + str;
        }
    }
}

function previewImage(sid) {
	var pswpElement = document.querySelectorAll('.pswp')[0];
	var w = $(window).width(), h = $(window).height();
	var items = _.map($('img.preview-img'),function(img) {
		return {
			src: $(img).attr('src'),
			w: w,
			h: h,
			initialPosition: { x: 0, y:0 }
		}
	});

	var options = {
	    // optionName: 'option value'
	    // for example:
	    index: sid||0 // start at first slide
	};
	options.mainClass = 'pswp--minimal--dark';
    options.barsSize = {top:0,bottom:0};
	options.captionEl = false;
	options.fullscreenEl = false;
	options.shareEl = false;
	options.bgOpacity = 0.85;
	options.tapToToggleControls = false;
	options.pinchToClose = false;
	options.clickToCloseNonZoomable = false;
	options.tapToClose = true;
	options.errorMsg = '<div class="pswp__error-msg">对不起，该图片加载失败</div>';
	// Initializes and opens PhotoSwipe
	gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
	gallery.init();
}

// 页面业务处理流程开始
//new Promise(function(resolve, reject) {
//
////	mui.plusReady(function() {
////		// plus已经准备好，可以往下执行
////		resolve(true);
////	});
//}).then(function() {
//	
//	// 获取基础环境信息
//	return getBaseEnvPromise().then(function(env) {
//		baseEnv = env;
//		// 获取登录医生信息
//		baseInfo = getBaseInfo();
//	})
//})
//.then(function() {
//	return getDetailPromise();
//})
//.catch(function(e) { console && console.error(e) });

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