// ////////////////////////////////////////////////////
// 1. 왼쪽 데이터
// ////////////////////////////////////////////////////
//가운데 예약 현황 스크롤위치
let xScrollPosition = '';
let holidayListMap = '';
/****************************************************************************
* 병원휴일
****************************************************************************/
function fn_searchHospitalHoliday(){
	let formData = new FormData();
	formData.append("menuClass", menuClass);

	$.ajax({
		url: encodeURI('/webreserve/selectHospitalHoliday.do'),
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		async: true,
		success: function(data){
			if('0'==data.msgCode){
				holidayListMap = data.rows;
				fn_setCalendar(holidayListMap);
			}
			else{
				modalEvent.danger("조회 오류", data.msgDesc);
			}
		},
		error : function(xhr, status, error) {
			modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
		},
		beforeSend:function(){
		},
		complete:function(){

		}
	});
}
/****************************************************************************
* 금일 공지사항
****************************************************************************/
function fn_selectListTodayNotice(){
	let reserveSearchDate = $("#date_reserveSearchDate").data().date;
	
	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("searchDate", reserveSearchDate);

	$.ajax({
		url: encodeURI('/webnotice/selectListTodayNotice.do'),
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		async: true,
		success: function(data){
			if('0'==data.msgCode){
				let listHTML = '';
				
				if(0<data.rows.length){
					for(let i=0 ; i < data.rows.length ; i++){
						let title   = data.rows[i].title;
						let content = data.rows[i].content;
						
						listHTML += '<span class="title">'+title+'</span><br/>';
						listHTML += '<span class="content">'+content.replace(/(?:\r\n|\r|\n)/g, '<br />')+'</span><br/><br/>';
					}
				}
				else{
					listHTML += '<span>금일 공지사항 정보가 없습니다.</span>';
				}
				
				$("#noticeBox").html(listHTML);
			}
			else{
				modalEvent.danger("조회 오류", data.msgDesc);
			}
		},
		error : function(xhr, status, error) {
			modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
		},
		beforeSend:function(){
		},
		complete:function(){
			
		}
	});
}


/****************************************************************************
* 금일 근무현황 조회
****************************************************************************/
function fn_selectListTodayAttendance(){
	let reserveSearchDate = $("#date_reserveSearchDate").data().date;
	
	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("searchDate", reserveSearchDate);

	$.ajax({
		url: encodeURI('/webattendance/selectListTodayAttendance.do'),
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		async: true,
		success: function(data){
			if('0'==data.msgCode){
				let listHTML = '';
				
				if(0<data.rows.length){
					for(let i=0 ; i < data.rows.length ; i++){
						let groupName   = data.rows[i].groupName;
						let memberName  = data.rows[i].memberName;
						
						listHTML += '<span class="title">'+groupName+'</span>&#58;';
						listHTML += '<span class="content">'+memberName+'</span><br/><br/>';
					}
				}
				else{
					listHTML += '<span>금일 근무현황 정보가 없습니다.</span>';
				}
				
				$("#attendanceBox").html(listHTML);
			}
			else{
				modalEvent.danger("조회 오류", data.msgDesc);
			}
		},
		error : function(xhr, status, error) {
			modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
		},
		beforeSend:function(){
		},
		complete:function(){
			
		}
	});
}

// ////////////////////////////////////////////////////
// 2. 가운데 데이터
// ////////////////////////////////////////////////////

/****************************************************************************
* 예약현황 상태별 건수 조회 (count)
****************************************************************************/
function fn_selectTotalReserveStatusCount(){
	let reserveSearchDate = $("#date_reserveSearchDate").data().date;
	
	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("searchDate", reserveSearchDate);

	$.ajax({
		url: encodeURI('/webreserve/selectTotalReserveStatusCount.do'),
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		async: true,
		success: function(data){
			if('0'==data.msgCode){
				$(".tStatusCount").text(data.rows[0].tTotalCount);
				$(".rStatusCount").text(data.rows[0].rTotalCount);
				$(".pStatusCount").text(data.rows[0].pTotalCount);
				$(".gStatusCount").text(data.rows[0].gTotalCount);
				$(".tnStatusCount").text(data.rows[0].tnTotalCount);

				let countHTML = '';
				if(0 < data.treatmentCountRows.length){
					countHTML += '(';
					for(let i = 0; i < data.treatmentCountRows.length; i++){
						let treatmentName = data.treatmentCountRows[i].treatmentName;
						let totalCount    = data.treatmentCountRows[i].totalCount;
						
						countHTML += '<span>'+treatmentName+'  '+totalCount+'</span>';
					}
					countHTML += ')';
				}
				$(".treartmentCountCount").html(countHTML);

				countHTML = '';
				if(0 < data.treatmentCountRows2.length){
					countHTML += '(';
					for(let i = 0; i < data.treatmentCountRows2.length; i++){
						let treatmentName = data.treatmentCountRows2[i].treatmentName;
						let totalCount    = data.treatmentCountRows2[i].totalCount;

						countHTML += '<span>'+treatmentName+'  '+totalCount+'</span>';
					}
					countHTML += ')';
				}
				$(".treartmentCountCount2").html(countHTML);

				countHTML = '';
				if(0 < data.treatmentCountRows3.length){
					countHTML += '(';
					for(let i = 0; i < data.treatmentCountRows3.length; i++){
						let treatmentName = data.treatmentCountRows3[i].treatmentName;
						let totalCount    = data.treatmentCountRows3[i].totalCount;

						countHTML += '<span>'+treatmentName+'  '+totalCount+'</span>';
					}
					countHTML += ')';
				}
				$(".treartmentCountCount3").html(countHTML);
			}
			else{
				modalEvent.danger("조회 오류", data.msgDesc);
			}
		},
		error : function(xhr, status, error) {
			modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
		},
		beforeSend:function(){
		},
		complete:function(){
			
		}
	});
}

/****************************************************************************
* 진료 콤보데이타 설정
****************************************************************************/
function fn_setTreatmentCombo(){

	let target = $('#sel_reserveTreatment');

	let comboData = fn_selectListTreatmentOption2();
	let comboHTML = '';
	for(let i = 0; i < comboData.length; i++){
		let muTreatmentId     = comboData[i].muTreatmentId;
		let treatmentName     = comboData[i].treatmentName;

		comboHTML += '<option value="'+muTreatmentId+'">'+treatmentName+'</option>';
	}

	target.html(comboHTML);
	target.selectpicker("refresh");

	target.change(function(){
		let value = $(this).val();

		if(0<value.length){
			// 진료시술 콤보 셋팅
			fn_setTreatmentProcedureCombo(value);
		}else{
			$('#sel_reserveTreatmentProcedure').empty();
			$('#sel_reserveTreatmentProcedure').selectpicker("refresh");
		}
	});
}


/****************************************************************************
* 시술 콤보데이타 설정
****************************************************************************/
function fn_setTreatmentProcedureCombo(param){

	let target = $('#sel_reserveTreatmentProcedure');

	let comboData = fn_selectListTreatmentProcedureOption(param);
	let comboHTML = '';
	for(let i = 0; i < comboData.length; i++){
		let muTreatmentProcedureId     = comboData[i].muTreatmentProcedureId;
		let treatmentProcedureName     = comboData[i].treatmentProcedureName;

		comboHTML += '<option value="'+muTreatmentProcedureId+'">'+treatmentProcedureName+'</option>';
	}

	target.html(comboHTML);
	target.selectpicker("refresh");

	target.change(function(){
		let value = $(this).val();

		if(0<value.length){
			// 닥터/상담 콤보 셋팅
			fn_setReserveMemberCombo(value);
		}else{
			$('#sel_reserveMember').empty();
			$('#sel_reserveMember').selectpicker("refresh");
		}
	});
}

/****************************************************************************
* 닥터/상담 콤보데이타 설정
****************************************************************************/
function fn_setReserveMemberCombo(param){

	let target = $('#sel_reserveMember');

	let reserveSearchDate   = $("#date_reserveSearchDate").data().date;
	let comboData = fn_selectListReserveMemberOption(reserveSearchDate, param);
	let comboHTML = '';
	for(let i = 0; i < comboData.length; i++){
		let muMemberId = comboData[i].muMemberId;
		let memberName = comboData[i].memberName;
		let typeName   = comboData[i].typeName;

		comboHTML += '<option value="'+muMemberId+'">'+typeName+' '+memberName+'</option>';
	}
	target.html(comboHTML);
	target.selectpicker("refresh");
}

/****************************************************************************
* 방문 콤보데이타 설정
****************************************************************************/
function fn_setReserveVisitCombo(){

	let target = $('#sel_reserveReserveVisit');

	let comboHTML = '';
	comboHTML += '<option value="A">초진</option>';
	comboHTML += '<option value="B">재진</option>';
	target.html(comboHTML);
	target.selectpicker("refresh");


	/*// 대상
	const target = $("#reserveReserveVisit").siblings("ul.select_option_list");
	
	let comboHTML = '<li id="li_reserveVisitAll" class="option_list_item">방문 전체</li>';
	comboHTML += '	 <li id="li_A" class="option_list_item">초진</li>';
	comboHTML += '	 <li id="li_B" class="option_list_item">재진</li>';
	target.empty().html(comboHTML).trigger("create");
	
	// 콤보 이벤트
	target.find("li.option_list_item").click(function () {
		// 1. 선택값 셋팅
		let selectIdArr = $(this).prop("id").split('_');
		let selectId    = selectIdArr[1];
		let selectName  = $(this).text();

		if(selectId.match("All")){
			selectId = '';
		}
		
		$(this).parent().siblings("button").text(selectName);
		$(this).parent().siblings("input").val(selectId);
	});
	
	// 초기화
	target.find("li:eq(0)").click();*/
}


/****************************************************************************
* 상태 표시
* 예약:'T',예약취소:'TN', 접수:'R', 접수취소:'RN', 진료중:'G', 진료끝:'Y'
****************************************************************************/
function fn_reserveStatus(param){
	let status = param;
	
	let result = '';
	
	if("T"==status){
		result = '예약';
	}
	else if("TN"==status){
		result = '예약취소';
	}
	else if("R"==status){
		result = '접수';
	}
	else if("RN"==status){
		result = '접수취소';
	}
	else if("G"==status){
		result = '진료중';
	}
	else if("Y"==status){
		result = '진료완료';
	}
	
	return result;
}

/****************************************************************************
* 상태별 아이콘 처리
* 예약:'T',예약취소:'TN', 접수:'R', 접수취소:'RN', 진료중:'G', 진료끝:'Y'
****************************************************************************/
function fn_reserveStatusImg(param, param2){
	let status = param;
	let charYn = param2;
	
	let resultHTML = '';
	
	if("T"==status){
		resultHTML = '<span><img class="img_situation" src="/image/web/situation1.svg" alt=""></span>';
	}
	else if("TN"==status){
		resultHTML = '<span><img class="img_situation" src="/image/web/situation1.svg" alt=""></span>';
	}
	else if("R"==status){
		resultHTML = '<span><img class="img_situation" src="/image/web/situation2.svg" alt=""></span>';
	}
	else if("RN"==status){
		resultHTML = '<span><img class="img_situation" src="/image/web/situation2.svg" alt=""></span>';
	}
	else if("G"==status){
		resultHTML = '<span><img class="img_situation" src="/image/web/situation3.svg" alt=""></span>';
	}
	else if("Y"==status){
		resultHTML = '<span><img class="img_situation" src="/image/web/situation4.svg" alt=""></span>';
	}
	
	if("Y"==charYn){
		resultHTML += '<span class="text">'+fn_reserveStatus(status)+'</span>';
	}
	
	return resultHTML;
}

/****************************************************************************
* 예약현황 조회 리스트
****************************************************************************/
function fn_selectListReserve(){
	let reserveSearchDate      = $("#date_reserveSearchDate").data().date;
	let muTreatmentId          = $('#sel_reserveTreatment').val();
	let muTreatmentProcedureId = $('#sel_reserveTreatmentProcedure').val();
	let muMemberId             = $('#sel_reserveMember').val();
	let reserveReserveVisit    = $('#sel_reserveReserveVisit').val();

	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("searchDate", reserveSearchDate);
	formData.append("muTreatmentId", muTreatmentId);
	formData.append("muTreatmentProcedureId", muTreatmentProcedureId);
	formData.append("muMemberId", muMemberId);
	formData.append("reserveReserveVisit", reserveReserveVisit);

	$.ajax({
		url: encodeURI('/webreserve/selectListReserve.do'),
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		async: true,
		success: function(data){
			if('0'==data.msgCode){
				let openYn = data.openYn;
				let holidayYn = data.holidayYn;
				if("N" == holidayYn && "Y" == openYn){
					// 1. 시간 출력
					let listHTML = '';
					for(let i = 0; i < data.timeRows.length; i++){
						let resultDate = data.timeRows[i].resultDate;
						let resultTime = data.timeRows[i].resultTime;
						let liId = data.timeRows[i].resultTime.replace(/\:/g, '')
						
						listHTML += '<li id="li_'+liId+'">'+resultTime+'</li>';
					}
					$("#career .main_content .time").empty().html(listHTML).trigger("create");
					// 1. 닥터, 상담사 조회 HTML
					let memberListHTML = '<div class="time"></div>';
					// 2. 닥터, 상담사 인원만큼 예약열 추가 HTML
					let reserveListHTML = '';
					let appRowsNumber=0;

					if (!data.appReserveRows.every(obj => Object.keys(obj).length === 0)) {
						// 초기 앱 예약 관련 HTML 삽입
						memberListHTML += '<div class="diagnosis_user" style="width: 185px;"><p class="day">앱 예약</p></div>';
						reserveListHTML += '<div class="day_wrap app"></div>';

						// 각 key에 대해 데이터 길이를 확인
						Object.keys(data.appReserveRows).forEach(function(key) {
							let reserveData = data.appReserveRows[key];

							if ( Object.keys(reserveData).length >= 30) {
								// 30개 단위로 추가
								let timesToAdd = Math.floor( Object.keys(reserveData).length / 30);  // 30개 배수만큼 반복

								for (let i = 1; i <= timesToAdd; i++) {
									memberListHTML += '<div class="diagnosis_user" style="width: 185px;"><p class="day">앱 예약</p></div>';
									reserveListHTML += '<div class="day_wrap app"></div>';
								}
							}
						});
					}

					for (let j = 0; j < data.memberRows.length; j++) {
						// 1. 닥터, 상담사 조회 처리
						let muMemberId  = data.memberRows[j].muMemberId;
						let memberName  = data.memberRows[j].memberName;
						let muGroupId   = data.memberRows[j].muGroupId;
						let groupName   = data.memberRows[j].groupName;
						let muDutyId    = data.memberRows[j].muDutyId;
						let dutyName    = data.memberRows[j].dutyName;
						let type        = data.memberRows[j].type;
						let typeName    = data.memberRows[j].typeName;
						
						memberListHTML += '<div class="diagnosis_user">';
						memberListHTML += '	<p class="day">'+groupName + ' ' +typeName+' '+memberName+'</p>';
						memberListHTML += '</div>';
						
						
						// 2. 닥터, 상담사 인원만큼 예약열 추가 처리
						reserveListHTML += '<div class="day_wrap"></div>';
					}
					// 1. 닥터, 상담사 조회 처리
					$("#career .main_content .table_box .top_box .diagnosis_list").empty().html(memberListHTML).trigger("create");
					
					// 2. 닥터, 상담사 인원만큼 예약열 추가
					$("#career .main_content .table_box .bottom_box").empty().html(reserveListHTML).trigger("create");
					
					
					
					// 예약 현황
					for(let i = 0; i < data.timeRows.length; i++){
						let resultDate = data.timeRows[i].resultDate;
						let resultTime = data.timeRows[i].resultTime;

						let maxHeight = 0;
						let appReserveData = data.appReserveRows;
						let appListHTML = '';

						let totalItems = Object.keys(appReserveData).length;
						let itemsPerColumn = 30;
						let totalColumns = Math.ceil(totalItems / itemsPerColumn);
						let appColumns = $(".day_wrap.app").length;
						if(0 < appColumns) {
							if (0 < appReserveData.length) {

								for(let j=0; j<appReserveData.length; j++){
									// 30개 단위로 나눠서 각 컬럼에 추가
									if (j % itemsPerColumn === 0) {
										if (j > 0) {
											// 이전에 생성된 ul 닫기
											appListHTML += '</ul>';
											// 새로운 컬럼에 새로운 ul 시작
											 $("#career .main_content .table_box .bottom_box .day_wrap:eq(" + (Math.floor(j / itemsPerColumn)-1) + ")").append(appListHTML).trigger("create");
											 appListHTML = ''; // 새로운 HTML 시작
										}

										appListHTML = '<ul class="day_list ' + (2 < totalItems ? 'obesity_list' : '') + '">';
									}
									const reserveData = appReserveData[j];

									if(resultTime == reserveData.reserveTime){

										// 사용자 상태별 다르게 UI 처리
										let uiClassArr = '';

										// 초진일 경우 클래스 추가
										if ('N' == reserveData.visitYn) {
											uiClassArr += ' firstVisit';
										}
										// 사용자 주의사항 있을 경우 클래스 추가
										if (true == fn_emptyCheck(reserveData.detailUserEtc)) {
											uiClassArr += ' highlight';
										}
										// 앱 예약일 경우 클래스 추가
										if ('Y' == reserveData.reserveAppYn) {
											uiClassArr += ' appReserve';
										}

										// 앱 회원은 회원가입하기 때문에 주석
										/*if ('' == reserveData.userType && 'Y' == reserveData.userType2) {
											uiClassArr += ' new';
										}*/

										appListHTML += '<li class="' + uiClassArr + '">';
										appListHTML += '	<input type="hidden" name="muReserveId" value="' + reserveData.muReserveId + '">';
										appListHTML += '	<div class="user_list">';
										appListHTML += '		<div class="user">'
										appListHTML += '			<p class="user_name">' + reserveData.userName + '</p>'
										appListHTML += '			<div class="icon_box">'
										// 여기에 사진거부 사진 추가
										appListHTML += reserveData.refusePhotoYn=="Y" ? '<img class="fruit" src="/image/web/refuse_photo.png" alt="사진거부">' : '';
										// appListHTML += reserveData.userType ? '<img class="fruit" src="' + reserveData.userType + '" alt="고객">' : '';
										if (true == fn_emptyCheck(reserveData.etc))
											appListHTML += '			<img class="alarm" src="/image/web/alarm.svg" alt="예약메모">';
										// 사용자 주의사항 있을 경우 문구추가
										if (true == fn_emptyCheck(reserveData.userEtc)) {
											appListHTML += '			<img class="precaution" src="/image/web/alarm2.svg" alt="주의사항">';
										}
										appListHTML += '			</div>'
										appListHTML += '		</div>'
										appListHTML += '	</div>';

										appListHTML += '	<p class="type">';
										appListHTML += fn_reserveStatusImg(reserveData.status, 'N');
										appListHTML += reserveData.treatmentName + '-' + reserveData.treatmentProcedureName;
										appListHTML += '	</p>';
										appListHTML += '	<div class="dropdown">';
										appListHTML += '		<button type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">';
										appListHTML += '			<img src="/image/web/day_list_dropdown_icon.svg" alt="메뉴">';
										appListHTML += '		</button>';

										appListHTML += '		<ul class="dropdown-menu" aria-labelledby="dLabel">';
										appListHTML += '			<li onclick="fn_updateUserPopup(\''+reserveData.muUserId+'\');">';
										appListHTML += '				<p class="list"><img class="img_situation" src="/image/web/situation6.svg" alt="">신환등록</p>';
										appListHTML += '			</li>';
										appListHTML += '			<li onclick="fn_updateReservePopup(\'' + reserveData.muReserveId + '\');">';
										appListHTML += '				<p class="list">예약수정</p>';
										appListHTML += '			</li>';

										appListHTML += '			<li onclick="fn_updateReserveStatus(\'' + reserveData.muReserveId + '\',\'TN\');">';
										appListHTML += '				<p class="list red_list">예약취소</p>';
										appListHTML += '			</li>';

										appListHTML += '		</ul>';
										appListHTML += '	</div>';
										if (true == fn_emptyCheck(reserveData.etc)) {
											appListHTML += '<div class="memo_box">';
											appListHTML += '	<p class="memo_title">예약 메모</p>';

											appListHTML += '	<div>';
											appListHTML += '		<p class="yeyagmemo_title">' + reserveData.treatmentName + '</p>';
											appListHTML += '		<p class="yeyagmemo_content">' + reserveData.etc + '</p>';
											appListHTML += '	</div>';
											appListHTML += '</div>';
										}
										if (true == fn_emptyCheck(reserveData.userEtc)) {
											appListHTML += '<div class="precaution_box">';
											appListHTML += '	<p class="memo_title">주의사항</p>';
											appListHTML += '	<div>';
											appListHTML += '		<p class="yeyagmemo_title"></p>';
											appListHTML += '		<p class="yeyagmemo_content">' + reserveData.userEtc + '</p>';
											appListHTML += '	</div>';
											appListHTML += '</div>';
										}
										appListHTML += '</li>';
									}
								}
								appListHTML +='</ul>'
								const dayWrap = $("#career .main_content .table_box .bottom_box").find(".day_wrap:eq(" + (appColumns-1) + ")");
								dayWrap.append(appListHTML).trigger("create");
							} else {
								// 예약 정보 없을 경우
								appListHTML += '<ul class="day_list"></ul>';
								if(0 === totalColumns){
									totalColumns = appColumns;
								}
								for (let j = 0; j < totalColumns; j++) {
									const dayWrap = $("#career .main_content .table_box .bottom_box").find(".day_wrap:eq(" + j + ")");
									dayWrap.append(appListHTML).trigger("create");

								}
							}

							if(0 === totalColumns){
								totalColumns = appColumns;
							}
							for (let j = 0; j < totalColumns; j++) {
								let thisHeight = $("#career .main_content .table_box .bottom_box").find(".day_wrap:eq(" + j + ")").find(".day_list:last").height();
								if (maxHeight < thisHeight) {
									maxHeight = thisHeight;
								}
								// 닥터 넓이 조정
								let dataWidth = $("#career .main_content .table_box .bottom_box").find(".day_wrap:eq(" + j + ")").width();
								$("#career .main_content .table_box .top_box .diagnosis_list").find(".diagnosis_user:eq(" + j + ")").css("width", dataWidth);
							}
						}

						for(let j = 0; j < data.memberRows.length; j++) {
							let listHTML = '';
							let muMemberId  = data.memberRows[j].muMemberId;

							for(let z = 0; z < data.rows.length; z++){
								let memberId       = data.rows[z].muMemberId;
								let searchDate     = data.rows[z].searchDate;
								let searchTime     = data.rows[z].searchTime;
								let reserveListMap = data.rows[z].reserveListMap;
								let timeClass = '';

								if(muMemberId == memberId){
									if(null==reserveListMap){
										// 예약 정보 없을 경우
										listHTML += '<ul class="day_list '+timeClass+'">';
									}
									else{
										if(2>=reserveListMap.length){
											listHTML += '<ul class="day_list '+timeClass+'">';
										}
										else{
											listHTML += '<ul class="day_list obesity_list '+timeClass+'">';
											
											// 닥터 상담사 class 추가
											$("#career .main_content .table_box .top_box .diagnosis_list").find(".diagnosis_user:eq("+(j+$(".day_wrap.app").length)+")").addClass("obesity_doctor");
										}
										
										for(let k = 0; k < reserveListMap.length; k++){
											if(resultTime == reserveListMap[k].reserveTime){
												// 예약 정보 있을 경우
												let detailReserveId               = reserveListMap[k].muReserveId;
												let detailUserId                  = reserveListMap[k].muUserId;
												let detailUserName                = reserveListMap[k].userName;
												let detailUserType2               = reserveListMap[k].userType2;
												let detailUserType                = reserveListMap[k].userType;
												let detailBirthday                = reserveListMap[k].birthday;
												let detailReserveDate             = reserveListMap[k].reserveDate;
												let detailReserveTime             = reserveListMap[k].reserveTime;
												let detailReserveCategoryItemId   = reserveListMap[k].reserveCategoryItemId;
												let detailReserveCategoryItemName = reserveListMap[k].reserveCategoryItemName;
												let detailTreatmentId             = reserveListMap[k].muTreatmentId;
												let detailTreatmentName           = reserveListMap[k].treatmentName;
												let detailTreatmentProcedureId    = reserveListMap[k].muTreatmentProcedureId;
												let detailTreatmentProcedureName  = reserveListMap[k].treatmentProcedureName;
												let detailReserveMemberId         = reserveListMap[k].reserveMemberId;
												let detailMemberId                = reserveListMap[k].muMemberId;
												let detailEtc                     = reserveListMap[k].etc;
												let detailStatus                  = reserveListMap[k].status;
												let detailStatus2                 = reserveListMap[k].status2;
												let detailUserEtc                 = reserveListMap[k].userEtc;
												let visitYn                       = reserveListMap[k].visitYn;
												let reserveAppYn                  = reserveListMap[k].reserveAppYn;
												let refusePhotoYn                 = reserveListMap[k].refusePhotoYn;
												let phoneNumber                   = reserveListMap[k].phoneNumber;

												// 사용자 상태별 다르게 UI 처리
												let uiClassArr = '';

												// 신환등록 필요한 사용자 클래스 추가
												if('T'==detailUserType2){
													uiClassArr += ' new';
												}

												// 진료완료, 수납 완료 클래스 추가
												if("Y" == detailStatus && ("Y" == detailStatus2||"PY" == detailStatus2||"R" == detailStatus2||"C" == detailStatus2||"NY" == detailStatus2)){
													uiClassArr += ' finish';
												}
												// 초진일 경우 클래스 추가
												if('N'==visitYn){
													uiClassArr += ' firstVisit';
												}
												// 사용자 주의사항 있을 경우 클래스 추가
												if(true == fn_emptyCheck(detailUserEtc)){
													uiClassArr += ' highlight';
												}
												if('NP'==detailStatus2){
													uiClassArr += ' nonPayment';
												}
												// 앱 예약일 경우 클래스 추가
												if('Y'==reserveAppYn){
													uiClassArr += ' appReserve';
												}
												listHTML += '<li class="reserveDiv '+uiClassArr+'">';
												listHTML += '	<input type="hidden" name="muReserveId" value="'+detailReserveId+'">';
												listHTML += '	<div class="user_list">';

												if('T'==detailUserType2){
													// 간편예약 고객
													listHTML += '	<p class="user">'+detailUserName+'</p>';
												}
												else{
													// 일반 고객
													listHTML += '	<div class="user">'
													if(true == fn_emptyCheck(detailBirthday)){
														listHTML += '		<p class="user_name">'+detailUserName+'</p> <p class="user_number">('+setFormatDate('H', detailBirthday)+')</p>'
													}else{
														listHTML += '		<p class="user_name">'+detailUserName+'</p> <p class="user_number">('+phoneNumber.slice(-4)+')</p>'
													}

													listHTML += '		<div class="icon_box">'
													// 여기에 사진거부 사진 추가
													listHTML += refusePhotoYn=="Y" ? '<img class="fruit" src="/image/web/refuse_photo.png" alt="사진거부">' : '';
													// listHTML += detailUserType?'<img class="fruit" src="'+detailUserType+'" alt="고객">':'';
													if(true == fn_emptyCheck(detailEtc))
														listHTML += '			<img class="alarm" src="/image/web/alarm.svg" alt="예약메모">';
													// 사용자 주의사항 있을 경우 문구추가
													if(true == fn_emptyCheck(detailUserEtc)) {
														listHTML += '			<img class="precaution" src="/image/web/alarm2.svg" alt="주의사항">';
													}
													listHTML += '		</div>'
													listHTML += '	</div>'
												}

												listHTML += '	</div>';

												listHTML += '	<p class="type">';
												listHTML += 		fn_reserveStatusImg(detailStatus, 'N');
												listHTML += 		detailTreatmentName+'-'+detailTreatmentProcedureName;
												listHTML += '	</p>';


												// 사용자 진료상태별 다르게 UI 처리
												let uiClassArr2 = '';

												// 접수상태인 경우 클래스 추가
												if('R'===detailStatus){
													uiClassArr2 = 'R';
												}
												// 진료중인 경우 클래스 추가
												if('G'===detailStatus){
													uiClassArr2 = 'G';
												}
												// 진료끝인 경우 클래스 추가
												if('Y'===detailStatus){
													uiClassArr2 = 'Y';
												}

												listHTML += '	<div class="dropdown">';
												listHTML += '		<button type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" name="rightClick">';
												listHTML += '			<img src="/image/web/day_list_dropdown_icon.svg" alt="메뉴">';
												listHTML += '		</button>';

												listHTML += '		<ul class="dropdown-menu '+uiClassArr2+'" aria-labelledby="dLabel">';
												listHTML += '			<li onclick="fn_updateUserPopup(\''+detailUserId+'\');">';
												listHTML += '				<p class="list"><img class="img_situation" src="/image/web/situation6.svg" alt="">신환등록</p>';
												listHTML += '			</li>';

												if('T'!=detailUserType2){
													listHTML += '		<li class="status0" onclick="fn_openPopup2(\'0201010101\', \'/webuser/updateUserIntro.do?muUserId='+detailUserId+'\')">';
													listHTML += '			<p class="list">고객정보</p>';
													listHTML += '		</li>';

													listHTML += '		<li class="status0" onclick="fn_openPopup2(\'0201010201\', \'/webreserve/selectListReserveUserHistoryIntro.do?muUserId='+detailUserId+'\')">';
													listHTML += '			<p class="list">진료내역</p>';
													listHTML += '		</li>';

													listHTML += '		<li class="status0" onclick="fn_openPopup2(\'0201010102\', \'/webuser/selectListUserPhysicalIntro.do?muUserId='+detailUserId+'\')">';
													listHTML += '			<p class="list">신체기록</p>';
													listHTML += '		</li>';

													listHTML += '		<li class="status0 borderBottom" onclick="fn_insertHomeSmsPopup(\''+detailUserId+'\')">';
													listHTML += '			<p class="list">문자보내기</p>';
													listHTML += '		</li>';

													listHTML += '		<li class="'+fn_addClassSelectStatus('T', detailStatus)+'" onclick="fn_updateReserveStatus(\''+detailReserveId+'\',\'T\');">';
													listHTML += '			<p class="list"><img class="img_situation" src="/image/web/situation1.svg" alt="">예약</p>';
													listHTML += '		</li>';

													listHTML += '		<li class="receipt '+fn_addClassSelectStatus('R', detailStatus)+'" onclick="fn_updateReserveStatus(\''+detailReserveId+'\',\'R\');">';
													listHTML += '			<p class="list"><img class="img_situation" src="/image/web/situation2.svg" alt="">접수</p>';
													listHTML += '		</li>';

													listHTML += '		<li class="status1 '+fn_addClassSelectStatus('G', detailStatus)+'" onclick="fn_updateReserveStatus(\''+detailReserveId+'\',\'G\');">';
													listHTML += '			<p class="list"><img class="img_situation" src="/image/web/situation3.svg" alt="">진료중</p>';
													listHTML += '		</li>';

													listHTML += '		<li class="status2 '+fn_addClassSelectStatus('Y', detailStatus)+' borderBottom" onclick="fn_updateReserveStatus(\''+detailReserveId+'\',\'Y\');">';
													listHTML += '			<p class="list"><img class="img_situation" src="/image/web/situation4.svg" alt="">진료끝</p>';
													listHTML += '		</li>';

													listHTML += '		<li onclick="fn_insertReservePaymentPopup(\''+detailReserveDate+'\',\''+detailUserId+'\',\''+visitYn+'\');">';
													listHTML += '			<p class="list"><img class="img_situation" src="/image/web/situation5.svg" alt="">수납</p>';
													listHTML += '		</li>';

												}else if('T'==detailUserType2){
													listHTML += '		<li class="'+fn_addClassSelectStatus('T', detailStatus)+'" onclick="fn_updateReserveStatus(\''+detailReserveId+'\',\'T\');">';
													listHTML += '			<p class="list"><img class="img_situation" src="/image/web/situation1.svg" alt="">예약</p>';
													listHTML += '		</li>';

													listHTML += '		<li class="receipt '+fn_addClassSelectStatus('R', detailStatus)+'" onclick="fn_updateReserveStatus(\''+detailReserveId+'\',\'R\');">';
													listHTML += '			<p class="list"><img class="img_situation" src="/image/web/situation2.svg" alt="">접수</p>';
													listHTML += '		</li>';
												}


												if("T"==detailStatus || "R"==detailStatus || "G"==detailStatus || "Y"==detailStatus){
													// 예약, 접수, 진료중, 진료끝 예약 수정 가능
													listHTML += '		<li class="borderTop" onclick="fn_updateReservePopup(\''+detailReserveId+'\');">';
													listHTML += '			<p class="list">예약수정</p>';
													listHTML += '		</li>';

													if("T"==detailStatus){
														listHTML += '		<li onclick="fn_updateReserveStatus(\''+detailReserveId+'\',\'TN\');">';
														listHTML += '			<p class="list red_list">예약취소</p>';
														listHTML += '		</li>';
													}
												}

												listHTML += '		</ul>';
												listHTML += '	</div>';

												if(true == fn_emptyCheck(detailEtc)){
													listHTML += '<div class="memo_box">';
													listHTML += '	<p class="memo_title">예약 메모</p>';

													listHTML += '	<div>';
													listHTML += '		<p class="yeyagmemo_title">'+detailTreatmentName+'</p>';
													listHTML += '		<p class="yeyagmemo_content">'+detailEtc+'</p>';
													listHTML += '	</div>';
													listHTML += '</div>';
												}
												if(true == fn_emptyCheck(detailUserEtc)){
													listHTML += '<div class="precaution_box">';
													listHTML += '	<p class="memo_title">주의사항</p>';
													listHTML += '	<div>';
													listHTML += '		<p class="yeyagmemo_title"></p>';
													listHTML += '		<p class="yeyagmemo_content">'+detailUserEtc+'</p>';
													listHTML += '	</div>';
													listHTML += '</div>';
												}
												listHTML += '</li>';
											}

										}
									}
									listHTML += '</ul>';
								}
								
							}
							$("#career .main_content .table_box .bottom_box").find(".day_wrap:eq("+(j+$(".day_wrap.app").length)+")").append(listHTML).trigger("create");
							
							// 각 시간별 높이 구하기
							let thisHeight = $("#career .main_content .table_box .bottom_box").find(".day_wrap:eq("+(j+$(".day_wrap.app").length)+")").find(".day_list:last").height();
							if(maxHeight<thisHeight){
								maxHeight = thisHeight;
							}
							// 닥터 넓이 조정
							let dataWidth = $("#career .main_content .table_box .bottom_box").find(".day_wrap:eq("+(j+$(".day_wrap.app").length)+")").width();
							$("#career .main_content .table_box .top_box .diagnosis_list").find(".diagnosis_user:eq("+(j+$(".day_wrap.app").length)+")").css("width", dataWidth);
						}
						
						// 각 시간별 높이 맞추기 (시간부분, 예약부분)
						if(0<maxHeight){
							$("#career .main_content .time").find("li").eq(i).css("height", maxHeight);
							$("#career .main_content .table_box .bottom_box").find(".day_wrap").find(".day_list:eq("+i+")").css("height", maxHeight);
						}
					}
					
					// 각 직원 전체 넓이 조정
					for(let j = 0; j < data.memberRows.length; j++){
						let maxWidthYn = $("#career .main_content .table_box .bottom_box").find(".day_wrap:eq("+j+")").find(".day_list").hasClass("obesity_list");
						
						if(true == maxWidthYn){
							$("#career .main_content .table_box .bottom_box").find(".day_wrap:eq("+j+")").find(".day_list").addClass("obesity_list");
						}
					}

					// window 우클릭 이벤트 해제
					// .bottom_box 안에서만 우클릭 이벤트 해제 (전체 우클릭 해제하려면
					// document.querySelector(".bottom_box") -> window로 변경
					document.querySelector(".bottom_box").oncontextmenu=function(){
						return false;
					}

					$('.alarm').on('click', function(){
						var $openMemo = $(this).closest('li, td');
						$openMemo.find('.memo_box').toggle();
					});
					$('.precaution').on('click', function(){
						var $openMemo = $(this).closest('li, td');
						$openMemo.find('.precaution_box').toggle();
					});

					// 다른 곳을 클릭했을 때 옵션 숨기기
					$(document).on("click", function(event){
						if (!$(event.target).closest('.alarm, .precaution').length) {
							$(".memo_box").hide();
							$(".precaution_box").hide();
						}
					});

					$(".day_list").on('mousedown', function() {
						// 우클릭 이벤트
						if((event.button === 2)||(event.which === 3)){
							// 클릭한 객체가 li면
							// 또는 가장 가까운 .reserveDiv가 있으면
							if($(event.target).is("li")
								|| 0<$(event.target).closest(".reserveDiv").length){

								let dropdownButton;
								if(0<$(event.target).closest(".reserveDiv").length){
									// 가장 가까운 .reserveDiv가 있으면 .reserveDiv 안에 button
									dropdownButton = $(event.target).closest(".reserveDiv").find("div.dropdown button");
								}else{
									// 클릭한 객체 안에 button
									dropdownButton = $(event.target).find("div.dropdown button");
								}

								if(dropdownButton.hasClass("open")){
									dropdownButton.click();
								}else{
									dropdownButton.click();
								}

							}else {
								// 가장 가까운 .dropdown-menu, li가 없으면
								if(0==$(event.target).closest(".dropdown-menu").length
									&& 0==$(event.target).closest("li").length){
									// #homeContextMenu가 있으면 제거
									if(0<$("#homeContextMenu").length){
										$("#homeContextMenu").remove();
									}

									// 클릭 좌표
									let offsetX = event.offsetX;
									let offsetY = event.offsetY;

									let targetIndex = $(event.target).index();
									let reserveTime = $("ul.time>li").eq(targetIndex).attr("id").split("_")[1];

									let contextMenuHTML = '';
									contextMenuHTML    += '<div id="homeContextMenu" class="homeContextMenu" style="left:'+offsetX+'px; top:'+offsetY+'px;">';
									contextMenuHTML    += '	<ul class="dropdown-menu">';
									contextMenuHTML    += '		<li onClick="fn_insertReservePopup(\'\', \''+reserveTime+'\')">';
									contextMenuHTML    += '			<p class="list">예약하기</p>';
									contextMenuHTML    += '		</li>';
									contextMenuHTML    += '	</ul>';
									contextMenuHTML    += '</div>';

									$(event.target).append(contextMenuHTML);
								}
							}
						}

						$('.day_list li').removeClass('user_focus');
						if($(event.target).is("li")){
							$(event.target).addClass('user_focus');
						}
						$('.home_wrap .right_box').addClass('oh');

						// 오른쪽 리스트 해당 내역으로 이동
						let selectReserveId = $(event.target).children('input[name="muReserveId"]').val();

						// 선택 탭 보이기
						let selectTabsId = $("#div_" + selectReserveId).closest('.tab-pane').attr('id');
						$('a[href="#' + selectTabsId + '"]').tab('show');

						// 기존 선택 표시 제거
						$(".home_wrap .right_box div ul").find('li').removeClass('user_focus');

						setTimeout(function () {
							let $target = $("#div_" + selectReserveId);
							if (0 < $target.length) {
								// 선택 표시
								$target.closest('li').addClass('user_focus');

								// 스크롤 이동
								let $container = $('#' + selectTabsId);
								let containerScrollTop = $container.scrollTop();
								let containerOffset = $container.offset().top + 50;
								let targetOffset = $target.offset().top;
								let scrollTop = containerScrollTop + (targetOffset - containerOffset);
								$('#' + selectTabsId).scrollTop(scrollTop);

								// 상세 열려있으면 닫기
								$('.user_info').hide();
							}
						}, 200);
					});

					// 오늘 날짜의 경우 현재시간으로 스크롤 이동
					/*$(".main_content").scrollTop(0);
					
					let today = new Date();
					let year = today.getFullYear();
					let month = ('0' + (today.getMonth() + 1)).slice(-2);
					let day = ('0' + today.getDate()).slice(-2);
					let todayDate = year+'-'+month+'-'+day;
					
					if(reserveSearchDate == todayDate){
						let hours = ('0' + today.getHours()).slice(-2); 
						let minutes = ('0' + today.getMinutes()).slice(-2);
						
						if(30 > minutes){
							minutes = '00';
						}
						else{
							minutes = '30';
						}
						
						let offset1 = $("#li_"+hours+minutes).offset();
						if(true == fn_emptyCheck(offset1)){
							$(".main_content").animate({scrollTop: offset1.top-233},200);
						}
					}
					if(xScrollPosition!==''){
						$('.main_content').scrollLeft(xScrollPosition);
					}*/
					
				}
				else{
					listHTML = '<p>운영시간이 아닙니다.</p>';
					$("#career .main_content .table_box .bottom_box").empty().html(listHTML).trigger("create");
					
					$("#career .main_content .table_box .top_box .diagnosis_list").empty();
				}
			}
			else{
				modalEvent.danger("조회 오류", data.msgDesc);
			}
		},
		error : function(xhr, status, error) {
			modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
		},
		beforeSend:function(){
			// 로딩열기
			// $(".loading-image-layer").show();
		},
		complete:function(){
			// 로딩닫기
			// $(".loading-image-layer").hide();
		}
	});
}

// ////////////////////////////////////////////////////
// 3. 오른쪽 데이터
// ////////////////////////////////////////////////////
/****************************************************************************
* 탭 - 접수 콤보데이타 이벤트 설정
****************************************************************************/
function fn_setTreatmentComboEvent(paramTarget, clickCallEvent){
	let target = paramTarget.next(".select_option_list");
	
	target.find("li.option_list_item").click(function () {
		// 1. 선택값 셋팅
		let selectId    = $(this).find('input[name="comboId"]').val();
		let selectName  = $(this).find('span').text(); 
		
		$(this).parent().siblings("button").text(selectName);
		$(this).parent().siblings("input").val(selectId);
		
		if( clickCallEvent )  {
			clickCallEvent(selectId);
		}
	});
	
	// 초기화
	target.find("li:eq(0)").click();
}

/****************************************************************************
* 탭 - 진료 콤보데이타 설정
****************************************************************************/
function fn_setTreatmentCombo2(paramTarget, allYn, clickCallEvent){
	let target = paramTarget.next(".select_option_list");
	
	let comboData = fn_selectListTreatmentOption2();
	
	let comboHTML = '';
	
	// 전체옵션 여부
	if('Y'==allYn){
		comboHTML = ' <li class="option_list_item">';
		comboHTML += '	<input type="hidden" name="comboId" value=""/>';
		comboHTML += '	<span>진료 전체</span>';
		comboHTML += '</li>';
	}
	
	for(let i = 0; i < comboData.length; i++){
		let muTreatmentId     = comboData[i].muTreatmentId;
		let treatmentName     = comboData[i].treatmentName;
		
		comboHTML += '<li class="option_list_item">';
		comboHTML += '	<input type="hidden" name="comboId" value="'+muTreatmentId+'"/>';
		comboHTML += '	<span>'+treatmentName+'</span>';
		comboHTML += '</li>';
	}
	target.html(comboHTML);
	
	target.find("li.option_list_item").click(function () {
		// 1. 선택값 셋팅
		let selectId    = $(this).find('input[name="comboId"]').val();
		let selectName  = $(this).find('span').text(); 
		
		$(this).parent().siblings("button").text(selectName);
		$(this).parent().siblings("input").val(selectId);
		
		if( clickCallEvent )  {
			clickCallEvent(selectId);
		}
	});
	
	// 초기화
	target.find("li:eq(0)").click();
}

function fn_setReserveStatusImg(param){
	let resultHTML = '';
	
	if('T'==param){
		// 예약
		resultHTML = '<img class="sityation_img" src="/image/web/situation1.svg" alt=""/>';
	}
	else if('TN'==param){
		// 예약취소
		resultHTML = '<img class="sityation_img" src="/image/web/situation1.svg" alt=""/>';
	}
	else if('R'==param){
		// 접수
		resultHTML = '<img class="sityation_img" src="/image/web/situation2.svg" alt=""/>';
	}
	else if('RN'==param){
		// 접수취소
		resultHTML = '<img class="sityation_img" src="/image/web/situation2.svg" alt=""/>';
	}
	else if('G'==param){
		// 진료중
		resultHTML = '<img class="sityation_img" src="/image/web/situation3.svg" alt=""/>';
	}
	else if('Y'==param){
		// 진료끝
		resultHTML = '<img class="sityation_img" src="/image/web/situation4.svg" alt=""/>';
	}
	
	return resultHTML;
}

/****************************************************************************
* 오른쪽 예약목록 조회 리스트
****************************************************************************/
function fn_selectListReserveStatus1(){
	let reserveSearchDate = $("#date_reserveSearchDate").data().date;
	
	let status            = $('#reservation_list #reservationStatus').val();
	let searchKeyword     = $('#reservation_list #reservationSeaerchKeyword').val();
	let muTreatmentId     = $('#reservation_list #reservationTreatmentId').val();
	
	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("searchDate", reserveSearchDate);
	formData.append("status", status);
	formData.append("searchKeywordParam", searchKeyword);
	formData.append("muTreatmentId", muTreatmentId);

	$.ajax({
		url: encodeURI('/webreserve/selectListReserveStatus.do'),
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		async: true,
		success: function(data){
			if('0'==data.msgCode){
				let listHTML = '';
				
				if(0<data.rows.length){
					for(let i=0 ; i < data.rows.length ; i++){
						let userName                 = data.rows[i].userName;
						let muUserId                 = data.rows[i].muUserId;
						let phoneNumber              = data.rows[i].phoneNumber;
						let birthday                 = data.rows[i].birthday;
						let userType                 = data.rows[i].userType;
						let userType2                = data.rows[i].userType2;
						let historyListMap           = data.rows[i].historyListMap;
						
						listHTML += '<li>';
						listHTML += '	<label for="check21" class="chk_box">';
						
						if("T" == userType2){
							// 간편예약 고객
							listHTML += '	<p class="user">'+userName+'('+phoneNumber.slice(-4)+')</p>';
						}
						else{
							// 일반 고객
							if(true == fn_emptyCheck(birthday)){
								listHTML += '	<p class="user">'+userName+'('+setFormatDate('H', birthday)+')'+(userType?'<img src="'+userType+'" alt="고객구분" /></p>':'');
							}else{
								listHTML += '	<p class="user">'+userName+'('+phoneNumber.slice(-4)+')'+(userType?'<img src="'+userType+'" alt="고객구분" /></p>':'');
							}
						}

						listHTML += '	</label>';
						
						for(let j=0 ; j < historyListMap.length ; j++){
							let muReserveId              = historyListMap[j].muReserveId;
							let reserveDate              = historyListMap[j].reserveDate;
							let reserveTime              = historyListMap[j].reserveTime;
							let reserveCategoryItemId    = historyListMap[j].reserveCategoryItemId;
							let reserveCategoryItemName  = historyListMap[j].reserveCategoryItemName;
							let muTreatmentId            = historyListMap[j].muTreatmentId;
							let treatmentName            = historyListMap[j].treatmentName;
							let muTreatmentProcedureId   = historyListMap[j].muTreatmentProcedureId;
							let treatmentProcedureName   = historyListMap[j].treatmentProcedureName;
							let reserveMemberId          = historyListMap[j].reserveMemberId;
							let muMemberId               = historyListMap[j].muMemberId;
							let etc                      = historyListMap[j].etc;
							let status                   = historyListMap[j].status;
							let status2                  = historyListMap[j].status2;
							
							listHTML += '<div id="div_'+muReserveId+'" class="user_reservation_list" onclick="fn_selectReserve(\''+muReserveId+'\')">';
							listHTML += '	<div class="img_box">';
							listHTML += fn_setReserveStatusImg(status);
							listHTML += '	</div>';
							listHTML += '	<p class="surgery">'+treatmentName+' <span>'+treatmentProcedureName+'</span></p>';
							listHTML += '	<p class="time">'+reserveTime+'</p>';
							listHTML += '	<p class="memo">'+etc+'</p>';
							listHTML += '</div>';
						}
						
						listHTML += '</li>';
					}
				}
				else{
					listHTML += `<div class="" 
									 style="width: 100%;height: 687px;padding: 0;margin: 0;border: none;display: flex;align-items: center;justify-content: center;background: white">
									<p class="user">조회 정보가 없습니다.</p>
								</div>`;
				}
				
				$("#reservation_list .reservation_list").html(listHTML);
			}
			else{
				modalEvent.danger("조회 오류", data.msgDesc);
			}
		},
		error : function(xhr, status, error) {
			modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
		},
		beforeSend:function(){
		},
		complete:function(){
			
		}
	});
}

/****************************************************************************
* 오른쪽 접수목록 조회 리스트
****************************************************************************/
function fn_selectListReserveStatus2(){
	let reserveSearchDate = $("#date_reserveSearchDate").data().date;
	
	let status        = $('#diagnosis_list #diagnosisStatus').val();
	let searchKeyword = $('#diagnosis_list #diagnosisSeaerchKeyword').val();
	let muTreatmentId = $('#diagnosis_list #diagnosisTreatmentId').val();
	
	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("searchDate", reserveSearchDate);
	formData.append("status", status);
	formData.append("searchKeywordParam", searchKeyword);
	formData.append("muTreatmentId", muTreatmentId);

	$.ajax({
		url: encodeURI('/webreserve/selectListReserveStatus.do'),
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		async: true,
		success: function(data){
			if('0'==data.msgCode){
				let listHTML = '';
				
				if(0<data.rows.length){
					for(let i=0 ; i < data.rows.length ; i++){
						let userName                 = data.rows[i].userName;
						let muUserId                 = data.rows[i].muUserId;
						let phoneNumber              = data.rows[i].phoneNumber;
						let birthday                 = data.rows[i].birthday;
						let userType                 = data.rows[i].userType;
						let userType2                = data.rows[i].userType2;
						let historyListMap           = data.rows[i].historyListMap;
						
						listHTML += '<li>';
						listHTML += '	<label for="check21" class="chk_box">';
						
						if("T" == userType2){
							// 간편예약 고객
							listHTML += '	<p class="user">'+userName+'('+phoneNumber.slice(-4)+')</p>';
						}
						else{
							// 일반 고객
							if(true == fn_emptyCheck(birthday)){
								listHTML += '	<p class="user">'+userName+'('+setFormatDate('H', birthday)+')'+(userType?'<img src="'+userType+'" alt="고객구분" /></p>':'');
							}else{
								listHTML += '	<p class="user">'+userName+'('+phoneNumber.slice(-4)+')'+(userType?'<img src="'+userType+'" alt="고객구분" /></p>':'');
							}
						}
						
						listHTML += '	</label>';
						
						for(let j=0 ; j < historyListMap.length ; j++){
							let muReserveId              = historyListMap[j].muReserveId;
							let reserveDate              = historyListMap[j].reserveDate;
							let reserveTime              = historyListMap[j].reserveTime;
							let reserveCategoryItemId    = historyListMap[j].reserveCategoryItemId;
							let reserveCategoryItemName  = historyListMap[j].reserveCategoryItemName;
							let muTreatmentId            = historyListMap[j].muTreatmentId;
							let treatmentName            = historyListMap[j].treatmentName;
							let muTreatmentProcedureId   = historyListMap[j].muTreatmentProcedureId;
							let treatmentProcedureName   = historyListMap[j].treatmentProcedureName;
							let reserveMemberId          = historyListMap[j].reserveMemberId;
							let muMemberId               = historyListMap[j].muMemberId;
							let etc                      = historyListMap[j].etc;
							let status                   = historyListMap[j].status;
							let status2                  = historyListMap[j].status2;
							
							listHTML += '<div id="div_'+muReserveId+'" class="user_diagnosis_list" onclick="fn_selectReserve(\''+muReserveId+'\')">';
							listHTML += '	<div class="img_box">';
							listHTML += fn_setReserveStatusImg(status);
							listHTML += '	</div>';
							listHTML += '	<p class="surgery">'+treatmentName+' <span>'+treatmentProcedureName+'</span></p>';
							listHTML += '	<p class="time">'+reserveTime+'</p>';
							listHTML += '	<p class="memo">'+etc+'</p>';
							listHTML += '</div>';
						}
						
						listHTML += '</li>';
					}
				}
				else{
					listHTML += `<div class="" 
									 style="width: 100%;height: 687px;padding: 0;margin: 0;border: none;display: flex;align-items: center;justify-content: center;background: white">
									<p class="user">조회 정보가 없습니다.</p>
								</div>`;
				}
				
				$("#diagnosis_list .diagnosis_list").html(listHTML);
			}
			else{
				modalEvent.danger("조회 오류", data.msgDesc);
			}
		},
		error : function(xhr, status, error) {
			modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
		},
		beforeSend:function(){
		},
		complete:function(){
			
		}
	});
}

/****************************************************************************
* 오른쪽 진료중 조회 리스트
****************************************************************************/
function fn_selectListReserveStatus3(){
	let reserveSearchDate = $("#date_reserveSearchDate").data().date;
	
	let searchKeyword = $('#treatment_list #treatmentSeaerchKeyword').val();
	let muTreatmentId = $('#treatment_list #treatmentTreatmentId').val();

	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("searchDate", reserveSearchDate);
	formData.append("status", "G");
	formData.append("searchKeywordParam", searchKeyword);
	formData.append("muTreatmentId", muTreatmentId);

	$.ajax({
		url: encodeURI('/webreserve/selectListReserveStatus.do'),
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		async: true,
		success: function(data){
			if('0'==data.msgCode){
				let listHTML = '';
				
				if(0<data.rows.length){
					for(let i=0 ; i < data.rows.length ; i++){
						let userName                 = data.rows[i].userName;
						let muUserId                 = data.rows[i].muUserId;
						let phoneNumber              = data.rows[i].phoneNumber;
						let birthday                 = data.rows[i].birthday;
						let userType                 = data.rows[i].userType;
						let userType2                = data.rows[i].userType2;
						let historyListMap           = data.rows[i].historyListMap;
						
						listHTML += '<li>';
						listHTML += '	<label for="check21" class="chk_box">';
						
						if("T" == userType2){
							// 간편 고객
							listHTML += '	<p class="user">'+userName+'('+phoneNumber.slice(-4)+')</p>';
						}
						else{
							// 일반 고객
							if(true == fn_emptyCheck(birthday)){
								listHTML += '	<p class="user">'+userName+'('+setFormatDate('H', birthday)+')'+(userType?'<img src="'+userType+'" alt="고객구분" /></p>':'');
							}else{
								listHTML += '	<p class="user">'+userName+'('+phoneNumber.slice(-4)+')'+(userType?'<img src="'+userType+'" alt="고객구분" /></p>':'');
							}
						}
						
						listHTML += '	</label>';
						
						for(let j=0 ; j < historyListMap.length ; j++){
							let muReserveId              = historyListMap[j].muReserveId;
							let reserveDate              = historyListMap[j].reserveDate;
							let reserveTime              = historyListMap[j].reserveTime;
							let reserveCategoryItemId    = historyListMap[j].reserveCategoryItemId;
							let reserveCategoryItemName  = historyListMap[j].reserveCategoryItemName;
							let muTreatmentId            = historyListMap[j].muTreatmentId;
							let treatmentName            = historyListMap[j].treatmentName;
							let muTreatmentProcedureId   = historyListMap[j].muTreatmentProcedureId;
							let treatmentProcedureName   = historyListMap[j].treatmentProcedureName;
							let reserveMemberId          = historyListMap[j].reserveMemberId;
							let muMemberId               = historyListMap[j].muMemberId;
							let etc                      = historyListMap[j].etc;
							let status                   = historyListMap[j].status;
							let status2                  = historyListMap[j].status2;
							
							listHTML += '<div id="div_'+muReserveId+'" class="user_diagnosis_list" onclick="fn_selectReserve(\''+muReserveId+'\')">';
							listHTML += '	<div class="img_box">';
							listHTML += fn_setReserveStatusImg(status);
							listHTML += '	</div>';
							listHTML += '	<p class="surgery">'+treatmentName+' <span>'+treatmentProcedureName+'</span></p>';
							listHTML += '	<p class="time">'+reserveTime+'</p>';
							listHTML += '	<p class="memo">'+etc+'</p>';
							listHTML += '</div>';
						}
						
						listHTML += '</li>';
					}
				}
				else{
					listHTML += `<div class="" 
									 style="width: 100%;height: 687px;padding: 0;margin: 0;border: none;display: flex;align-items: center;justify-content: center;background: white">
									<p class="user">조회 정보가 없습니다.</p>
								</div>`;
				}
				
				$("#treatment_list .diagnosis_list").html(listHTML);
			}
			else{
				modalEvent.danger("조회 오류", data.msgDesc);
			}
		},
		error : function(xhr, status, error) {
			modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
		},
		beforeSend:function(){

		},
		complete:function(){

		}
	});
}

/****************************************************************************
* 오른쪽 진료완료 조회 리스트
****************************************************************************/
function fn_selectListReserveStatus4(){
	let reserveSearchDate = $("#date_reserveSearchDate").data().date;
	
	let searchKeyword = $('#complete_list #completeSeaerchKeyword').val();
	let muTreatmentId = $('#complete_list #completeTreatmentId').val();

	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("searchDate", reserveSearchDate);
	formData.append("status", "Y");
	formData.append("searchKeywordParam", searchKeyword);
	formData.append("muTreatmentId", muTreatmentId);

	$.ajax({
		url: encodeURI('/webreserve/selectListReserveStatus.do'),
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		async: true,
		success: function(data){
			if('0'==data.msgCode){
				let listHTML = '';
				
				if(0<data.rows.length){
					let mustListHTML = '';
					let finishListHTML = '';

					for(let i=0 ; i < data.rows.length ; i++){
						let userName                 = data.rows[i].userName;
						let muUserId                 = data.rows[i].muUserId;
						let phoneNumber              = data.rows[i].phoneNumber;
						let birthday                 = data.rows[i].birthday;
						let userType                 = data.rows[i].userType;
						let userType2                = data.rows[i].userType2;
						let historyListMap           = data.rows[i].historyListMap;
						
						for(let j=0 ; j < historyListMap.length ; j++){
							let muReserveId              = historyListMap[j].muReserveId;
							let reserveDate              = historyListMap[j].reserveDate;
							let reserveTime              = historyListMap[j].reserveTime;
							let reserveCategoryItemId    = historyListMap[j].reserveCategoryItemId;
							let reserveCategoryItemName  = historyListMap[j].reserveCategoryItemName;
							let muTreatmentId            = historyListMap[j].muTreatmentId;
							let treatmentName            = historyListMap[j].treatmentName;
							let muTreatmentProcedureId   = historyListMap[j].muTreatmentProcedureId;
							let treatmentProcedureName   = historyListMap[j].treatmentProcedureName;
							let reserveMemberId          = historyListMap[j].reserveMemberId;
							let muMemberId               = historyListMap[j].muMemberId;
							let etc                      = historyListMap[j].etc;
							let status                   = historyListMap[j].status;
							let status2                  = historyListMap[j].status2;
							let visitYn                  = historyListMap[j].visitYn;

							let listItemHTML = '';
							//환불, 결제취소, 미수납 고객은 리스트에 표시추가
							let itemHTML = '';
							if('R'==status2||'C'==status2||'NP'==status2||'P'==status2){
								addClass = 'nonPayment';
								let statusString = (function(status2) {
									switch (status2) {
										case 'R':
											return '환불';
										case 'C':
											return '결제취소';
										case 'NP':
											return '미수';
										case 'P':
											return '부분결제';
										default:
											return '알 수 없음';  // 기본값
									}
								})(status2);

								itemHTML = `<p class="cancelP" style="color: red;float: left">(${statusString})</p>`
							}
							if('Y'==status2||'PY'==status2||'NY'==status2||'R'==status2||'C'==status2||'PP'==status2||'NP'==status2||'P'==status2){
								listItemHTML += '<li id="div_'+muReserveId+'" class="finish">';
							}
							else{
								listItemHTML += '<li id="div_'+muReserveId+'" class="must">';
							}

							
							if("T" == userType2){
								// 간편예약 고객
								listItemHTML += '	<p class="user">'+userName+'</p>';
							}
							else{
								// 일반 고객
								if(true == fn_emptyCheck(birthday)){
									listItemHTML += '	<p class="user">'+userName+'('+setFormatDate('H', birthday)+')'+(userType?'<img src="'+userType+'" alt="고객구분" /></p>':'');
								}else{
									listItemHTML += '	<p class="user">'+userName+'('+phoneNumber.slice(-4)+')'+(userType?'<img src="'+userType+'" alt="고객구분" /></p>':'');
								}
							}
							
							listItemHTML += '		<div class="user_complete_list">';
							listItemHTML += '			<div class="pointer" onclick="fn_selectReserve(\''+muReserveId+'\')">';
							listItemHTML += '				<div class="img_box">';
							listItemHTML += fn_setReserveStatusImg(status);
							listItemHTML += '				</div>';
							listItemHTML += '				<p class="surgery">'+treatmentName+' <span>'+treatmentProcedureName+'</span></p>';
							listItemHTML += '				<p class="time">'+reserveTime+'</p>';
							listItemHTML += '			</div>';
							if('Y'==status2||'PY'==status2||'NY'==status2||'C'==status2||'PP'==status2||'R'==status2){
							listItemHTML += '			<button class="whether" onclick="fn_selectReserve(\''+muReserveId+'\')">'+itemHTML+'수납완료</button>';
							}
							else{
							listItemHTML += '			<button class="whether" onClick="fn_insertReservePaymentPopup(\''+reserveDate+'\', \''+muUserId+'\', \''+visitYn+'\')">'+itemHTML+'수납하기</button>';
							}
							listItemHTML += '		</div>';
							listItemHTML += '		<button class="complete_btn" onclick="fn_selectReserve(\''+muReserveId+'\')"><img src="/image/web/dropdown_arrow.svg"  alt=""/></button>';
							listItemHTML += '	</li>';

							if ('Y'==status2||'PY'==status2||'NY'==status2||'R'==status2||'C'==status2||'PP'==status2||'NP'==status2||'P'==status2) {
                                finishListHTML += listItemHTML;
                            } else {
                                mustListHTML += listItemHTML;
                            }
						}
						
					}
					listHTML = mustListHTML + finishListHTML;
				}
				else{
					listHTML += `<div class="" 
									 style="width: 100%;height: 687px;padding: 0;margin: 0;border: none;display: flex;align-items: center;justify-content: center;background: white">
									<p class="user">조회 정보가 없습니다.</p>
								</div>`;
				}
				
				$("#complete_list .complete_list").html(listHTML);
			}
			else{
				modalEvent.danger("조회 오류", data.msgDesc);
			}
		},
		error : function(xhr, status, error) {
			modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
		},
		beforeSend:function(){
		},
		complete:function(){
			
		}
	});
}

/****************************************************************************
* 진료상태 변경
****************************************************************************/
function fn_updateReserveStatus(param, param2){

	if(true != fn_emptyCheck(param)){
		modalEvent.warning("수정", "예약 정보가 없습니다.");	
		return;
	}
	
	if(true != fn_emptyCheck(param2)){
		modalEvent.warning("수정", "상태 정보가 없습니다.");	
		return;
	}
	
	let msg = "";
	
	if("R"==param2){
		msg = "접수 상태로 변경하시겠습니까?";
	}
	else if("G"==param2){
		msg = "진료중 상태로 변경하시겠습니까?";
	}
	else if("Y"==param2){
		msg = "진료완료 상태로 변경하시겠습니까?";
	}
	else if("TN"==param2){
		msg = "예약취소 상태로 변경하시겠습니까?";
	}
	else if("T"==param2){
		msg = "예약 상태로 변경하시겠습니까?";
	}
	else{
		modalEvent.warning("수정", "상태가 올바르지 않습니다.");	
		return;
	}
	
	modalEvent.info("수정", msg, function(){
		let formData = new FormData();
		formData.append("menuClass", menuClass);
		formData.append("muReserveId", param);
		formData.append("status", param2);
		
		$.ajax({
			url: encodeURI('/webreserve/updateReserveStatus.do'),
			data: formData,
			dataType: "json",
			processData: false,
			contentType: false,
			type: 'POST',
			async: true,
			success: function(data){
				if('0'==data.msgCode){
					modalEvent.success("진료상태 변경 성공", data.msgDesc, function(){
						xScrollPosition = $('.main_content').scrollLeft();
						fn_searchReserveDate();
					});
				}
				else{
					modalEvent.danger("진료상태 변경 오류", data.msgDesc);
				}
			},
			error : function(xhr, status, error) {
				modalEvent.danger("진료상태 변경 오류", "변경 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
			},
			beforeSend:function(){
				
			},
			complete:function(){
				
			}
		});
	});
}

/****************************************************************************
* 오른쪽 진료 상세
****************************************************************************/
function fn_selectReserve(param){

	let reserveSearchDate = $("#date_reserveSearchDate").data().date;
	
	if(true != fn_emptyCheck(param)){
		modalEvent.warning("수정", "예약 정보가 없습니다.");	
		return;
	}
	
	if(true != fn_emptyCheck(reserveSearchDate)){
		modalEvent.warning("수정", "날짜 정보가 없습니다.");	
		return;
	}
	
	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("muReserveId", param);
	formData.append("searchDate", reserveSearchDate);
	
	$.ajax({
		url: encodeURI('/webreserve/selectReserve.do'),
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		async: true,
		success: function(data){
			if('0'==data.msgCode){
				$("#hiddenMuUserId").val(data.rows[0].muUserId);
				// 예약 정보
				$('.user_info .user_info_top .userName').text(data.rows[0].userName);
				$('.user_info .user_info_bottom .user_info_bottom_top .phoneNumber').text(fn_setFormatPhone(data.rows[0].phoneNumber));
				$('.user_info .user_info_bottom .user_info_bottom_center .statusImg').html(fn_reserveStatusImg(data.rows[0].status, 'Y'));
				$('.user_info .user_info_bottom .user_info_bottom_center .reserveDateTime').text(data.rows[0].reserveDate+', '+data.rows[0].reserveTime);
				$('.user_info .user_info_bottom .user_info_bottom_center .visitType').text(data.rows[0].visitYn=='Y'?'재진':'초진');
				$('.user_info .user_info_bottom .user_info_bottom_center .reserveMemberName').text(data.rows[0].reserveMemberName);
				$('.user_info .user_info_bottom .user_info_bottom_center .treatmentName').text(data.rows[0].treatmentName);
				$('.user_info .user_info_bottom .user_info_bottom_center .treatmentProcedureName').text(data.rows[0].treatmentProcedureName);
				$('.user_info .user_info_bottom .user_info_bottom_center .reserveEtc').text(data.rows[0].reserveEtc);

				if('T'==data.rows[0].userType2){
					// 간편예약 고객
					$(".user_info .newUser").show();
					$(".user_info .newUserHidden").hide();
					
					$('.user_info .user_info_bottom .user_info_bottom_top .birthday').text('-');
					$('.user_info .user_info_bottom .user_info_bottom_top .age').text('');
					$('.user_info .user_info_bottom .user_info_bottom_top .gender').text('');
					$('.user_info .user_info_bottom .user_info_bottom_top .nationality').text('');
					$('.user_info .user_info_bottom .user_info_bottom_top .userPhysical').text('-');
					$('.user_info .user_info_bottom .user_info_bottom_top .userType').html('-');
					$('.user_info .user_info_bottom .user_info_bottom_top .etc').text('-');
					$('.user_info .user_info_bottom .user_info_bottom_top .memo').text('-');
					
					// 예약/접수 상태의 경우
					if("T"==data.rows[0].status || "R"==data.rows[0].status){
						// 접수 버튼 처리
						$(".user_info .user_info_bottom .button_box .accept_btn").off("click");
						$(".user_info .user_info_bottom .button_box .accept_btn").click(function () {
							fn_updateReserveStatus(data.rows[0].muReserveId, "R");
						});
						if("T"==data.rows[0].status)
							$(".user_info .user_info_bottom .button_box .accept_btn").show();
						else
							$(".user_info .user_info_bottom .button_box .accept_btn").hide();
						// 수정버튼 버튼 처리
						$(".user_info .user_info_bottom .button_box .modify_btn").off("click");
						$(".user_info .user_info_bottom .button_box .modify_btn").click(function () {
							fn_updateReservePopup(data.rows[0].muReserveId);
						});
						$(".user_info .user_info_bottom .button_box .modify_btn").show();
					}
					else{
						// 접수 버튼
						$(".user_info .user_info_bottom .button_box .accept_btn").off("click");
						$(".user_info .user_info_bottom .button_box .accept_btn").hide();
						// 예약수정 버튼
						$(".user_info .user_info_bottom .button_box .modify_btn").off("click");
						$(".user_info .user_info_bottom .button_box .modify_btn").hide();
					}
					
					// 신환등록 버튼 처리
					$(".user_info .user_info_bottom .button_box button.new_user_btn").off("click");
					$(".user_info .user_info_bottom .button_box button.new_user_btn").click(function () {
						fn_updateUserPopup(data.rows[0].muUserId);
					});
				}
				else if(''===data.rows[0].reserveMemberName){
					$(".user_info .newUser").show();
					$(".user_info .newUserHidden").hide();
					if(!data.rows[0].nationality){
						// 앱 신환 고객
						$('.user_info .user_info_bottom .user_info_bottom_top .birthday').text('-');
						$('.user_info .user_info_bottom .user_info_bottom_top .age').text('');
						$('.user_info .user_info_bottom .user_info_bottom_top .gender').text('');
						$('.user_info .user_info_bottom .user_info_bottom_top .nationality').text('');
						$('.user_info .user_info_bottom .user_info_bottom_top .userPhysical').text('-');
						$('.user_info .user_info_bottom .user_info_bottom_top .userType').html('-');
						$('.user_info .user_info_bottom .user_info_bottom_top .etc').text('-');
						$('.user_info .user_info_bottom .user_info_bottom_top .memo').text('-');
					}else {
						// 앱 기존 고객
						$(".user_info .new_user_btn").hide();
						$('.user_info .user_info_bottom .user_info_bottom_top .birthday').text(data.rows[0].birthday);
						$('.user_info .user_info_bottom .user_info_bottom_top .age').text(data.rows[0].age);
						$('.user_info .user_info_bottom .user_info_bottom_top .gender').text(data.rows[0].gender);
						$('.user_info .user_info_bottom .user_info_bottom_top .nationality').text(data.rows[0].nationality);
						$('.user_info .user_info_bottom .user_info_bottom_top .userPhysical').text(data.rows[0].userPhysical);
						$('.user_info .user_info_bottom .user_info_bottom_top .userType').html(data.rows[0].userType?'<img src="'+data.rows[0].userType+'" alt="고객구분" />':'-');
						$('.user_info .user_info_bottom .user_info_bottom_top .etc').text(data.rows[0].etc);
						$('.user_info .user_info_bottom .user_info_bottom_top .memo').text(data.rows[0].memo);
					}
					$(".user_info .user_info_bottom .button_box .modify_btn").off("click");
					$(".user_info .user_info_bottom .button_box .modify_btn").click(function () {
						fn_updateReservePopup(data.rows[0].muReserveId);
					});
					$(".user_info .user_info_bottom .button_box .modify_btn").show();

					// 신환등록 버튼 처리
					$(".user_info .user_info_bottom .button_box button.new_user_btn").off("click");
					$(".user_info .user_info_bottom .button_box button.new_user_btn").click(function () {
						fn_updateUserPopup(data.rows[0].muUserId);
					});
					$(".user_info .user_info_bottom .button_box .accept_btn").off("click");
					$(".user_info .user_info_bottom .button_box .accept_btn").hide();
				}
				else{
					// 일반 고객
					$(".user_info .newUser").hide();
					$(".user_info .newUserHidden").show();
					
					$('.user_info .user_info_bottom .user_info_bottom_top .birthday').text(data.rows[0].birthday);
					$('.user_info .user_info_bottom .user_info_bottom_top .age').text(data.rows[0].age);
					$('.user_info .user_info_bottom .user_info_bottom_top .gender').text(data.rows[0].gender);
					$('.user_info .user_info_bottom .user_info_bottom_top .nationality').text(data.rows[0].nationality);
					$('.user_info .user_info_bottom .user_info_bottom_top .userPhysical').text(data.rows[0].userPhysical);
					$('.user_info .user_info_bottom .user_info_bottom_top .userType').html(data.rows[0].userType?'<img src="'+data.rows[0].userType+'" alt="고객구분" />':'-');
					$('.user_info .user_info_bottom .user_info_bottom_top .etc').text(data.rows[0].etc);
					$('.user_info .user_info_bottom .user_info_bottom_top .memo').text(data.rows[0].memo);
					
					// 예약/접수 상태의 경우
					if("T"==data.rows[0].status || "R"==data.rows[0].status || "G"==data.rows[0].status || "Y"==data.rows[0].status){
						// 접수 버튼 처리
						$(".user_info .user_info_bottom .button_box .accept_btn").off("click");
						$(".user_info .user_info_bottom .button_box .accept_btn").click(function () {
							fn_updateReserveStatus(data.rows[0].muReserveId, "R");
						});
						if("T"==data.rows[0].status){
							$(".user_info .user_info_bottom .button_box .accept_btn").show();
						}else{
							$(".user_info .user_info_bottom .button_box .accept_btn").hide();
						}
						// 수정버튼 버튼 처리
						$(".user_info .user_info_bottom .button_box .modify_btn").off("click");
						$(".user_info .user_info_bottom .button_box .modify_btn").click(function () {
							fn_updateReservePopup(data.rows[0].muReserveId);
						});
						$(".user_info .user_info_bottom .button_box .modify_btn").show();
					}
					else{
						// 접수 버튼
						$(".user_info .user_info_bottom .button_box .accept_btn").off("click");
						$(".user_info .user_info_bottom .button_box .accept_btn").hide();
						
						// 예약수정 버튼
						$(".user_info .user_info_bottom .button_box .modify_btn").off("click");
						$(".user_info .user_info_bottom .button_box .modify_btn").hide();
					}
					
					// 상담차트 버튼 처리
					$(".user_info .user_info_bottom .user_info_bottom_center button.counseling_btn").off("click");
					$(".user_info .user_info_bottom .user_info_bottom_center button.counseling_btn").click(function () {
						if(!fn_chartRelationCheck('상담차트')){
							modalEvent.warning("", "조회 권한이 없습니다.");
							return false;
						}
						fn_updateUserConsultingChartPopup(data.rows[0].muUserConsultingChartId, data.rows[0].muUserId);
					});
					
					// 시술차트 버튼 처리
					$(".user_info .user_info_bottom .user_info_bottom_center button.surgery_btn").off("click");
					$(".user_info .user_info_bottom .user_info_bottom_center button.surgery_btn").click(function () {
						if(!fn_chartRelationCheck('시술차트')){
							modalEvent.warning("", "조회 권한이 없습니다.");
							return false;
						}
						fn_updateUserMedicalChartPopup(data.rows[0].muUserMedicalChartId, data.rows[0].muUserId);
					});
					
					// 수납 버튼 처리
					$(".user_info .user_info_bottom .button_box button.calculation_btn").off("click");
					$(".user_info .user_info_bottom .button_box button.calculation_btn").click(function () {
						fn_insertReservePaymentPopup(data.rows[0].reserveDate, data.rows[0].muUserId,data.rows[0].visitYn);
					});
					
					// 이용내역 5개 조회
					let historyList = data.rows[0].historyList;
					if(null!=historyList){
						let historyHTML = '';
						
						if(null!=historyList && 0<historyList.length){
							for(let i=0 ; i < historyList.length ; i++){
								let historyReserveDate            = setFormatDate('E', historyList[i].reserveDate);
								let historyTreatmentName          = historyList[i].treatmentName;
								let historyReserveMemberName      = historyList[i].reserveMemberName;
								let historyStatus                 = historyList[i].status;
								let historyStatusName             = fn_reserveStatus(historyList[i].status);
								
								historyHTML += '<tr>';
								historyHTML += '	<td>'+historyReserveDate+'</td>';
								historyHTML += '	<td>'+historyTreatmentName+'</td>';
								historyHTML += '	<td>'+historyReserveMemberName+'</td>';
								if("Y"==historyStatus){
									historyHTML += '<td>'+historyStatusName+'</td>';
								}
								else{
									historyHTML += '<td class="register_state">'+historyStatusName+'</td>';
								}
								
								historyHTML += '</tr>';
							}
						}
						else{
							historyHTML += '<tr>';
							historyHTML += '	<td colspan="4">조회 내역이 없습니다.</td>';
							historyHTML += '</tr>';
						}
						$(".user_info .user_info_bottom .table_top button").attr("id",data.rows[0].muUserId);
						$(".user_info .user_info_bottom .table_box tbody").html(historyHTML);
					}
				}
				$('.user_info').show();
			}
			else{
				modalEvent.danger("조회 오류", data.msgDesc);
			}
		},
		error : function(xhr, status, error) {
			modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
		},
		beforeSend:function(){
			
		},
		complete:function(){
			
		}
	});
}
/****************************************************************************
 * 차트조회 권한 체크
 ****************************************************************************/
function fn_chartRelationCheck(menuName){
	let result;

	let formData = new FormData();
	formData.append("menuName",menuName)
	$.ajax({
		url: encodeURI('/webauth/selectHeaderRelation.do'),
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		async: false,
		success: function(data){
			if('0'==data.msgCode){
				result = data.rows.selectUseYn==='Y';
			}
			else if(data.msgCode=='-1'){
				modalEvent.warning("조회 오류", data.msgDesc);
			}
			else{
				modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
			}
		},
		error : function(xhr, status, error) {
			modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
		},
		beforeSend:function(){

		},
		complete:function(){

		}
	});

	return result;
}
/****************************************************************************
* 날짜선택 시 조회 이벤트
****************************************************************************/
function fn_searchReserveDate(){
	// 1. 왼쪽 데이터
	// 금일 공지사항 조회
	fn_selectListTodayNotice();
	
	// 금일 근무현황 조회
	fn_selectListTodayAttendance();
	
	// 2. 가운데 데이터
	// 방문 콤보데이타 설정
	fn_setReserveVisitCombo();
	
	// 진료 콤보데이타 설정
	fn_setTreatmentCombo();
	
	fn_selectListReserve();
	
	// 3. 오른쪽 데이터
	// 예약건수 조회
	fn_selectTotalReserveStatusCount();
	// 예약목록 진료 콤보 데이터 설정
	let comboTarget = $('#reservation_list #reservationTreatmentId');
	let allYn = 'Y';
	fn_setTreatmentCombo2(comboTarget, allYn, function(value){});
	
	// 예약목록 접수 콤보 데이터 이벤트 설정
	let comboTarget2 = $('#reservation_list #reservationStatus');
	fn_setTreatmentComboEvent(comboTarget2, function(value){});
	
	// 접수목록 접수 콤보 데이터 이벤트 설정
	let comboTarget3 = $('#diagnosis_list #diagnosisStatus');
	fn_setTreatmentComboEvent(comboTarget3, function(value){});
	
	// 예약목록 리스트 조회
	fn_selectListReserveStatus1();
	fn_selectListReserveStatus2();
	fn_selectListReserveStatus3();
	fn_selectListReserveStatus4();
	
	// 첫 탭 active
	$('a[href="#reservation_list"]').tab('show');
	
	$('.user_info').hide();
	
}

/****************************************************************************
* 검색 엔터 이벤트
****************************************************************************/
function fn_homeEnter(e){
	if(e.which){
		// 파이어폭스
		if(13 == e.which) {
			//로그인 액션 스크립트
			fn_noticeSearch();
		}
	}
	else{
		// 윈도우, 사파리, 크롬
		if(13 == event.keyCode) {
			//로그인 액션 스크립트
			fn_noticeSearch();
		}
	}
}


/****************************************************************************
* 상담차트 조회 및 수정 팝업
****************************************************************************/
function fn_updateUserConsultingChartPopup(param, param2){
	
	if(true != fn_emptyCheck(param)){
		modalEvent.warning("등록", "상담차트 정보가 없습니다.");	
		return;
	}
	
	if(true != fn_emptyCheck(param2)){
		modalEvent.warning("등록", "고객 정보가 없습니다.");	
		return;
	}
	
	let reqParam =  {'muUserConsultingChartId':param, 'muUserId':param2};
	userConsultingChartUpdateModal.popup(function(obj, reqParam) {
		fn_searchReserveDate();
	}, reqParam);
}


/****************************************************************************
* 시술차트 조회 및 수정 팝업
****************************************************************************/
function fn_updateUserMedicalChartPopup(param, param2){
	
	if(true != fn_emptyCheck(param)){
		modalEvent.warning("등록", "시술차트 정보가 없습니다.");	
		return;
	}
	
	if(true != fn_emptyCheck(param2)){
		modalEvent.warning("등록", "고객 정보가 없습니다.");	
		return;
	}
	
	let reqParam =  {'muUserMedicalChartId':param, 'muUserId':param2};
	userMedicalChartUpdateModal.popup(function(obj, reqParam) {
		fn_searchReserveDate();
	}, reqParam);
}

/****************************************************************************
* 예약 건 수납 및 수내역 조회 팝업
****************************************************************************/
function fn_insertReservePaymentPopup(param, param2, param3){

	if(true != fn_emptyCheck(param)){
		modalEvent.warning("등록", "날짜 정보가 없습니다.");	
		return;
	}
	
	if(true != fn_emptyCheck(param2)){
		modalEvent.warning("등록", "고객 정보가 없습니다.");	
		return;
	}
	if(true != fn_emptyCheck(param3)){
		modalEvent.warning("등록", "방문유형 정보가 없습니다.");
		return;
	}
	
	let reqParam =  {'reserveDate':param, 'muUserId':param2, 'visitYn':param3};
	reservePaymentInsertModal.popup(function(obj, reqParam) {
		fn_searchReserveDate();
	}, reqParam);
}



/****************************************************************************
* 예약 수정 팝업
****************************************************************************/
function fn_updateReservePopup(param){
	let reserveSearchDate = $("#date_reserveSearchDate").data().date;
	
	if(true != fn_emptyCheck(reserveSearchDate)){
		modalEvent.warning("등록", "조회날짜 정보가 없습니다.");	
		return;
	}
	
	if(true != fn_emptyCheck(param)){
		modalEvent.warning("등록", "예약 정보가 없습니다.");	
		return;
	}
	
	let reqParam =  {'muReserveId':param,
					 'reserveDate':reserveSearchDate
					};
	reserveUpdateModal.popup(function(obj, reqParam) {
		fn_searchReserveDate();
	}, reqParam);
}

/****************************************************************************
* 간편예약 고객 - 신환등록 처리
****************************************************************************/
function fn_updateUserPopup(param){
	
	if(true != fn_emptyCheck(param)){
		modalEvent.warning("등록", "상담차트 정보가 없습니다.");	
		return;
	}
	
	let reqParam =  {'muUserId':param};
	userUpdateModal.popup(function(obj, reqParam) {
		fn_searchReserveDate();
	}, reqParam);
}
/****************************************************************************
* 고객상세- 예약(진료) 내역 이동
****************************************************************************/
function fn_selectReserveHistoryMenuCode(){
	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("menuName", '예약(진료) 내역');
	$.ajax({
		url: encodeURI('/webmenu/selectMenuCode.do'),
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		async: true,
		success: function(data){
			if('0'==data.msgCode){
				let muUserId = $(".user_info .user_info_bottom .table_top button").attr("id");
				let pagingParam = "?menuClass="+data.menuCode;
				pagingParam    += "&muUserId="+muUserId;
				fn_leftFormAction("/webreserve/selectListReserveUserHistoryIntro.do"+pagingParam);
			}
			else{
				modalEvent.danger("조회 오류", data.msgDesc);
			}
		},
		error : function(xhr, status, error) {
			modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
		},
		beforeSend:function(){
		},
		complete:function(){
		}
	});
}

/****************************************************************************
* 달력 휴일 표시
****************************************************************************/
function fn_setCalendar(holidayData){
	holidayData.forEach(data =>{
		if('hospitalHoliday'===data.dateType){
			$(`.datepicker-days .table-condensed  [data-day="${data.locDate}"]`).css('color','#3985EA');
		}else if('publicHoliday'===data.dateType){
			$(`.datepicker-days .table-condensed  [data-day="${data.locDate}"]`).css('color','red');
		}
	});
}

/****************************************************************************
 * 문자 등록
 ****************************************************************************/
function fn_insertHomeSmsPopup(param) {
    if ("Y" != insertUseYn) {
        modalEvent.warning("", "등록 권한이 없습니다.");
        return false;
    }

    if(true != fn_emptyCheck(param)){
        modalEvent.warning("", "발송대상이 없습니다.");
        return false;
    }

    let reqParam = {
		"muUserId" : param
	};
    homeSmsInsertModal.popup(function (obj, reqParam) {
    }, reqParam);
}

/****************************************************************************
* 글자 수 byte 체크 (SMS)
****************************************************************************/
function fn_getByteText(param, maxByte){

    let strValue = param.value;
    let strLen = strValue.length;
    let totalByte = 0;
    let len = 0;
    let str2 = '';
    let code;

    if(!strValue){
        // $("#smsContentByteCheck").text("0");
        $("#userConsultingChartUpdateModal #smsTypeCheck").val("S");
    }else{
        for(let i=0; i<strLen; i++){
            code = strValue.charCodeAt(i);

            if(code > 127){
                totalByte += 2;
            }else{
                totalByte += 1;
            }

            // $("#smsContentByteCheck").text(totalByte);

            // 입력한 문자 길이보다 넘치면 잘라내기 위해 저장
            if(totalByte <= maxByte){
                len = i+1;
            }

            if(totalByte>90){
                $("#userConsultingChartUpdateModal #smsTypeCheck").val("L");
            }else{
                $("#userConsultingChartUpdateModal #smsTypeCheck").val("S");
            }
        }
    }

    // 넘어가는 글자는 자른다.
    if(totalByte > maxByte){
        modalEvent.warning("", maxByte + "자를 초과 입력할 수 없습니다.");

        str2 = strValue.substr(0, len);
        param.value = str2;
        // $("#smsContentByteCheck").text(maxByte);
        fn_getByteText(param);
    }
}

/****************************************************************************
* 상태에 따라 selectStatus 클래스 추가
****************************************************************************/
function fn_addClassSelectStatus(status, userStatus){
	if(status == userStatus){
		return "selectStatus";
	}else{
		return "";
	}
}

/****************************************************************************
* 페이지 init
****************************************************************************/
function fn_pageInit(){
	// 1. 왼쪽 데이터
	// 달력
	$('#date_reserveSearchDate').datetimepicker({
		inline: true,
		sideBySide: true,
		format: 'YYYY-MM-DD',
	})
	.on('dp.change', function (e) {
		fn_searchReserveDate();
	});


	$('#sel_reserveTreatment').selectpicker({
		selectAllText: "전체 선택",
		deselectAllText: "전체 해제",
		noneSelectedText: "진료 선택"
	});

	$('#sel_reserveTreatmentProcedure').selectpicker({
		selectAllText: "전체 선택",
		deselectAllText: "전체 해제",
		noneSelectedText: "시술 선택"
	});

	$('#sel_reserveMember').selectpicker({
		selectAllText: "전체 선택",
		deselectAllText: "전체 해제",
		noneSelectedText: "닥터/상담 선택"
	});

	$('#sel_reserveReserveVisit').selectpicker({
		selectAllText: "전체 선택",
		deselectAllText: "전체 해제",
		noneSelectedText: "방문 선택"
	});


	fn_searchHospitalHoliday();
	fn_searchReserveDate();
}

/****************************************************************************
* 페이지 event
****************************************************************************/
function fn_pageEvent(){
	// 가운데 예약현황 조회 버튼 이벤트
	$("#career .search_btn").on("click", function(){
		fn_selectListReserve();
		let treatmentId = $('#reserveTreatmentId').val();
		$('#diagnosis_list #diagnosisTreatmentId').val(treatmentId);
		$('#reservation_list #reservationTreatmentId').val(treatmentId);
		fn_selectListReserveStatus1();
		fn_selectListReserveStatus2();
	});
	
	
	
	// 오른쪽 상태별 예약현황 조회 탭 이벤트
	$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
		let target = $(e.target).attr("href");
		
		if(('#reservation_list' == target)) {
			// 검색 초기화
			$('#reservation_list #reservationStatus').siblings(".select_option_list").find("li:eq(0)").click();
			
			// 예약목록 진료 콤보 데이터 설정
			let comboTarget = $('#reservation_list #reservationTreatmentId');
			let allYn = 'Y';
			fn_setTreatmentCombo2(comboTarget, allYn, function(value){});
			
			
			fn_selectListReserveStatus1();
		}
		else if(('#diagnosis_list' == target)) {
			// 검색 초기화
			$('#diagnosis_list #diagnosisStatus').siblings(".select_option_list").find("li:eq(0)").click();
			
			// 접수목록 진료 콤보 데이터 설정
			let comboTarget = $('#diagnosis_list #diagnosisTreatmentId');
			let allYn = 'Y';
			fn_setTreatmentCombo2(comboTarget, allYn, function(value){});
			
			
			fn_selectListReserveStatus2();
		}
		else if(('#treatment_list' == target)) {
			// 접수목록 진료 콤보 데이터 설정
			let comboTarget = $('#treatment_list #treatmentTreatmentId');
			let allYn = 'Y';
			fn_setTreatmentCombo2(comboTarget, allYn, function(value){});

			fn_selectListReserveStatus3();
		}
		else if(('#complete_list' == target)) {
			// 접수목록 진료 콤보 데이터 설정
			let comboTarget = $('#complete_list #completeTreatmentId');
			let allYn = 'Y';
			fn_setTreatmentCombo2(comboTarget, allYn, function(value){});
			fn_selectListReserveStatus3();

			fn_selectListReserveStatus4();
		}
		
	});
	
	// 예약목록 조회 버튼 이벤트
	$("#reservation_list .search_btn").on("click", function(){
		fn_selectListReserveStatus1();
	});
	
	
	// 접수목록 조회 버튼 이벤트
	$("#diagnosis_list .search_btn").on("click", function(){
		fn_selectListReserveStatus2();
	});
	
	// 진료중 조회 버튼 이벤트
	$("#treatment_list .search_btn").on("click", function(){
		fn_selectListReserveStatus3();
	});
	
	// 진료완료 조회 버튼 이벤트
	$("#complete_list .search_btn").on("click", function(){
		fn_selectListReserveStatus4();
	});
	
	// 예약 상세 닫기 이벤트
	$('.user_info_top .close_btn').on('click', function(){
		$('.user_info').hide();
	});

	$('.user_info .more_btn').on('click', function(){
		fn_selectReserveHistoryMenuCode();
	});

	// $('.datepicker-days').on('click', function(e) {
	// 	fn_setCalendar(holidayListMap);
	// 	e.stop();
	// })

	// 달력의 DOM 변경을 감지하는 MutationObserver 설정
	let targetNode = document.querySelector('.datepicker-days .table-condensed');

	let observer = new MutationObserver(function(mutationsList, observer) {
		for (let mutation of mutationsList) {
			if (mutation.type === 'childList') {
				// 달력이 다시 렌더링될 때마다 공휴일 스타일을 적용
				fn_setCalendar(holidayListMap);
			}
		}
	});

// 감시할 대상과 옵션 설정
	let config = { childList: true, subtree: true };

// MutationObserver 시작
	if (targetNode) {
		observer.observe(targetNode, config);
	}

	// 고객이름 클릭 - 고객 상세 새창
	$("#homeRightUserInfoName").on("click", function(){
		let muUserId = $("#hiddenMuUserId").val();
		fn_openPopup2('0201010101', '/webuser/updateUserIntro.do?muUserId='+muUserId);
	});

	// 고객이름 클릭 - 고객 상세 새창
	$("#homeRightUserInfoPhysical").on("click", function(){
		let muUserId = $("#hiddenMuUserId").val();
		fn_openPopup2('0201010102', '/webuser/selectListUserPhysicalIntro.do?muUserId='+muUserId);
	});
}

$(function(){
	// 페이지 init
	fn_pageInit();
	
	// 페이지 event
	fn_pageEvent();
});

/****************************************************************************
* 페이지 event - right_box 관련 (반응형일때)
****************************************************************************/

// right_box open
function rightOpen(){
	$(".right_box").toggleClass("open");
	$("body").toggleClass("oh");
}

// calendar open
function calendar(){
	$(".calendar").toggleClass("open");
}

// notice open
function notice(){
	$(".notice").toggleClass("open");
}

// situation open
function situation(){
	$(".situation").toggleClass("open");
}

// 박스 외부 클릭 시 닫기
$(document).on('click', function(event) {
	if (!$(event.target).closest('.calendar, .calendar_btn').length) {
		$(".calendar").removeClass("open");
	}
	if (!$(event.target).closest('.notice, .notice_btn').length) {
		$(".notice").removeClass("open");
	}
	if (!$(event.target).closest('.situation, .situation_btn').length) {
		$(".situation").removeClass("open");
	}

	if (!$(event.target).closest('#homeContextMenu').length) {
		$("#homeContextMenu").remove();
	}
});