
/* ##############################################################
	설  명 : [Modal]예약 수정 팝업
	작성일 : 2023. 01. 19.
	작성자 : NTsoft
	수정일 	        수정자 	 수정내용
	-------         -------- ---------------------------
	2023. 01. 19.	NTsoft 	 최초 생성
*/
let reserveUpdateModal = {
	callback : null,
	reqParam : null,
	dataList : null,
	/* 모달 초기화 작업 */
	init : function () {
		$('#reserveUpdateModal').remove();
		$('body').append( this.HtmlTemplate);
		//그리드 이벤트
		this.setEvent();
	},
	/* 그리드 이벤트 설정 */
	setEvent:function() {
		$('#reserveUpdateModal .btnCancle').on("click", function(){
			reserveUpdateModal.close();
		});
		
		$('#reserveUpdateModal .btnSave').on("click", function(){
			reserveUpdateModal.save("I");
		});
		
		// tab1 : 예약등록
		$('#reserveUpdateModal #list1 .btnReserveAdd').on("click", function(){
			reserveUpdateModal.addRow();
		});
		
		// tab1 : 담당자 수정하기 이벤트
		$('#reserveUpdateModal #list1 .manager_btn').on("click", function(){
			$('#reserveUpdateModal #list1 .read_box').hide();
			$('#reserveUpdateModal #list1 .search_box.member_box').show();
		});
		
		// tab1 : 담당자 수정 취소하기 이벤트
		$('#reserveUpdateModal #list1 .cancel_btn').on("click", function(){
			$('#reserveUpdateModal #list1 .read_box').show();
			$('#reserveUpdateModal #list1 .search_box.member_box').hide();
		});
		
		// tab1 : 담당자 변경 이벤트
		let modalMemberTarget = $('#reserveUpdateModal #list1 input[name="modalMemberName"]');
		modalMemberTarget.on("click", function(){
			let reqParam = {};
			memberSearchModal.popup(function (obj) {
				modalMemberTarget.val(obj.selectMemberName);
				modalMemberTarget.closest('.search_box').siblings('input[name="modalMemberId"]').val(obj.selectMemberId);
			}, reqParam);
		});
		$('#reserveUpdateModal #list1').on('change','input[name="modalReserveDate"]',function (){
			let selectDate = $('#reserveUpdateModal #list1').find('input[name="modalReserveDate"]').val();
			// 예약 시간 셋팅
			fn_searchSetTime('reserveUpdateModal #list1 .modal_table_content:last .select_option_list.time',selectDate);
		})
	},
	/* 예약경로 콤보데이터 설정 (동적추가) */
	setReserveCategoryCombo:function() {
		// let comboData = fn_selectListReserveCategoryItemOption();
		// let comboHTML = '';
		// for(let i = 0; i < comboData.length; i++){
		// 	let muCategoryItemId = comboData[i].muCategoryItemId;
		// 	let categoryItemCode = comboData[i].categoryItemCode;
		// 	let categoryItemName = comboData[i].categoryItemName;
		//
		// 	comboHTML += '<li id="li_'+muCategoryItemId+'" class="option_list_item">'+categoryItemName+'</li>';
		// }
		// return comboHTML;
		let category = fn_selectCategoryList2();
		let reservationCategory = category.find(cat => cat.categoryName === '예약경로');

		if (reservationCategory) {
			fn_selectModalOtherOption2(reservationCategory.categoryCode);
		}
	},
	/* 닥터/상담 콤보데이터 설정 (동적추가) */
	setReserveMemberCombo:function(param, param2) {
		let comboData = fn_selectListReserveMemberOption(param, param2);
		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 += '<li id="li_'+muMemberId+'" class="option_list_item">'+typeName+' '+memberName+'</li>';
		}
		return comboHTML;
	},
	/* tab1 : 예약 추가 */
	addRow:function() {
		let addRowHtml = '';
		addRowHtml += '<li class="modal_table_content">';
		addRowHtml += '	<div class="first">';
		addRowHtml += '	<input type="hidden" name="modalReserveId" />';
		addRowHtml += '		<div class="calendar_box">';
		addRowHtml += '			<div class="date_box">';
		addRowHtml += '				<img src="/image/web/calendar.svg" alt="calendar"/>';
		addRowHtml += '				<input type="date" class="date_picker" name="modalReserveDate">';
		addRowHtml += '			</div>';
		addRowHtml += '		</div>';
		addRowHtml += '		<div class="select_box dropdown">';
		addRowHtml += '			<button class="label" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">00:00</button>';
		addRowHtml += '			<input type="hidden" name="modalReserveTime">';
		
		addRowHtml += '			<ul class="select_option_list dropdown-menu time"></ul>';
		addRowHtml += '		</div>';
		addRowHtml += '	</div>';
		addRowHtml += '	<div>';
		addRowHtml += '		<div class="select_box dropdown">';
		addRowHtml += '			<button class="label" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">예약경로</button>';
		addRowHtml += '			<input type="hidden" name="modalReserveCategoryItemCode">';
		addRowHtml += '			<ul class="select_option_list dropdown-menu">';
		addRowHtml += '			</ul>';
		addRowHtml += '		</div>';
		addRowHtml += '	</div>';
		addRowHtml += '	<div>';
		addRowHtml += '		<div class="search_box" data-target=".medical_type" style="transition: all 0.2s ease-in-out 0s;">';
		addRowHtml += '			<img src="/image/web/search_B.svg" alt="search"/>';
		addRowHtml += '			<input type="hidden" name="modalTreatmentProcedureId" />';
		addRowHtml += '			<input type="text" name="modalTreatmentProcedureName" readonly />';
		addRowHtml += '		</div>';
		addRowHtml += '	</div>';
		addRowHtml += '	<div>';
		addRowHtml += '		<div class="select_box dropdown">';
		addRowHtml += '			<button class="label" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">닥터/상담</button>';
		addRowHtml += '			<input type="hidden" name="modalReserveMemberId">';
		addRowHtml += '			<ul class="select_option_list dropdown-menu"></ul>';
		addRowHtml += '		</div>';
		addRowHtml += '	</div>';
		addRowHtml += '	<div>';
		addRowHtml += '		<div class="input_box">';
		addRowHtml += '			<input type="text" name="modalEtc" placeholder="-"/>';
		addRowHtml += '		</div>';
		addRowHtml += '	</div>';
		addRowHtml += '</li>';
		$('#reserveUpdateModal #list1 .reserveRowBox').append(addRowHtml).trigger("create");
		reserveUpdateModal.setReserveCategoryCombo();
		
		// 현재 row
		let parentTarget = $('#reserveUpdateModal #list1 .modal_table_content:last');
		
		// 예약 일자
		parentTarget.find('input[name="modalReserveDate"]').datetimepicker({
			allowInputToggle: true,
			format: 'YYYY-MM-DD',
			defaultDate: moment()
		});
		
		// 예약 시간 셋팅
		let selectDate = $('#reserveUpdateModal #list1').find('input[name="modalReserveDate"]').val();
		fn_searchSetTime('reserveUpdateModal #list1 .modal_table_content:last .select_option_list.time', selectDate);
		
		// 콤보 이벤트
		parentTarget.find(".select_option_list").not('.time').find("li.option_list_item").click(function () {
			// 1. 선택값 셋팅
			let selectIdArr = $(this).prop("id").split('_');
			let selectId    = selectIdArr[1];
			let selectName  = $(this).text();
			
			$(this).parent().siblings("button").text(selectName);
			$(this).parent().siblings("input").val(selectId);
		});
		
		// 진료/시술 검색 팝업 이벤트
		let treatmentProcedureTarget = parentTarget.find('input[name="modalTreatmentProcedureName"]');
		treatmentProcedureTarget.on("click", function(){
			let reqParam = {};
			treatmentProcedureSearchModal.popup(function (obj, reqParam) {
				treatmentProcedureTarget.prev().val(obj.muTreatmentProcedureId);
				treatmentProcedureTarget.val(obj.treatmentProcedureName);
				
				// 닥터/상담자 콤보 셋팅
				let reserveMemberTarget = parentTarget.find('input[name="modalReserveMemberId"]').next(".select_option_list");
				
				let modalReserveDate = parentTarget.find('input[name="modalReserveDate"]').val();
				let reserveMemberHTML = reserveUpdateModal.setReserveMemberCombo(modalReserveDate, obj.muTreatmentProcedureId);
				reserveMemberTarget.html(reserveMemberHTML);
				reserveMemberTarget.siblings("button").text("닥터/상담");
		
				reserveMemberTarget.find("li.option_list_item").click(function () {
					// 1. 선택값 셋팅
					let selectIdArr = $(this).prop("id").split('_');
					let selectId    = selectIdArr[1];
					let selectName  = $(this).text();
					
					$(this).parent().siblings("button").text(selectName);
					$(this).parent().siblings("input").val(selectId);
				});
			}, reqParam);
		});
		
	},
	/* 데이터 선택 */
	setSelect:function(selectNumber) {
		let checkedData = dataList[selectNumber];
		if(dataList==null||checkedData==undefined){
			return ;
		}
		
		if( reserveUpdateModal.callback )  {
			reserveUpdateModal.callback(checkedData);
		}
		reserveUpdateModal.close();
	},
	// 상세 조회
	search:function(state) {
		let reserveDate = reserveUpdateModal.reqParam.reserveDate;
		let muReserveId = reserveUpdateModal.reqParam.muReserveId;

		if(true != fn_emptyCheck(reserveDate)){
			modalEvent.warning("수정", "날짜 정보가 없습니다.");
			return;
		}
		
		if(true != fn_emptyCheck(muReserveId)){
			modalEvent.warning("수정", "예약 정보가 없습니다.");
			return;
		}
		
		let formData = new FormData();
		formData.append("menuClass", menuClass);
		formData.append("muReserveId", muReserveId);
		formData.append("searchDate", reserveDate);

		$.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){
					
					$('#reserveUpdateModal #list1 input[name="modalUserId"]').val(data.rows[0].muUserId);
					$('#reserveUpdateModal #list1 input[name="modalUserName"]').val(data.rows[0].userName);
					
					if("T" == data.rows[0].userType2){
						// 간편예약 고객
						$('#reserveUpdateModal #list1 .modalUserType').html('-');
						$('#reserveUpdateModal #list1 .modalBirthday').text('-');
						$('#reserveUpdateModal #list1 .modalGender').text('-');
						$('#reserveUpdateModal #list1 .modalNationality').text('-');
						$('#reserveUpdateModal #list1 .modalPhoneNumber').text(fn_setFormatPhone(data.rows[0].phoneNumber));
						$('#reserveUpdateModal #list1 .modalMemo').text('-');
						
						$("#reserveUpdateModal #list1 .btnReserveAdd").hide();
					}
					else{
						// 일반 고객
						$('#reserveUpdateModal #list1 .modalUserType').html('<img src="'+data.rows[0].userType.replace("C:", "")+'" alt="고객구분" />');
						$('#reserveUpdateModal #list1 .modalBirthday').text(data.rows[0].birthday);
						$('#reserveUpdateModal #list1 .modalGender').text(data.rows[0].gender);
						$('#reserveUpdateModal #list1 .modalNationality').text(data.rows[0].nationality);
						$('#reserveUpdateModal #list1 .modalPhoneNumber').text(fn_setFormatPhone(data.rows[0].phoneNumber));
						$('#reserveUpdateModal #list1 .modalMemo').text(data.rows[0].memo);
					}
					
					
					$('#reserveUpdateModal #list1 input[name="modalMemberId"]').val(data.rows[0].muMemberId);
					$('#reserveUpdateModal #list1 input[name="modalMemberName"]').val(data.rows[0].memberName);
					
					
					for(let i = 0; i < data.rows.length; i++){
						let muReserveId                = data.rows[i].muReserveId;
						let reserveDate                = data.rows[i].reserveDate;
						let reserveTime                = data.rows[i].reserveTime;
						let reserveCategoryItemCode    = data.rows[i].reserveCategoryItemCode;
						let reserveCategoryItemName    = data.rows[i].reserveCategoryItemName;
						let muTreatmentProcedureId     = data.rows[i].muTreatmentProcedureId;
						let treatmentProcedureName     = data.rows[i].treatmentProcedureName;
						let reserveMemberId            = data.rows[i].reserveMemberId;
						let reserveMemberName          = data.rows[i].reserveMemberName;
						let etc                        = data.rows[i].reserveEtc;
						let status                     = data.rows[i].status;
						let status2                    = data.rows[i].status2;
						
						// row 생성
						reserveUpdateModal.addRow();
						
						// 현재 row
						let parentTarget = $('#reserveUpdateModal #list1 .modal_table_content:last');
						
						// 값 셋팅
						// 예약 식별자
						parentTarget.find('input[name="modalReserveId"]').val(muReserveId);
						
						// 예약일자
						parentTarget.find('input[name="modalReserveDate"]').val(reserveDate);
						
						// 예약시간
						parentTarget.find('input[name="modalReserveTime"]').siblings("button").text(reserveTime);
						parentTarget.find('input[name="modalReserveTime"]').val(reserveTime);
						
						// 예약경로
						parentTarget.find('input[name="modalReserveCategoryItemCode"]').siblings("button").text(reserveCategoryItemName);
						parentTarget.find('input[name="modalReserveCategoryItemCode"]').val(reserveCategoryItemCode);
						
						// 진료유형
						parentTarget.find('input[name="modalTreatmentProcedureId"]').val(muTreatmentProcedureId);
						parentTarget.find('input[name="modalTreatmentProcedureName"]').val(treatmentProcedureName);
						
						// 닥터/상담자 콤보 셋팅
						let reserveMemberTarget = parentTarget.find('input[name="modalReserveMemberId"]').next(".select_option_list");
						
						let modalReserveDate = parentTarget.find('input[name="modalReserveDate"]').val();
						let reserveMemberHTML = reserveUpdateModal.setReserveMemberCombo(modalReserveDate, muTreatmentProcedureId);
						reserveMemberTarget.html(reserveMemberHTML);
				
						reserveMemberTarget.find("li.option_list_item").click(function () {
							// 1. 선택값 셋팅
							let selectIdArr = $(this).prop("id").split('_');
							let selectId    = selectIdArr[1];
							let selectName  = $(this).text();
							
							$(this).parent().siblings("button").text(selectName);
							$(this).parent().siblings("input").val(selectId);
						});
						if(reserveMemberId){
							parentTarget.find('input[name="modalReserveMemberId"]').siblings("button").text(reserveMemberName);
							parentTarget.find('input[name="modalReserveMemberId"]').val(reserveMemberId);
						}
						// 예약메모
						parentTarget.find('input[name="modalEtc"]').val(etc);
						
						// 진료중 / 진료완료 또는 수납완료는 수정 불가
						if("Y" == status2){
							parentTarget.find('input').attr("disabled",true);
							parentTarget.find('.select_option_list').siblings('button').attr("disabled",true);
							if("G" == status || "Y" == status){
								$('#reserveUpdateModal .title').text('접수내역');
							}
							$('#reserveUpdateModal .btnSave').text('확인');
						}
					}
				}
				else{
					modalEvent.danger("조회 오류", data.msgDesc);
				}
			},
			error : function(xhr, status, error) {
				modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
			},
			beforeSend:function(){

			},
			complete:function(){

			}
		});
	},
	// tab1 : 저장
	save:function(state) {
		// tab1 : 예약등록
		let muUserId                = $('#reserveUpdateModal #list1 input[name="modalUserId"]').val();
		let userName                = $('#reserveUpdateModal #list1 input[name="modalUserName"]').val();
		let phoneNumber                = $('#reserveUpdateModal #list1 .modalPhoneNumber').text().replace(/-/g, "");
		let muMemberId              = $('#reserveUpdateModal #list1 input[name="modalMemberId"]').val();
		
		// 예약 정보
		let reserveArray   = new Object();
		
		if(true != fn_emptyCheck(muUserId)){
			modalEvent.warning("수정", "고객 정보가 없습니다.");	
			return;
		}
		
		if(true != fn_emptyCheck(userName)){
			modalEvent.warning("수정", "고객명 정보가 없습니다.");	
			return;
		}
		else{
			if(true != fn_lengthCheck(userName, 255)) {
				modalEvent.warning("수정", "고객명 정보는 255자를 넘을 수 없습니다.");	
				return;
			}
		}
		
		if(true != fn_emptyCheck(muMemberId)){
			modalEvent.warning("수정", "담당자 정보가 없습니다.");	
			return;
		}
		
		// 예약 정보
		let reserveTr = $('#reserveUpdateModal #list1 .reserveRowBox').children('li.modal_table_content');
		let reserveTempArray = new Array();
		for(let i=0 ; i < reserveTr.length; i++){
			let muReserveId             = reserveTr.eq(i).find('input[name="modalReserveId"]').val();
			let reserveDate             = reserveTr.eq(i).find('input[name="modalReserveDate"]').val();
			let reserveTime             = reserveTr.eq(i).find('input[name="modalReserveTime"]').val();
			let reserveCategoryItemCode   = reserveTr.eq(i).find('input[name="modalReserveCategoryItemCode"]').val();
			let reserveCategoryItemName   = reserveTr.eq(i).find('input[name="modalReserveCategoryItemCode"]').siblings('button').text();
			let muTreatmentProcedureId  = reserveTr.eq(i).find('input[name="modalTreatmentProcedureId"]').val();
			let reserveMemberId         = reserveTr.eq(i).find('input[name="modalReserveMemberId"]').val();
			let etc                     = reserveTr.eq(i).find('input[name="modalEtc"]').val();
			
			if(true != fn_emptyCheck(reserveDate)){
				modalEvent.warning("수정", "예약일자 정보가 없습니다.");
				return;
			}
			
			if(true != fn_emptyCheck(reserveTime)){
				modalEvent.warning("수정", "예약시간 정보가 없습니다.");
				return;
			}
			
			if(true != fn_emptyCheck(reserveCategoryItemCode)){
				modalEvent.warning("수정", "예약경로 정보가 없습니다.");
				return;
			}
			
			if(true != fn_emptyCheck(muTreatmentProcedureId)){
				modalEvent.warning("수정", "진료유형 정보가 없습니다.");	
				return;
			}
			
			if(true != fn_emptyCheck(reserveMemberId)){
				modalEvent.warning("수정", "닥터/상담자 정보가 없습니다.");
				return;
			}
			
			let arr_sub = new Object();
			arr_sub.muReserveId            = muReserveId;
			arr_sub.reserveDate            = reserveDate;
			arr_sub.reserveTime            = reserveTime;
			arr_sub.reserveCategoryItemCode  = reserveCategoryItemCode;
			arr_sub.reserveCategoryItemName  = reserveCategoryItemName;
			arr_sub.muTreatmentProcedureId = muTreatmentProcedureId;
			arr_sub.reserveMemberId        = reserveMemberId;
			arr_sub.etc                    = etc;
			reserveTempArray.push(arr_sub);
			
			reserveArray.data = reserveTempArray;
		}
		
		modalEvent.info("수정", "예약 정보를 수정하시겠습니까?", function(){
			let formData = new FormData();
			formData.append("menuClass", menuClass);
			formData.append("muUserId", muUserId);
			formData.append("userName", userName);
			formData.append("phoneNumber", phoneNumber);
			formData.append("muMemberId", muMemberId);
			formData.append("reserveRows",JSON.stringify(reserveArray));
	
			$.ajax({
				url: encodeURI('/webreserve/updateReserve.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(){
							if( reserveUpdateModal.callback )  {
								reserveUpdateModal.callback();
							}
							reserveUpdateModal.close();
						});
					}
					else{
						modalEvent.danger("수정 오류", data.msgDesc);
					}
				},
				error : function(xhr, status, error) {
					modalEvent.danger("수정 오류", "수정 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
				},
				beforeSend:function(){
					
				},
				complete:function(){
					
				}
			});
		});
	},
	/*
	 * 팝업
	 * callback : 콜백함수, reqParam: 팝업파라미터
	 */
	popup:function(callback, reqParam) {
		// 초기화 후 열기
		reserveUpdateModal.init();
		
		//콜백함수 지정.
		reserveUpdateModal.callback = callback;
		reserveUpdateModal.reqParam = reqParam;
		reserveUpdateModal.dataList = null;
		
		reserveUpdateModal.search();
		
		setTimeout(function(){
			$('#reserveUpdateModal').modal({keyboard:false, backdrop:'static'});
		}, 200);
	},
	/*
	 * 팝업 닫기
	 */
	close:function() {
		$('#reserveUpdateModal').modal('hide');
		
		setTimeout(function(){
			$('#reserveUpdateModal').remove();
		},500);
	},
	HtmlTemplate : `
	<div id="reserveUpdateModal" class="modal reservation_modal fade" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<p class="title">예약수정</p>
				</div>
	
				<div class="modal-body">
					<div class="tab-content">
						<div role="tabpanel" class="tab-pane active" id="list1">
							<div class="form_box">
								<div class="input_box first">
									<label>고객</label>
									<div class="search_box" data-toggle="modal" data-target=".client_inquiry" style="transition: all 0.2s ease-in-out 0s;">
										<img src="/image/web/search_B.svg" alt="search"/>
										<input type="hidden" name="modalUserId" />
										<input type="text" name="modalUserName" placeholder="검색 (고객명, 연락처, 생년월일)" readonly/>
									</div>
								</div>

								<ul class="modal_table_box">
									<li class="modal_table_title">
										<p>고객등급</p>
										<p>생년월일</p>
										<p>성별</p>
										<p>국적</p>
										<p>연락처</p>
										<p>특이사항</p>
									</li>
									<li class="modal_table_content">
										<p class="modalUserType">-</p>
										<p class="modalBirthday">-</p>
										<p class="modalGender">-</p>
										<p class="modalNationality">-</p>
										<p class="modalPhoneNumber">-</p>
										<p class="modalMemo">-</p>
									</li>
								</ul>

								<ul class="modal_table_box last reserveRowBox">
									<li class="modal_table_title">
										<p>예약일시</p>
										<p>예약경로</p>
										<p>진료유형</p>
										<p>닥터/상담</p>
										<p>예약메모</p>
									</li>
								</ul>

								<!-- <div class="button_box">
									<button class="btnReserveAdd">
										<img src="/image/web/add1.svg" alt="예약추가" alt="예약추가"/>
										예약 추가
									</button>
								</div> -->

								<div class="input_box">
									<label>담당자</label>
									<input type="hidden" name="modalMemberId"/>
									
									<div class="search_box member_box" style="display:none;">
										<img src="/image/web/search_B.svg" alt="search"/>
										<input type="text" name="modalMemberName" readonly style="padding-left: 40px;"/>
										<button class="cancel_btn" style="position: relative; font-size: 14px; font-weight: 700; color: rgb(57, 133, 234); padding: 0px 10px; background: none;">취소</button>
									</div>
									
									<div class="read_box">
										<input type="text" name="modalMemberName" placeholder="" disabled>
										<button class="manager_btn"><img src="/image/web/menu_6_off.svg" alt="수정하기"></button>
									</div>
								</div>
							</div>
							
							<div class="form_footer_box">
								<div class="btn_box">
									<button type="button" class="cancel_btn btnCancle">취소</button>
									<button type="button" class="registration_bth btnSave">저장</button>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
    `
};