"use strict";
/**
 * mplus_medical_OnDutyWeekSch
 */
var mplus_schedule_doctorworksch = 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("");
		 
		$("#sltOnDutyWeekSchDept").empty();
		$("#divOnDutyWeekSchResultRows").empty();
		//1.기간설정_test
		initStartEndDate();
		
		//2.주 일자 처리
		initWeekDate();
		
		//3.선택 부서 처리
		initSelDept();
	};
	
	var initStartEndDate = function(){
		varSelDate = new Date();
			
		//일요일이면 차주 가져오기
		//다른 요일이면 해당 요일 처리
		varSelDate.setDate(varSelDate.getDate() - varSelDate.getDay());
		$("#txtOnDutyWeekSchStartYear").text( moment(varSelDate).format("YYYY") );
		$("#txtOnDutyWeekSchStartMonth").text( moment(varSelDate).format("MM") );
		$("#txtOnDutyWeekSchStartDay").text( moment(varSelDate).format("DD") );
		varSelDate.setDate(varSelDate.getDate() + 6);
		$("#txtOnDutyWeekSchEndYear").text( moment(varSelDate).format("YYYY") );
		$("#txtOnDutyWeekSchEndMonth").text( moment(varSelDate).format("MM") );
		$("#txtOnDutyWeekSchEndDay").text( moment(varSelDate).format("DD") );
		varSelDate.setDate(varSelDate.getDate() - 6);
		
		//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){
		$("#sltOnDutyWeekSchDept").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>";
			}
		}
		$("#sltOnDutyWeekSchDept").append(strDisplayTemp);
		$("#sltOnDutyWeekSchDept").val(localStorage.selectedDeptCd);
		
		if($("#sltOnDutyWeekSchDept").val()==null){
			$("#sltOnDutyWeekSchDept").val($("#sltOnDutyWeekSchDept option:first").val());
		};
		
		//기본 정보 셋팅 후 호출
		searchWorkSch();
	};
	//==== 초기화 설정 } ====
	
	//==== 이벤트 설정 { ====
	var addEvent = function(){
		eventRowClick();
		
		eventConditionClick();
	};
	
	var eventConditionClick = function(){
		//부서변경 이벤트
		$("#sltOnDutyWeekSchDept").unbind();
		$("#sltOnDutyWeekSchDept").change(function(){
			searchWorkSch();
		});
		
		// 이전 주 버튼클릭
		$("#btnOnDutyWeekSchBeforeWeek").off("click"); // 기존 이벤트 해제
		$("#btnOnDutyWeekSchBeforeWeek").on("click", function(e){
			
			varSelDate.setDate(varSelDate.getDate() - 7);
			$("#txtOnDutyWeekSchStartYear").text( moment(varSelDate).format("YYYY") );
			$("#txtOnDutyWeekSchStartMonth").text( moment(varSelDate).format("MM") );
			$("#txtOnDutyWeekSchStartDay").text( moment(varSelDate).format("DD") );
			varSelDate.setDate(varSelDate.getDate() + 6);
			$("#txtOnDutyWeekSchEndYear").text( moment(varSelDate).format("YYYY") );
			$("#txtOnDutyWeekSchEndMonth").text( moment(varSelDate).format("MM") );
			$("#txtOnDutyWeekSchEndDay").text( moment(varSelDate).format("DD") );
			varSelDate.setDate(varSelDate.getDate() - 6);
			
			initWeekDate();
			searchWorkSch();
		});
		
		// 다음 주 버튼클릭
		$("#btnOnDutyWeekSchNextWeek").off("click"); // 기존 이벤트 해제
		$("#btnOnDutyWeekSchNextWeek").on("click", function(e){
						
			varSelDate.setDate(varSelDate.getDate() + 7);
			$("#txtOnDutyWeekSchStartYear").text( moment(varSelDate).format("YYYY") );
			$("#txtOnDutyWeekSchStartMonth").text( moment(varSelDate).format("MM") );
			$("#txtOnDutyWeekSchStartDay").text( moment(varSelDate).format("DD") );
			varSelDate.setDate(varSelDate.getDate() + 6);
			$("#txtOnDutyWeekSchEndYear").text( moment(varSelDate).format("YYYY") );
			$("#txtOnDutyWeekSchEndMonth").text( moment(varSelDate).format("MM") );
			$("#txtOnDutyWeekSchEndDay").text( moment(varSelDate).format("DD") );
			varSelDate.setDate(varSelDate.getDate() - 6);
			
			initWeekDate();
			searchWorkSch();
		});
		
		//전화걸기
		$("#btnDoctorInfoDoctorTelCall").unbind();
		$("#btnDoctorInfoDoctorTelCall").on("click", function(e){
			if($("#txtDoctorInfoDoctorTel").text()==""){
				self.alert("해당 의사의 전화번호가 존재하지 않습니다.");
				return;
			};
			location.href = "tel:"+$("#txtDoctorInfoDoctorTel").text();
		});
		
		//조회 클릭
		$("#btnOnDutyWeekSchSearch").unbind();
		$("#btnOnDutyWeekSchSearch").on("click", function(e){
			searchWorkSch();
		});
		
		$(window).unbind();
		$(window).resize(function() {
			console.log("resize call!");
			//p 사이즈 처리
			//화면의 고정되는 input으로 처리 .col-xs-2로 처리하면 변함
			var pHeightSize = ($("#inputOnDutyWeekSchSearchTxt").height() * 0.6);
			var pWidthSize = ($("#inputOnDutyWeekSchSearchTxt").width() * 0.25);
			
			console.log("pWidthSize : " + pWidthSize);
			

			$(".schptag").width(pWidthSize);
			$(".schptag").height(pHeightSize);
			
			$(".schkeytag").width(pWidthSize);
		});
	};
	
	var initWeekDate = function(){
		var tempSelDate = new Date(varSelDate);
		
		$("#txtSchSunDate").text(moment(tempSelDate).format("DD"));
		tempSelDate.setDate(tempSelDate.getDate() + 1);
		$("#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(){
		// 스케줄 선택 이벤트 처리
		$(".schptag").off("click"); // 기존 이벤트 해제
		$(".schptag").on("click", function(e){
			var doctorId = e.currentTarget.attributes.doctorId.value;
			var doctorNm = e.currentTarget.attributes.doctorNm.value;
			//console.log("click : " + doctorId);
			var param = {
					doctorId : doctorId,
					doctorNm : doctorNm,
					searchMonth : moment(varSelDate).format("YYYYMM")
			};
			
			mplusModalDoctorworkschdetail.init(param);
			$("#modalDoctorWorkSchDetail").modal("show");
			
			return;
			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){
			/*
			var varDoctorInfo = "주치의 : "  + lists[0].doctorNm +"<br/>"
							  + "전문분야 : "+ lists[0].speciality+"<br/>"
			  				  + "전화번호 : "+ lists[0].doctorTel;
			$("#mplusAlertDoctorInfoBody").append(varDoctorInfo);
			*/
			$("#txtDoctorInfoDoctorNm").text(lists[0].doctorNm);
			$("#txtDoctorInfoSpeciality").text(lists[0].speciality);
			if(lists[0].doctorTel != ""){
				$("#txtDoctorInfoDoctorTel").text(lists[0].doctorTel);
				$("#btnDoctorInfoDoctorTelCall").css('display', 'inline-block');
			}else{
				$("#btnDoctorInfoDoctorTelCall").css('display', 'none');
			}
				
			//$("#mplusAlertDoctorInfo").modal("show");
		}else{
			self.alert("해당 의사의 정보가 없습니다.");
		}
	};
	//==== 이벤트 설정 } ====
	
	//==== 스케줄 정보 조회 처리 { ====
	// 스케줄 정보 조회
	var searchWorkSch = function(){
		var tempSelDate = new Date(varSelDate);
		tempSelDate.setDate(tempSelDate.getDate() + 6);
		//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"),
				jobCls:"D",//의사
				workingTy:"%",//진료구분
				selectedDeptCd: $("#sltOnDutyWeekSchDept").val(),
				searchTxt:$("#inputOnDutyWeekSchSearchTxt").val()
			};
		self.schedule.getOnDutyWeekSch(param, processSearchWorkSch);
	};
	
	// 스케줄 정보 조회 결과 처리
	var processSearchWorkSch = function(lists){
		// 1. 스케줄 조회 결과 리스트를 varResultLists로 복사
		varResultLists = lists;	
		// 2. 스케줄 검색 결과 리스트를 재정리 : 아이디순서별
		//self.common.JSONGroupBy(varResultLists, "dutyTxt");
		// 3. 스케줄 검색 결과를 화면에 disaplay
		drawWorkSchList();
	};
	
	// 환자 정보 화면에 그리기
	var drawWorkSchList = function(){
		//1.dutyTxt로 정렬 된 list 출력
		//2.CSS로 인한 p size 처리
		//3.key로 리스트 출력
		//4.row 정리
		
		var lists = self.common.JSONGroupBy(varResultLists, "dutyTxt");
		//console.log(JSON.stringify(lists));
		
		var strDisplayTemp = "";
		$("#divOnDutyWeekSchResultRows").empty();
		
		//일 월 화 수 목 금 토 일 변수
		var scheduleList = ["","","","","","",""];
		
		//CSS Style List
		var scheduleClassList = ["D-type","N-type","ICU"];
		
		//CSS 변수
		var varCSSTemp = 0;
		//p 사이즈 처리
		var pHeightSize = ($("#inputOnDutyWeekSchSearchTxt").height() * 0.6);
		var pWidthSize = ($("#inputOnDutyWeekSchSearchTxt").width() * 0.25);
		console.log("pWidthSize : " + pWidthSize);

		for(var key in lists){
			
			//초기화
			scheduleList = ["","","","","","",""];
			var tempLists = lists[key];
			
			//console.log(JSON.stringify(tempLists[0].dayCd)); }
			
			
			for(var inputCnt = 0 ;  inputCnt < tempLists.length ; inputCnt++){
				//console.log("cnt inputCnt : " + inputCnt + " lists[inputCnt].dayCd : " + lists[inputCnt].dayCd + " lists[inputCnt].workingInfo : " + lists[inputCnt].workingInfo + " userid : " + lists[inputCnt].doctorId);
				
				var TempPTage = "";
				
				if(tempLists[inputCnt].userId == gLoginUserId){
					TempPTage = "<p class=\"schptag \" style=\"background:#99abb5; display:inline-block; padding-top:8px;\" doctorNm=\"" + tempLists[inputCnt].userNm + "\" doctorId=\"" + tempLists[inputCnt].userId + "\">"+tempLists[inputCnt].userNm+"</p>";
				}else{
					TempPTage = "<p class=\"schptag \" style=\"display:inline-block; padding-top:8px;\" doctorNm=\"" + tempLists[inputCnt].userNm + "\" doctorId=\"" + tempLists[inputCnt].userId + "\">"+tempLists[inputCnt].userNm+"</p>";
				}
				
				if(tempLists[inputCnt].dayCd == "SUN"){
					scheduleList[0] += TempPTage;
				} else if (tempLists[inputCnt].dayCd == "MON"){
					scheduleList[1] += TempPTage;
				} else if (tempLists[inputCnt].dayCd == "TUE"){
					scheduleList[2] += TempPTage;
				} else if (tempLists[inputCnt].dayCd == "WED"){
					scheduleList[3] += TempPTage;
				} else if (tempLists[inputCnt].dayCd == "THU"){
					scheduleList[4] += TempPTage;
				} else if (tempLists[inputCnt].dayCd == "FRI"){
					scheduleList[5] += TempPTage;
				} else if (tempLists[inputCnt].dayCd == "SAT"){
					scheduleList[6] += TempPTage;
				}
				
			}
			var TempKey = key.replace(/\//g , "/<br/>");
			//console.log("TempKey : " + TempKey);
			strDisplayTemp += "<div class=\"duty-person\">" 
				+ "<div class=\"row\">"
				+ "	<div class=\"col-sm-2 col-xs-2 \" style=\"margin-top: 8px;\"><sapn class=\" span" + scheduleClassList[(varCSSTemp % 3)] + " \" style=\"display: inline-block; width:35px; word-wrap: break-word; line-height: normal;\">" + TempKey + "</span></div>"
				+ "	<div class=\"col-sm-2 col-xs-2 "+scheduleClassList[(varCSSTemp % 3)]+"\">"
				+ scheduleList[0]
				+ "	 </div>"
				+ "	<div class=\"col-sm-2 col-xs-2 "+scheduleClassList[(varCSSTemp % 3)]+"\">"
				+ scheduleList[1]
				+ "	</div>"
				+ "	<div class=\"col-sm-2 col-xs-2 "+scheduleClassList[(varCSSTemp % 3)]+"\">"
				+ scheduleList[2]
				+ "	</div>"
				+ "	<div class=\"col-sm-2 col-xs-2 "+scheduleClassList[(varCSSTemp % 3)]+"\">"
				+ scheduleList[3]
				+ "	</div>"
				+ "	<div class=\"col-sm-2 col-xs-2 "+scheduleClassList[(varCSSTemp % 3)]+"\">"
				+ scheduleList[4]
				+ "	</div>"
				+ "	<div class=\"col-sm-2 col-xs-2 "+scheduleClassList[(varCSSTemp % 3)]+"\">"
				+ scheduleList[5]
				+ "	</div>"
				+ "	<div class=\"col-sm-2 col-xs-2 "+scheduleClassList[(varCSSTemp % 3)]+"\">"
				+ scheduleList[6]
				+ "	</div>"
				+ "	</div>"
				+ "</div>"
				;
			varCSSTemp++;
		}
	
		$("#divOnDutyWeekSchResultRows").append(strDisplayTemp);	// element 추가
		$(".schptag").width(pWidthSize);
		$(".schptag").height(pHeightSize);
		
		$(".schkeytag").width(pWidthSize);
		eventRowClick();
		
	};
	
	//==== 환자 정보 조회 처리 } ====

};