"use strict";
/**
 * mplus_medical_outpatientsch
 */
var mplus_schedule_outpatientsch = function(){
	// 상속
	mplus_common.call(this);
	
	// 상위 객체 생성
	//var mplusPatient = new mplus_mobile_patient();
	//var mplusNursing = new mplus_nursing();
	
	//super
	var self = this;
	
	//선택일자 전역변수
	var varSelDate;
	
	var varResultLists = [];
	//==== 변수 } ====
		
	/**
	 * 초기화
	 */
	this.init = function(){ //여기서 모든화면 콤보박스데이터를 집어넣자!!! 그래야지 화면이동할때 속도가 오래걸리지않음!!!
		// 접근 권한 체크
		checkAccessPermission();
		
		// 초기 화면 조건 구성
		initCondition();
		
		// 이벤트 초기화
		addEvent();
	};
	
	//==== 접근 권한 체크 { ====
	var checkAccessPermission = function(){
		//if( !self.common.checkAccessJobKind( "1000")){
		//	self.alertTrue("접근 권한이 없습니다.", self.common.gotoDefaultHomePage);
		//}
			
		//if( !self.common.checkAccessUserAuth( "01")){
		//	self.alertTrue("접근 권한이 없습니다.", self.common.gotoDefaultHomePage);
		//}
		
		//self.common.disableElements( $("#myModalBtn"));
	};
	//==== 접근 권한 체크 } ====
	
	//==== 초기화 설정 { ====
	var initCondition = function(){
		// 초기 화면 조건 구성
		// 순서 조심! startdt enddt 설정 후 서버에서 부서리스트를 설정 후 스케줄데이터를 호출해야함
		//0.데이터 초기화
		$("#txtDoctorInfoDoctorNm").text("");
		$("#txtDoctorInfoSpeciality").text("");
		$("#txtDoctorInfoDoctorTel").text("");
		
		$("#sltOutpatientschDept").empty();
		$("#divOutpatientschResultRows").empty();
		//1.기간설정
		initStartEndDate();
		//2.주 일자 처리
		initWeekDate();
		
		//3.선택 부서 처리
		initSelDept();
	};
	
	var initStartEndDate = function(){
		varSelDate = new Date();
			
		//일요일이면 차주 가져오기
		//다른 요일이면 해당 요일 처리
		varSelDate.setDate(varSelDate.getDate() - varSelDate.getDay() + 1);
		$("#txtOutpatientschStartYear").text( moment(varSelDate).format("YYYY") );
		$("#txtOutpatientschStartMonth").text( moment(varSelDate).format("MM") );
		$("#txtOutpatientschStartDay").text( moment(varSelDate).format("DD") );
		varSelDate.setDate(varSelDate.getDate() + 5);
		$("#txtOutpatientschEndYear").text( moment(varSelDate).format("YYYY") );
		$("#txtOutpatientschEndMonth").text( moment(varSelDate).format("MM") );
		$("#txtOutpatientschEndDay").text( moment(varSelDate).format("DD") );
		varSelDate.setDate(varSelDate.getDate() - 5);
		
		//console.log("처리일자 : " + moment(varSelDate).format("YYYY-MM-DD"));
	};
	
	var initSelDept = function(){		
		//search deptlist
		var param = {
				userId: gLoginUserId,
				jobCls: localStorage.selectedJobKindCd
				};
		self.schedule.getShcDeptList(param, processSearchShcDeptList);
	};
	
	var processSearchShcDeptList = function(lists){
		$("#sltOutpatientschDept").empty();
		var strDisplayTemp = "";
		strDisplayTemp = "<option value=\"\">부서</option>";
		if(lists != undefined){
			for(var i=0; i<lists.length; i++){
				strDisplayTemp += "<option value=\""+ lists[i].deptCd +"\">"+ lists[i].deptNm +"</option>";
			}
		}
		$("#sltOutpatientschDept").append(strDisplayTemp);
		$("#sltOutpatientschDept").val(localStorage.selectedDeptCd);
		
		if($("#sltOutpatientschDept").val()==null){
			$("#sltOutpatientschDept").val($("#sltOutpatientschDept option:first").val());
		};
		
		//기본 정보 셋팅 후 호출
		searchWorkSch();
	};
	//==== 초기화 설정 } ====
	
	//==== 이벤트 설정 { ====
	var addEvent = function(){
		eventRowClick();
		
		eventConditionClick();
	};
	
	var eventConditionClick = function(){
		//부서변경 이벤트
		$("#sltOutpatientschDept").change(function(){
			searchWorkSch();
		});
		
		// 이전 주 버튼클릭
		$("#btnOutpatientschBeforeWeek").off("click"); // 기존 이벤트 해제
		$("#btnOutpatientschBeforeWeek").on("click", function(e){
			
			varSelDate.setDate(varSelDate.getDate() - 7);
			$("#txtOutpatientschStartYear").text( moment(varSelDate).format("YYYY") );
			$("#txtOutpatientschStartMonth").text( moment(varSelDate).format("MM") );
			$("#txtOutpatientschStartDay").text( moment(varSelDate).format("DD") );
			varSelDate.setDate(varSelDate.getDate() + 5);
			$("#txtOutpatientschEndYear").text( moment(varSelDate).format("YYYY") );
			$("#txtOutpatientschEndMonth").text( moment(varSelDate).format("MM") );
			$("#txtOutpatientschEndDay").text( moment(varSelDate).format("DD") );
			varSelDate.setDate(varSelDate.getDate() - 5);
			
			initWeekDate();
			searchWorkSch();
		});
		
		// 다음 주 버튼클릭
		$("#btnOutpatientschNextWeek").off("click"); // 기존 이벤트 해제
		$("#btnOutpatientschNextWeek").on("click", function(e){
						
			varSelDate.setDate(varSelDate.getDate() + 7);
			$("#txtOutpatientschStartYear").text( moment(varSelDate).format("YYYY") );
			$("#txtOutpatientschStartMonth").text( moment(varSelDate).format("MM") );
			$("#txtOutpatientschStartDay").text( moment(varSelDate).format("DD") );
			varSelDate.setDate(varSelDate.getDate() + 5);
			$("#txtOutpatientschEndYear").text( moment(varSelDate).format("YYYY") );
			$("#txtOutpatientschEndMonth").text( moment(varSelDate).format("MM") );
			$("#txtOutpatientschEndDay").text( moment(varSelDate).format("DD") );
			varSelDate.setDate(varSelDate.getDate() - 5);
			
			initWeekDate();
			searchWorkSch();
		});
		
		//전화걸기
		$("#btnDoctorInfoDoctorTelCall").unbind();
		$("#btnDoctorInfoDoctorTelCall").on("click", function(e){
			if($("#txtDoctorInfoDoctorTel").text()==""){
				self.alert("해당 의사의 전화번호가 존재하지 않습니다.");
				return;
			};
			location.href = "tel:"+$("#txtDoctorInfoDoctorTel").text();
		});
		
		//조회 클릭
		$("#btnOutpatientschSearch").unbind();
		$("#btnOutpatientschSearch").on("click", function(e){
			searchWorkSch();
		});
		
		$(window).unbind();
		$(window).resize(function() {
			//p 사이즈 처리
			var pHeightSize = ($("#sltOutpatientschDept").height() * 0.6);
			var pWidthSize = ($("#sltOutpatientschDept").width() * 0.15);
			$(".schptag").width(pWidthSize);
			$(".schptag").height(pHeightSize);
		});
	};
	
	var initWeekDate = function(){
		var tempSelDate = new Date(varSelDate);
		
		$("#txtSchMonDate").text(moment(tempSelDate).format("DD"));
		tempSelDate.setDate(tempSelDate.getDate() + 1);
		$("#txtSchTueDate").text(moment(tempSelDate).format("DD"));
		tempSelDate.setDate(tempSelDate.getDate() + 1);
		$("#txtSchWedDate").text(moment(tempSelDate).format("DD"));
		tempSelDate.setDate(tempSelDate.getDate() + 1);
		$("#txtSchThuDate").text(moment(tempSelDate).format("DD"));
		tempSelDate.setDate(tempSelDate.getDate() + 1);
		$("#txtSchFriDate").text(moment(tempSelDate).format("DD"));
		tempSelDate.setDate(tempSelDate.getDate() + 1);
		$("#txtSchSatDate").text(moment(tempSelDate).format("DD"));
	};
	
	var eventRowClick = function(){
		// 스케줄 선택 이벤트 처리
		$(".duty-schedule .dutyDoctorId").off("click"); // 기존 이벤트 해제
		$(".duty-schedule .dutyDoctorId").on("click", function(e){
			var doctorId = e.currentTarget.attributes.doctorId.value;
			//console.log("click : " + doctorId);
						
			var param = {
					userId:gLoginUserId,
					doctorId: doctorId
					};
			self.schedule.getDoctorInfo(param, processSearchDoctorInfo);
			// 환자 정보 화면 띄우기
			//$("#modalDoctorInfo").modal("show");
			//mplusModalDoctorinfo.init(param);
		});
	};
	
	var processSearchDoctorInfo = function(lists){
		//console.log("lists : " + lists.length);
		if(lists !== undefined && lists != null && lists.length != 0 && lists[0].doctorId != undefined && lists[0].doctorId != null && lists[0].doctorId != ""){
			/*
			var varDoctorInfo = "주치의 : "  + lists[0].doctorNm +"<br/>"
							  + "전문분야 : "+ lists[0].speciality+"<br/>"
			  				  + "전화번호 : "+ lists[0].doctorTel;
			$("#mplusAlertDoctorInfoBody").append(varDoctorInfo);
			*/
			if(lists[0].doctorNm != "" && lists[0].doctorNm != null && lists[0].doctorNm != undefined) {
				$("#txtDoctorInfoDoctorNm").text(lists[0].doctorNm);
			}else{
				$("#txtDoctorInfoDoctorNm").text("");
			}

			if(lists[0].speciality != "" && lists[0].speciality != null && lists[0].speciality != undefined) {
				$("#txtDoctorInfoSpeciality").text(lists[0].speciality);
			}else{
				$("#txtDoctorInfoSpeciality").text("");
			}

			if(lists[0].doctorTel != ""  && lists[0].doctorTel != null && lists[0].doctorTel != undefined){
				$("#txtDoctorInfoDoctorTel").text(lists[0].doctorTel);
				$("#btnDoctorInfoDoctorTelCall").css('display', 'inline-block');
			}else{
				$("#txtDoctorInfoDoctorTel").text("");
				$("#btnDoctorInfoDoctorTelCall").css('display', 'none');
			}
				
			$("#mplusAlertDoctorInfo").modal("show");
		}else{
			self.alert("해당 의사의 정보가 없습니다.");
		}
	};
	//==== 이벤트 설정 } ====
	
	//==== 스케줄 정보 조회 처리 { ====
	// 스케줄 정보 조회
	var searchWorkSch = function(){
		var tempSelDate = new Date(varSelDate);
		tempSelDate.setDate(tempSelDate.getDate() + 5);
		//console.log("searchWorkSch varSelDate : " + moment(varSelDate).format("YYYY-MM-DD") + " / tempSelDate : " + moment(tempSelDate).format("YYYY-MM-DD"));
		var param = {				
				userId: gLoginUserId,
				startDt: moment(varSelDate).format("YYYYMMDD"),
				endDt: moment(tempSelDate).format("YYYYMMDD"),
				selectedDeptCd: $("#sltOutpatientschDept").val()
				};
		self.schedule.getWorkSch(param, processSearchWorkSch);
	};
	
	// 스케줄 정보 조회 결과 처리
	var processSearchWorkSch = function(lists){
		// 1. 스케줄 조회 결과 리스트를 varResultLists로 복사
		varResultLists = lists;	
		// 2. 스케줄 검색 결과 리스트를 재정리 : 아이디순서별
		//20190527 dkchoi75 상계백병원 앱 자체 정렬 않되게 요청
//		self.common.sortArrayObject( varResultLists, "doctorId", true);
		// 3. 스케줄 검색 결과를 화면에 disaplay
		drawWorkSchList();
	};
	
	// 환자 정보 화면에 그리기
	var drawWorkSchList = function(){
		//1.아이디로 정렬 된 list 같은 아이디 위치 체크
		//2.해당 위치까지 for은 돌려 각 일별 근무일정 arry에 담기
		//3.출력하기
		
		var lists = varResultLists;
		var strDisplayTemp = "";
		$("#divOutpatientschResultRows").empty();
		
		//월 화 수 목 금 토 일 변수
		var scheduleList = ["","","","","","",""];
		
		//CSS Style List
		var scheduleClassList = ["D-type","N-type","ICU"];
		//CSS 변수
		var varCSSTemp = 0;
		//p 사이즈 처리
		
		
		var pHeightSize = ($("#sltOutpatientschDept").height() * 0.6);
		var pWidthSize = ($("#sltOutpatientschDept").width() * 0.15);
		
		for( var i = 0; i < lists.length; ){
			
			//초기화
			scheduleList = [["","","","","","",""],["","","","","","",""]];
			var varDocId = lists[i].doctorId;
			var inputEndCnt = 0;
			var startCnt = i;
			
			//의사 동일 ID 위치 처리
			for( ; i < lists.length ; i++){
				if(varDocId != lists[i].doctorId){
					varDocId = lists[i].doctorId;
					
					inputEndCnt = i;
					break;
				}
				inputEndCnt = i;
			}
			
			//마지막 list까지 확인했을 경우 inputEndCnt +1처리 위의 for에서 처리 제한
			if(i == lists.length) inputEndCnt += 1;
			
			for(var inputCnt = startCnt ;  inputCnt < inputEndCnt ; inputCnt++){
				//console.log("cnt inputCnt : " + inputCnt + " lists[inputCnt].dayCd : " + lists[inputCnt].dayCd + " lists[inputCnt].workingInfo : " + lists[inputCnt].workingInfo + " userid : " + lists[inputCnt].doctorId);
				//null값 처리
				
				if(lists[inputCnt].workingInfo == null){
					lists[inputCnt].workingInfo = "&nbsp";
				}
				
				if(lists[inputCnt].dayCd == "MON"){
					scheduleList[0][0] = lists[inputCnt].workingInfo;
					scheduleList[1][0] = drawWorkSchListColor(lists[inputCnt].workingInfo);
				} else if (lists[inputCnt].dayCd == "TUE"){
					scheduleList[0][1] = lists[inputCnt].workingInfo;
					scheduleList[1][1] = drawWorkSchListColor(lists[inputCnt].workingInfo);
				} else if (lists[inputCnt].dayCd == "WED"){
					scheduleList[0][2] = lists[inputCnt].workingInfo;
					scheduleList[1][2] = drawWorkSchListColor(lists[inputCnt].workingInfo);
				} else if (lists[inputCnt].dayCd == "THU"){
					scheduleList[0][3] = lists[inputCnt].workingInfo;
					scheduleList[1][3] = drawWorkSchListColor(lists[inputCnt].workingInfo);
				} else if (lists[inputCnt].dayCd == "FRI"){
					scheduleList[0][4] = lists[inputCnt].workingInfo;
					scheduleList[1][4] = drawWorkSchListColor(lists[inputCnt].workingInfo);
				} else if (lists[inputCnt].dayCd == "SAT"){
					scheduleList[0][5] = lists[inputCnt].workingInfo;
					scheduleList[1][5] = drawWorkSchListColor(lists[inputCnt].workingInfo);
				} else if (lists[inputCnt].dayCd == "SUN"){
					scheduleList[0][6] = lists[inputCnt].workingInfo;
					scheduleList[1][6] = drawWorkSchListColor(lists[inputCnt].workingInfo);
				}
				
			}
			
			strDisplayTemp += "<div class=\"duty-person \">" 
				+ "<div class=\"row\">"
				+ "	<div class=\"col-sm-2 col-xs-2 dutyDoctorId\" doctorId=\"" + lists[startCnt].doctorId + "\" style=\"margin-top: 8px;\">" + lists[startCnt].doctorNm + "</div>"
				+ "	<div class=\"col-sm-2 col-xs-2 "+scheduleList[1][0]+"\">"
				+ "	  <p class=\"schptag\">"+scheduleList[0][0]+"</p>"
				+ "	 </div>"
				+ "	<div class=\"col-sm-2 col-xs-2 "+scheduleList[1][1]+"\">"
				+ "	   <p class=\"schptag\">"+scheduleList[0][1]+"</p>"
				+ "	</div>"
				+ "	<div class=\"col-sm-2 col-xs-2 "+scheduleList[1][2]+"\">"
				+ "	    <p class=\"schptag\">"+scheduleList[0][2]+"</p>"
				+ "	</div>"
				+ "	<div class=\"col-sm-2 col-xs-2 "+scheduleList[1][3]+"\">"
				+ "	     <p class=\"schptag\">"+scheduleList[0][3]+"</p>"
				+ "	</div>"
				+ "	<div class=\"col-sm-2 col-xs-2 "+scheduleList[1][4]+"\">"
				+ "	     <p class=\"schptag\">"+scheduleList[0][4]+"</p>"
				+ "	</div>"
				+ "	<div class=\"col-sm-2 col-xs-2 "+scheduleList[1][5]+"\">"
				+ "	      <p class=\"schptag\">"+scheduleList[0][5]+"</p>"
				+ "	</div>"
				+ "	</div>"
				+ "</div>"
				;
			varCSSTemp++;
		}
	
		$("#divOutpatientschResultRows").append(strDisplayTemp);	// element 추가
		$(".schptag").width(pWidthSize);
		$(".schptag").height(pHeightSize);
		eventRowClick();
	};
	
	//외래진료일정 색상변경(건대용)
	var drawWorkSchListColor = function(colorData){
		var returnColorData = "";
		
		if(colorData == "오전"){//#c2d4de
			returnColorData = "pRed";
		}else if(colorData == "오후"){//#99abb5
			returnColorData = "pGreen";
		}else if(colorData == "종일"){//#e9c77b
			returnColorData = "pBlue";
		}else if(colorData == "&nbsp"){//회색
			returnColorData = "pGrey";
		}else{//#e2b49a
			returnColorData = "pYellow";
		}
		return returnColorData;
	};
	
	//==== 환자 정보 조회 처리 } ====

};