"use strict";
/**
 * mplus_modal_medicalrecord
 */
var mplus_modal_medicalrecord = function(){
	// 상속
	mplus_common.call(this);
	
	// 상위 객체 생성
	//var mplusPatient = new mplus_mobile_patient();
	//var mplusNursing = new mplus_nursing();
	
	//super
	var self = this;
	
	//==== 변수 { ====
	var varResultLists = [];
	
	//==== 변수 } ====
	var varGetDeviceInfo;
	
	/**
	 * 초기화
	 */
	this.init = function(){ //여기서 모든화면 콤보박스데이터를 집어넣자!!! 그래야지 화면이동할때 속도가 오래걸리지않음!!!
		//데이터
		initData();		
		
		// 초기 화면 조건 구성
		initCondition();
		
		// 이벤트 초기화
		addEvent();		
	};
	
	//==== 초기화 설정 { ====
	var initData = function(){
		$("#sltMedicalRecordListSearch").val("1");//기록 목록조회
		$("#sltMedicalRecordListSearch").trigger("change");//header 처리
		$("#chkMedicalRecordSelfList").prop("checked" , false);//본인기록	
		/*
		 * 진료기록 안드로이드 앱버전체크 후 안내 계획 폐지
		//앱버전체크
		var toNaiveMsg = {
				"type" : "command",
				"functionType" : "getDeviceInfo",
				"value" : {
				    "callbackFn":"window.activeObj.toNativeCallbackFn"
				}
		};
		*/
		//self.toNative(toNaiveMsg);
	};
	
	this.toNativeCallbackFn = function(result){
		varGetDeviceInfo = result;
		console.log(JSON.stringify(varGetDeviceInfo));
	};
	
	var initCondition = function(){
		// 초기 화면 조건 구성
		// 일자 설정
		initStartEndDate();
		
		searchMedicalRecord();
	};
	
	var searchMedicalRecord = function(){
		if($("#sltMedicalRecordListSearch").val() == 1){//기록목록조회
			var param = {
					userId:gLoginUserId,
					patientId:gPatientId,
					startDt: moment($("#txtMedicalRecordStartDt").val()).format("YYYYMMDD"),
					endDt: moment($("#txtMedicalRecordEndDt").val()).format("YYYYMMDD"),
					deptCd:gPatientDeptCd,
					personalRecordYn:($("#chkMedicalRecordSelfList").prop("checked") == true ? "Y" : "N" ),
					searchCls:gPatientTreatCls
			};
			//console.log("TEST : " + JSON.stringify(param));
			
			self.medical.getMediRecordList(param, processSearchMediRecordList);
		}else if($("#sltMedicalRecordListSearch").val() == 2){//기록내용조회
			var param = {
					userId:gLoginUserId,
					patientId:gPatientId,
					startDt: moment($("#txtMedicalRecordStartDt").val()).format("YYYYMMDD"),
					endDt: moment($("#txtMedicalRecordEndDt").val()).format("YYYYMMDD"),
					deptCd:gPatientDeptCd,
					personalRecordYn:($("#chkMedicalRecordSelfList").prop("checked") == true ? "Y" : "N" ),
					searchCls:gPatientTreatCls
			};
			//console.log("TEST : " + JSON.stringify(param));
			
			self.medical.getMediRecordFormList(param, processSearchMediRecordFormList);
		}
	};
	
	var processSearchMediRecordList = function(lists){
		//console.log(JSON.stringify(lists));
		varResultLists = lists;

		var strDisplayTemp = "";
		$("#divMedicalRecordRows").empty();
		for( var i = 0; i < lists.length; i++){
			var medicalRecordColor = "";
			if(lists[i].medicalRecordSubTitle != null && lists[i].medicalRecordSubTitle != "-"){
				medicalRecordColor = "color:#C86400;";
			}
			
			strDisplayTemp += "<div class=\"row list-group-item\" rowNo=\"" + i + "\" medicalRecordSeq=\"" + lists[i].medicalRecordSeq + "\" style=\"overflow: hidden; padding-left: 0px; padding-right: 0px;\">"
			+ "  <div class=\"col-xs-12 col-sm-6 col-lg-6\">"
			+ "    <div class=\"col-xs-3 col-sm-3 col-lg-3 text-center\" style=\"padding: 0px;\">" + ((moment(lists[i].medicalRecordDt).format("YYYY-MM-DD") != "Invalid date") ? moment(lists[i].medicalRecordDt).format("YYYY-MM-DD") : "-") + "</div>"
			+ "    <div class=\"col-xs-4 col-sm-3 col-lg-3 text-center\" style=\"padding: 0px; "+medicalRecordColor+" \">" + lists[i].medicalRecordFormNm + "</div>"
			+ "    <div class=\"col-xs-3 col-sm-3 col-lg-3 text-center\" style=\"padding: 0px; "+medicalRecordColor+" \">" + lists[i].medicalRecordSubTitle + "</div>"
			+ "    <div class=\"col-xs-2 col-sm-3 col-lg-3 text-center\" style=\"padding: 0px;\">" + lists[i].lastWriter + "</div>"
			+ "  </div>"
			+ "</div>"
			;
			//console.log( i + " : " + lists[i].deptNm);
		}
	
		$("#divMedicalRecordRows").append(strDisplayTemp);	// element 추가
		
		addEventSearchMediRecord(); // row click event 추가
	};
	
	var processSearchMediRecordFormList = function(lists){
		//console.log(JSON.stringify(lists));
		varResultLists = lists;

		var strDisplayTemp = "";
		$("#divMedicalRecordRows").empty();
		for( var i = 0; i < lists.length; i++){
			
			strDisplayTemp += "<div class=\"row list-group-item\" rowNo=\"" + i + "\" medicalRecordFormCd=\"" + lists[i].medicalRecordFormCd + "\" style=\"overflow: hidden; padding-left: 0px; padding-right: 0px;\">"
			+ "  <div class=\"col-xs-12 col-sm-6 col-lg-6\">"
			+ "    <div class=\"col-xs-12 col-sm-3 col-lg-3 text-center\" style=\"padding: 0px;\">" + lists[i].medicalRecordFormNm + "</div>"
			+ "  </div>"
			+ "</div>"
			;
			//console.log( i + " : " + lists[i].deptNm);
		}
	
		$("#divMedicalRecordRows").append(strDisplayTemp);	// element 추가
		
		addEventSearchMediRecord(); // row click event 추가
	};
	
	var addEventSearchMediRecord = function() {
		$("#divMedicalRecordRows .list-group-item").off("click"); // 기존 이벤트 해제
		$("#divMedicalRecordRows .list-group-item").on("click", function(e){
			//진료기록 조회 리스트 검색 처리
			var varMedicalRecordrowNo = "";
			var varMedicalRecordSeq = "";
			var varMedicalRecordFormCd = "";
			if(e.currentTarget.attributes.rowNo !== undefined){
				varMedicalRecordrowNo = e.currentTarget.attributes.rowNo.value;
			}
			if(e.currentTarget.attributes.medicalRecordSeq !== undefined){
				varMedicalRecordSeq = e.currentTarget.attributes.medicalRecordSeq.value;
			}
			if(e.currentTarget.attributes.medicalRecordFormCd !== undefined){
				varMedicalRecordFormCd = e.currentTarget.attributes.medicalRecordFormCd.value;
			}
			
			/* 2019 03 11 iSO일 경우 alert후 return */
			/*
			if(gLoginUserId == "29990030"){
			
			}else if(self.isIos()){
				//console.log("iOS입니다.");
				self.alert("iOS에서 본 기능은 서비스 개발중입니다.");
				return;
			}else{//안드로이드일때 처리
				
			}*/
			
			if($("#sltMedicalRecordListSearch").val() == 1 && varMedicalRecordSeq != ""){//기록목록조회
				/*
				var initParam = {
						medicalRecordFormNm:varResultLists[varMedicalRecordrowNo].medicalRecordFormNm,
						
						userId:gLoginUserId,
						patientId:gPatientId,
						deptCd:gPatientDeptCd,
						searchCls:gPatientTreatCls,
						medicalRecordSeq:varMedicalRecordSeq
				};
				//$("#modalMedicalRecordRslt").modal("show");
				//mplusModalMedicalrecorddetail.initList(initParam);
				*/
				//진료 기록 상세 조회
				var sendParam = {
						userId:gLoginUserId,
						patientId:gPatientId,
						deptCd:gPatientDeptCd,
						searchCls:gPatientTreatCls,
						medicalRecordSeq:varMedicalRecordSeq
				};
				//console.log(JSON.stringify(sendParam));
				self.medical.getMediRecordDetail(sendParam, processMedicalRecordResult);
			}else if($("#sltMedicalRecordListSearch").val() == 2 && varMedicalRecordFormCd != ""){//기록내용조회
				/*
				var initParam = {
						medicalRecordFormNm:varResultLists[varMedicalRecordrowNo].medicalRecordFormNm,
						
						userId:gLoginUserId,
						patientId:gPatientId,
						deptCd:gPatientDeptCd,
						startDt: moment($("#txtMedicalRecordStartDt").val()).format("YYYYMMDD"),
						endDt: moment($("#txtMedicalRecordEndDt").val()).format("YYYYMMDD"),
						personalRecordYn:($("#chkMedicalRecordSelfList").prop("checked") == true ? "Y" : "N" ),
						medicalRecordFormCd:varMedicalRecordFormCd,
						searchCls:gPatientTreatCls
				};
				//$("#modalMedicalRecordRslt").modal("show");
				//mplusModalMedicalrecorddetail.initContents(initParam);
				*/
				//진료 기록 내용 상세 조회
				var sendParam = {
						userId:gLoginUserId,
						patientId:gPatientId,
						deptCd:gPatientDeptCd,
						startDt:moment($("#txtMedicalRecordStartDt").val()).format("YYYYMMDD"),
						endDt:moment($("#txtMedicalRecordEndDt").val()).format("YYYYMMDD"),
						personalRecordYn:($("#chkMedicalRecordSelfList").prop("checked") == true ? "Y" : "N" ),
						medicalRecordFormCd:varMedicalRecordFormCd,
						searchCls:gPatientTreatCls
				};
				//console.log(JSON.stringify(sendParam));
				self.medical.getMediRecordContentDetail(sendParam, processMedicalRecordResult);				
			}else{
				self.alert("데이터 오류입니다. 관리자에게 문의하세요.");
				return;
			}
		});
	};
	
	var processMedicalRecordResult = function(lists){
		if(lists[0].url != null && lists !== undefined){
			//$("#divMedicalRecordResult").append(lists[0].url);	// element 추가
			var jsonMsg = {
				    "type":"command",
				    "functionType":"popup",
				    "value" : {
				        "url" : lists[0].url,
				        "method": "GET",  // Default "GET"  ** 2017-10-19 추가
				        "parameters": "-"  // POST 인 경우만, GET 인 경우는 "url" 에 모두 붙여서 전달  ** 2017-10-19 추가
				    }
			};
			self.toNative(jsonMsg);  
		}else{
			self.alert("데이터 오류입니다. 관리자에게 문의하세요.");
		}
	};
	
	var initStartEndDate = function(){
		//오늘일자 로드
		var varToday = new Date();
			
		//일요일이면 차주 가져오기
		//다른 요일이면 해당 요일 처리
		$("#txtMedicalRecordEndDt").val( moment(varToday).format("YYYY-MM-DD") );
		varToday.setDate(varToday.getDate() - 6);
		$("#txtMedicalRecordStartDt").val( moment(varToday).format("YYYY-MM-DD") );
	};
	//==== 초기화 설정 } ====
	
	//==== 이벤트 설정 { ====
	var addEvent = function(){
		//$("#btnLogout").on("click", function(){
		//	logout();
		//});
		
		eventColumnClick();
		
		eventRowClick();
		
		eventConditionClick();
	};
	
	var eventConditionClick = function(){
		// 1주 버튼클릭
		$("#btnMedicalRecordOneWeekSearch").off('click'); // 기존 이벤트 해제
		$("#btnMedicalRecordOneWeekSearch").on('click', function(e){
			var varSelDate = new Date($("#txtMedicalRecordEndDt").val());
			varSelDate.setDate(varSelDate.getDate() - 6);
			$("#txtMedicalRecordStartDt").val( moment(varSelDate).format("YYYY-MM-DD") );
		});
		// 1달 버튼클릭
		$("#btnMedicalRecordOneMonthSearch").off('click'); // 기존 이벤트 해제
		$("#btnMedicalRecordOneMonthSearch").on('click', function(e){
			var varSelDate = new Date($("#txtMedicalRecordEndDt").val());
			varSelDate.setDate(varSelDate.getDate() - 1);
			varSelDate.setMonth(varSelDate.getMonth() - 1);
			$("#txtMedicalRecordStartDt").val( moment(varSelDate).format("YYYY-MM-DD") );
		});
		// 3달 버튼클릭
		$("#btnMedicalRecordThreeMonthSearch").off('click'); // 기존 이벤트 해제
		$("#btnMedicalRecordThreeMonthSearch").on('click', function(e){
			var varSelDate = new Date($("#txtMedicalRecordEndDt").val());
			varSelDate.setDate(varSelDate.getDate() - 1);
			varSelDate.setMonth(varSelDate.getMonth() - 3);
			$("#txtMedicalRecordStartDt").val( moment(varSelDate).format("YYYY-MM-DD") );
		});
		
		// 조회버튼
		$("#btnMedicalRecordSearch").off('click'); // 기존 이벤트 해제
		$("#btnMedicalRecordSearch").on('click', function(e){
			//로우 초기화
			$("#divMedicalRecordRows").empty();
			
			searchMedicalRecord();
		});
		
		$("#sltMedicalRecordListSearch").off("change");
		$("#sltMedicalRecordListSearch").on("change", function(){
			var strDisplayTemp = "";
			//header변경
			if($("#sltMedicalRecordListSearch").val() == 1){//기록목록조회
				$("#divMedicalRecordListResultHeader").empty();
				strDisplayTemp = "<div class=\"chart-title well\">"
					+ "<div class=\"row\">"
					+ "  <div class=\"col-xs-3 text-center\" style=\"padding: 4px 0px;\">"
					+ "	<p>접수일</p>"
					+ "  </div>"
					+ "  <div class=\"col-xs-4 text-center\" style=\"padding: 4px 0px;\">"
					+ "	<p>서식명</p>"
					+ "  </div>"
					+ "  <div class=\"col-xs-3 text-center\" style=\"padding: 4px 0px;\">"
					+ "	<p>부제목</p>"
					+ "  </div>"
					+ "  <div class=\"col-xs-2 text-center\" style=\"padding: 4px 0px;\">"
					+ "	<p>최종작성</p>"
					+ "  </div>"
					+ "</div>"
					+ "</div>"
					;
				
			}else if($("#sltMedicalRecordListSearch").val() == 2){//기록내용조회
				$("#divMedicalRecordListResultHeader").empty();
				strDisplayTemp = "<div class=\"chart-title well\">"
					+ "<div class=\"row\">"
					+ "  <div class=\"col-xs-12 text-center\" style=\"padding: 4px 0px;\">"
					+ "	<p>해당기간 기록내용조회 선택</p>"
					+ "  </div>"
					+ "  </div>"
					+ "</div>"
					;
			}
			$("#divMedicalRecordListResultHeader").append(strDisplayTemp);
			searchMedicalRecord();
		});
		
	};
	
	var eventColumnClick = function(){

	};
	
	var eventRowClick = function(){
		
	};
	//==== 이벤트 설정 } ====
	
	
	//==== 서비스 실행 { ====
	//==== 서비스 실행 { ====
	
};