"use strict";
/**
 * mplus_modal_prescription
 */
var mplus_modal_prescription = function(){
	// 상속
	mplus_common.call(this);
	
	// 상위 객체 생성
	//var mplusPatient = new mplus_mobile_patient();
	//var mplusNursing = new mplus_nursing();
	
	//super 
	var self = this;
	var varPrescriptionLists = [];
	//20190607 dkchoi75
	// var varExamrslttyParam = { "examCd" : "", "examRsltKey" : "", "examRsltKey2" : "", "examRsltKey3" : "" };
	var varExamrslttyParam = { "examCd" : "", "examRsltKey" : "", "examRsltKey2" : "", "examRsltKey3" : "", "prescriptionNo" : "" };
	
	//==== 변수 { ====
	//==== 변수 } ====
		
	/**
	 * 초기화
	 */
	this.init = function(){ //여기서 모든화면 콤보박스데이터를 집어넣자!!! 그래야지 화면이동할때 속도가 오래걸리지않음!!!
		// 초기 화면 조건 구성
		initCondition();
		
		// 이벤트 초기화
		addEvent();		
	};
	
	//==== 초기화 설정 { ====
	var initCondition = function(){
		
		initEmptyData();
		
		initSetData();
		
		// 초기 화면 조건 구성
		//외래 입원 분기처리
		searchMedicalInOut();
		
		//처방조회 조회
		//searchMedicalPrescriptionList();
		
		//3.처방 분류 리스트
		searchMedicalPrescriptionClsList();
		//4.처방 상태 리스트
		searchMedicalgetPrescriptionStatList();
		//5.구분 리스트
		searchMedicalgetPrescriptionClassList();
	};
	var initSetData = function(){
		var varToday = new Date();		
		$("#txtPrescriptionVisitDt").val(moment(varToday).format("YYYY-MM-DD"));
	};
	
	var initEmptyData = function(){
		$("#divPrescriptionResultRows").empty();
		varPrescriptionLists = [];
		// 20190607 dkchoi75
		//varExamrslttyParam = { "examCd" : "", "examRsltKey" : "", "examRsltKey2" : "", "examRsltKey3" : "" };
		varExamrslttyParam = { "examCd" : "", "examRsltKey" : "", "examRsltKey2" : "", "examRsltKey3" : "", "prescriptionNo" : "" };
	}
	
	var searchMedicalPrescriptionList = function(){
		var varPrescriptionDt = "";
		
		if(gPatientTreatCls == "I"){ //입원
			varPrescriptionDt = moment($("#txtPrescriptionVisitDt").val()).format("YYYYMMDD");
			//20190520 dkchoi75 백병원 입원>처방조회 시 외래일자 API 변경 미처리 부분
		//	varPrescriptionDt = moment($("#sltOutPrescriptionHospitalizationDt").val()).format("YYYYMMDD");
		}else if(gPatientTreatCls == "O"){ //외래
			varPrescriptionDt = moment($("#sltOutPrescriptionHospitalizationDt").val()).format("YYYYMMDD");
		}
		// 20190502 dkchoi75 : 응급 처방조회 목록 수정
		else if(gPatientTreatCls == "E"){ //응급
			varPrescriptionDt = moment($("#sltOutPrescriptionHospitalizationDt").val()).format("YYYYMMDD");
		}
		
		var param = {
				userId:gLoginUserId,
				patientId:gPatientId,
				deptCd:gPatientDeptCd,
				searchCls:gPatientTreatCls,
				prescriptionDt:varPrescriptionDt,
				prescriptionClsCd:$("#sltPrescriptionClsCd").val(),
				prescriptionStatCd:$("#sltPrescriptionStatCd").val(),
				prescriptionCls2Cd:$("#sltPrescriptionClass").val()
		};
		
		self.medical.getPrescription(param, processSearchMedicalPrescriptionList);
	};
	
	var processSearchMedicalPrescriptionList = function(lists){
		//console.log(JSON.stringify(lists));
		varPrescriptionLists = lists;
		var strDisplayTemp = "";
		$("#divPrescriptionResultRows").empty();
		for( var i = 0; i < lists.length; i++){
			
			strDisplayTemp += "<div id=\"" + "divPrescriptionList" + i + "\" class=\"row list-group-item\" listCnt=\"" + i + "\" prescriptionNo=\"" + lists[i].prescriptionNo + "\" style=\"overflow: hidden; padding-left: 0px; padding-right: 0px;\">"
			+ "  <div class=\"col-xs-12\" style=\" padding-left: 0px; padding-right: 0px;\">"
			+ "    <div class=\"col-xs-1 text-center\" style=\"padding: 0px;\">" + lists[i].prescriptionStatNm + "</div>"
			+ "    <div class=\"col-xs-1 text-center\" style=\"padding: 0px;\">" + lists[i].prescriptionClsNm + "</div>"
			+ "    <div class=\"col-xs-1 text-center\" style=\"padding: 0px;\">" + lists[i].prescriptionCls2Nm + "</div>"
			+ "    <div class=\"col-xs-9\" style=\"padding-left: 5px;\">" + lists[i].prescriptionNm + "</div>"
			+ "  </div>"
			+ "  <div id=\"divPrescriptionDetail" + i + "\" class=\"hidden col-xs-12\">"
			+ "    <div class=\"col-xs-2 \" style=\"padding: 0px;\">" + "</div>"
			+ "    <div class=\"col-xs-10 \" style=\"padding: 0px;\">" + lists[i].prescriptionStatNm + " / " + ((lists[i].commentYn == "Y") ? lists[i].comment : "")  + "</div>"
			+ "    <div class=\"col-xs-2 \" style=\"padding: 0px;\"></div>" 			
			+ "    <div class=\"col-xs-10 \" style=\"padding: 0px;\">" ;
			
			 if(lists[i].examResultKey != null && lists[i].examResultKey != "" && lists[i].examResultKey != "-"){
				strDisplayTemp += "    		<button id=\"btnCallExamrsltty\" type=\"button\" class=\"btn btn-info\">검사결과</button>"
			 }
			if(lists[i].medicationKeyYn == "Y"){
				strDisplayTemp += "    		<button id=\"btnCallMedicationlist\" type=\"button\" class=\"btn btn-info\">투약조회</button>"
			}
			
			//2019.04.15. 건대 코드 하드코딩
			// prescriptionClsCd (11 주사)(12 내복약) 또는 처방코드 앞문자가 M 또는 I
			//2019.05.09 백병원 요구사항으로 약품정보 버튼 미노출
			// 20190610 dkchoi75 일산백병원 요구사항으로 약품정보 버튼 노출 Y: 노출 N:미노출
			var varDrogInfoButtonYn = "Y";
			//if(lists[i].prescriptionClsCd == "11" || lists[i].prescriptionClsCd == "12" || (lists[i].prescriptionCd).indexOf("M") == 0 || (lists[i].prescriptionCd).indexOf("I") == 0){
			if(lists[i].prescriptionCd != null && lists[i].prescriptionCd != "" && lists[i].prescriptionCd != "-"){
			//if(lists[i].comment != null && lists[i].comment != "" && lists[i].comment != "-" && varDrogInfoButtonYn == "Y"){
				strDisplayTemp += "    		<button id=\"btnCallPrescriptionDrugInfo\" type=\"button\" class=\"btn btn-info\">약품정보</button>"
			}
			strDisplayTemp += "    </div>"
			+ "  </div>"
			+ "</div>"
			;
			//console.log( i + " : " + lists[i].deptNm);
		}
		
		$("#divPrescriptionResultRows").append(strDisplayTemp);	// element 추가
		
		//선택이벤트 처리
		addEventPrescriptionResult();		
	};
	
	var addEventPrescriptionResult = function() {
		$("#divPrescriptionResultRows .list-group-item").off("click"); // 기존 이벤트 해제
		$("#divPrescriptionResultRows .list-group-item").on("click", function(e){
			//진료기록 조회 리스트 검색 처리
			var varPreCnt = e.currentTarget.attributes.listCnt.value;
			var divPrescriptionId = "#divPrescriptionDetail" + varPreCnt;

			// 20190610 dkchoi75 일산백병원 약품정보 Naver 연동 서비스 구분 N:Naver, E:내부EMR, K:킴스
			var varDrugInfoApi = "N";

			//버튼 클릭 이벤트 처리
			if((e.target.id).indexOf("btnCallExamrsltty") != -1){//검사결과

                varExamrslttyParam.examRsltKey =
                    ((varPrescriptionLists[varPreCnt].examResultKey != undefined ||
                            varPrescriptionLists[varPreCnt].examResultKey != null ||
                            varPrescriptionLists[varPreCnt].examResultKey != "" ||
                            varPrescriptionLists[varPreCnt].examResultKey != "-") ? varPrescriptionLists[varPreCnt].examResultKey : ""
                    );

                // 20190607 dkchoi75
				varExamrslttyParam.prescriptionNo = varPrescriptionLists[varPreCnt].prescriptionNo;

                if (varPrescriptionLists[varPreCnt].isExamResult == "1"){
				// if(varPrescriptionLists[varPreCnt].examResultKey != null && varPrescriptionLists[varPreCnt].examResultKey != "" && varPrescriptionLists[varPreCnt].examResultKey != "-"){
					//examResultKey의 값을 정확하게 처리해야함!!! 체크바람!
					if(varPrescriptionLists[varPreCnt].examRsltTy == "1"){//검사결과 검체
						$("#modalExamRsltTy1").modal("show");
						//mplusModalExamrsltty1.init(varPrescriptionLists[varPreCnt]);
						mplusModalExamrsltty1.init(varExamrslttyParam);
					}else{//판독결과
						// 환자 정보 화면 띄우기
						$("#modalExamRsltTy2").modal("show");
						//mplusModalExamrsltty2.init(varPrescriptionLists[varPreCnt]);
						mplusModalExamrsltty2.init(varExamrslttyParam);
					}
				}else{
					//self.alert("데이터 오류입니다. 관리자에게 문의하세요.");
					console.log("examResultKey값 확인바람 : " + varPrescriptionLists[varPreCnt].examResultKey);
				}
				return;
			}else if((e.target.id).indexOf("btnCallMedicationlist") != -1){//투약조회
				if(/*varPrescriptionLists[varPreCnt].prescriptionNo != "" &&*/ varPrescriptionLists[varPreCnt].prescriptionCd != ""&& varPrescriptionLists[varPreCnt].medicationSearchDt != ""){
					var param = {
							prescriptionCd: varPrescriptionLists[varPreCnt].prescriptionCd,
							prescriptionNo: varPrescriptionLists[varPreCnt].prescriptionNo,
							medicationSearchDt: varPrescriptionLists[varPreCnt].medicationSearchDt
					};
					$("#modalMedicationList").modal("show");
					mplusModalMedicationlist.init(param);
				}else{
					//self.alert("데이터 오류입니다. 관리자에게 문의하세요.");
					console.log("prescriptionCd 확인바람 : " + varPrescriptionLists[varPreCnt].prescriptionCd);
				}
				return;
			}else if((e.target.id).indexOf("btnCallPrescriptionDrugInfo") != -1){//약품정보
				//if(varPrescriptionLists[varPreCnt].prescriptionCd != null && varPrescriptionLists[varPreCnt].prescriptionCd != "" && varPrescriptionLists[varPreCnt].prescriptionCd != "-"){
//				if(varPrescriptionLists[varPreCnt].comment != null && varPrescriptionLists[varPreCnt].comment != "" && varPrescriptionLists[varPreCnt].comment != "-" ){
					// 20190610 dkchoi75 일산백병원 약품정보 Naver 연동
					if (varDrugInfoApi == "N") {
						var jsonMsg = {
							"type":"command",
							"functionType":"popup",
							"value" : {
								"url" : "http://m.terms.naver.com/medicineSearch.nhn?query=" + varPrescriptionLists[varPreCnt].comment,
								"method": "GET",  // Default "GET"  ** 2017-10-19 추가
								"parameters": "-"  // POST 인 경우만, GET 인 경우는 "url" 에 모두 붙여서 전달  ** 2017-10-19 추가
							}
						};
						self.toNative(jsonMsg);
					} else if (varDrugInfoApi == "E") {
						var param = {
							orderCd: varPrescriptionLists[varPreCnt].prescriptionCd
						};
						//console.log("prescriptionCd : " + varPrescriptionLists[varPreCnt].prescriptionCd);
						mplusModalMedication.init(param);
						$("#mplusAlertDrugInfo").modal("show");
					} else if (varDrugInfoApi == "K") {
						// 킴스 연동 부분
					}
//				}else{
					//self.alert("데이터 오류입니다. 관리자에게 문의하세요.");
//					self.alert("약품정보가 없습니다.");
					//console.log("prescriptionCd 확인바람 : " + varPrescriptionLists[varPreCnt].prescriptionCd);
//				}
				return;
			}
			
			if( $(divPrescriptionId).hasClass("hidden")) {
				$(divPrescriptionId).removeClass("hidden");
			} else {
				$(divPrescriptionId).addClass("hidden");
			}
			
		});
	};
	
	var searchMedicalInOut = function(){
		if(gPatientTreatCls == "I"){ //입원
			$("#divOutPrescriptionHospitalizationDt").addClass('hidden');
			$("#divInPrescriptionHospitalizationDt").removeClass('hidden');
			//1.입원일자 이력 리스트
			// 20190514 dkchoi75 백병원 요구사항 입원->처방조회 검색 부분 외래로 맞춰달라고 함
			//$("#divOutPrescriptionHospitalizationDt").removeClass('hidden');
			//$("#divInPrescriptionHospitalizationDt").addClass('hidden');
			searchMedicalInDateList();
			//searchMedicalOutDateList();
		}else if(gPatientTreatCls == "O"){ //외래
			$("#divOutPrescriptionHospitalizationDt").removeClass('hidden');
			$("#divInPrescriptionHospitalizationDt").addClass('hidden');
			//2.외래 진료일자 이력 리스트
			searchMedicalOutDateList();
		}
		// 20190502 dkchoi75 : 응급 처방조회 목록 수정
		else if(gPatientTreatCls == "E"){ //응급
			$("#divOutPrescriptionHospitalizationDt").removeClass('hidden');
			$("#divInPrescriptionHospitalizationDt").addClass('hidden');
			//3.응급(외래) 진료일자 이력 리스트
			searchMedicalOutDateList();
		}
	};
	
	var searchMedicalInDateList = function(){
		var param = {
				userId:gLoginUserId,
				patientId:gPatientId
		};
		
		self.medical.getInDateList(param, processSearchMedicalInDateList);
	};
	
	var processSearchMedicalInDateList = function(lists){
		$("#sltInPrescriptionHospitalizationDt").empty();
		var strDisplayTemp = "";
		strDisplayTemp = "<option value=\"\">입원일자 리스트</option>";
		if(lists != undefined){
			for(var i=0; i<lists.length; i++){
				var varHospitalizationDt = "";
				var varDischargeDt = "";
				if(lists[i].hospitalizationDt != undefined && lists[i].hospitalizationDt != "" && lists[i].hospitalizationDt != null) {
					varHospitalizationDt = moment(lists[i].hospitalizationDt).format("YYYY-MM-DD");
				} else {
					varHospitalizationDt = lists[i].hospitalizationDt;
				}

				if(lists[i].dischargeDt != undefined && lists[i].dischargeDt != "" && lists[i].dischargeDt != null) {
					varDischargeDt = moment(lists[i].dischargeDt).format("YYYY-MM-DD");
				} else {
					varDischargeDt = lists[i].dischargeDt;
				}

				// strDisplayTemp += "<option value=\""+ lists[i].hospitalizationDt +"\">"+ moment(lists[i].hospitalizationDt).format("YYYY-MM-DD") + "~" + moment(lists[i].dischargeDt).format("YYYY-MM-DD") +"</option>";
				strDisplayTemp += "<option value=\""+ varHospitalizationDt +"\">"+ varHospitalizationDt + "~" + varDischargeDt +"</option>";
			}
		}
		$("#sltInPrescriptionHospitalizationDt").append(strDisplayTemp);
				
		$("#sltInPrescriptionHospitalizationDt").val($("#sltInPrescriptionHospitalizationDt option:first").val());
		
		//처방조회 조회
		searchMedicalPrescriptionList();
	};


	var searchMedicalOutDateList = function(){
		var param = {
				userId:gLoginUserId,
				patientId:gPatientId,
			    //20190521 dkchoi75 백병원 Input Paremeter에 deptCd (진료과코드) 추가
			    deptCd:gPatientDeptCd
		};
		
		self.medical.getOutDateList(param, processSearchMedicalOutDateList);
	};
	
	var processSearchMedicalOutDateList = function(lists){
		$("#sltOutPrescriptionHospitalizationDt").empty();
		var varVisitDt = "";
		var strDisplayTemp = "";
		if(lists != undefined){
			for(var i=0; i<lists.length; i++){
                if(lists[i].visitDt != undefined && lists[i].visitDt != "" && lists[i].visitDt != null) {
                    varVisitDt = moment(lists[i].visitDt).format("YYYY-MM-DD");
                } else {
                    varVisitDt = lists[i].visitDt;
                }

				// strDisplayTemp += "<option value=\""+ lists[i].visitDt +"\" deptCd=\"" + lists[i].deptCd + "\" >"+ moment(lists[i].visitDt).format("YYYY-MM-DD") +"</option>";
                strDisplayTemp += "<option value=\""+ lists[i].visitDt +"\" deptCd=\"" + lists[i].deptCd + "\" >"+ varVisitDt +"</option>";
			}
		}else{
			strDisplayTemp = "<option value=\"\">진료일이 없습니다.</option>";
		}
		$("#sltOutPrescriptionHospitalizationDt").append(strDisplayTemp);
				
		$("#sltOutPrescriptionHospitalizationDt").val($("#sltOutPrescriptionHospitalizationDt option:first").val());
		
		//처방조회 조회
		searchMedicalPrescriptionList();
	};
	
	var searchMedicalPrescriptionClsList = function(){
		var param = {
				userId:gLoginUserId,
				searchCls:gPatientTreatCls
		};
		
		self.medical.getPrescriptionClsList(param, processSearchMedicalPrescriptionClsList);
	};
	
	var processSearchMedicalPrescriptionClsList = function(lists){
		$("#sltPrescriptionClsCd").empty();
		var strDisplayTemp = "";
		strDisplayTemp = "<option value=\"\">분류</option>";		
		if(lists != undefined){
			for(var i=0; i<lists.length; i++){
				strDisplayTemp += "<option value=\""+ lists[i].prescriptionClsCd +"\">"+ lists[i].prescriptionClsNm +"</option>";
			}
		}
		$("#sltPrescriptionClsCd").append(strDisplayTemp);
				
		$("#sltPrescriptionClsCd").val($("#sltPrescriptionClsCd option:first").val());
	};
	
	var searchMedicalgetPrescriptionStatList = function(){
		var param = {
				userId:gLoginUserId,
				searchCls:gPatientTreatCls
		};
		
		self.medical.getPrescriptionStatList(param, processSearchMedicalPrescriptionStatList);
	};
	
	var processSearchMedicalPrescriptionStatList = function(lists){
		$("#sltPrescriptionStatCd").empty();
		var strDisplayTemp = "";
		strDisplayTemp = "<option value=\"\">상태</option>";
		if(lists != undefined){
			for(var i=0; i<lists.length; i++){
				strDisplayTemp += "<option value=\""+ lists[i].prescriptionStatCd +"\">"+ lists[i].prescriptionStatNm +"</option>";
			}
		}
		$("#sltPrescriptionStatCd").append(strDisplayTemp);
				
		$("#sltPrescriptionStatCd").val($("#sltPrescriptionStatCd option:first").val());
	};
	
	var searchMedicalgetPrescriptionClassList = function(lists){
		$("#sltPrescriptionClass").empty();
		var strDisplayTemp = "";
		strDisplayTemp = "<option value=\"\">구분</option>";
		if(lists != undefined){
			for(var i=0; i<lists.length; i++){
				strDisplayTemp += "<option value=\""+ lists[i].prescriptionStatCd +"\">"+ lists[i].prescriptionStatNm +"</option>";
			}
		}
		$("#sltPrescriptionClass").append(strDisplayTemp);
				
		$("#sltPrescriptionClass").val($("#sltPrescriptionClass option:first").val());
	};
	
	//==== 초기화 설정 } ====
	
	//==== 이벤트 설정 { ====
	var addEvent = function(){
		//$("#btnLogout").on("click", function(){
		//	logout();
		//});
		eventConditionClick();
		
		eventColumnClick();
		
		eventRowClick();
	};
	
	var eventConditionClick = function(){
		// 조회버튼
		$("#btnPrescriptionSearch").off("click"); // 기존 이벤트 해제
		$("#btnPrescriptionSearch").on("click", function(e){
			searchMedicalPrescriptionList();
		});
		
		
		$("#sltOutPrescriptionHospitalizationDt").off("change");
		$("#sltOutPrescriptionHospitalizationDt").on("change", function(){
			//처방조회 조회
			searchMedicalPrescriptionList();
		});
	};
	
	var eventColumnClick = function(){

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