
/* ##############################################################
	설  명 : [Modal]바로접수 등록 팝업
	작성일 : 2023. 01. 19.
	작성자 : NTsoft
	수정일 	        수정자 	 수정내용
	-------         -------- ---------------------------
	2023. 01. 19.	NTsoft 	 최초 생성
*/
let reserveReadyInsertModal = {
	callback : null,
	reqParam : null,
	dataList : null,
	/* 모달 초기화 작업 */
	init : function () {
		$('#reserveReadyInsertModal').remove();
		$('body').append( this.HtmlTemplate);
		//그리드 이벤트
		this.setEvent();
	},
	/* 그리드 이벤트 설정 */
	setEvent:function() {
		$('#reserveReadyInsertModal .btnCancle').on("click", function(){
			reserveReadyInsertModal.close();
		});
		
		// tab1 : 바로접수 등록
		$('#reserveReadyInsertModal #list1 .btnSave').on("click", function(){
			reserveReadyInsertModal.save("I");
		});
		
		// tab1 : 고객조회 팝업
		$('#reserveReadyInsertModal #list1 input[name="modalUserName"]').on("click", function(){
			let reqParam = {};
			userIntroSelectModal.popup(function (obj, reqParam) {
				$('#reserveReadyInsertModal #list1 input[name="modalUserId"]').val(obj.muUserId);
				$('#reserveReadyInsertModal #list1 input[name="modalUserName"]').val(obj.userName);
				
				$('#reserveReadyInsertModal #list1 .modalPhoneNumber').text(fn_setFormatPhone(obj.phoneNumber));
				
				if("T" == obj.userType2){
					// 간편예약 고객
					$('#reserveReadyInsertModal #list1 .modalUserType').html('-');
					$('#reserveReadyInsertModal #list1 .modalBirthday').text('-');
					$('#reserveReadyInsertModal #list1 .modalGender').text('-');
					$('#reserveReadyInsertModal #list1 .modalNationality').text('-');
					$('#reserveReadyInsertModal #list1 .modalMemo').text('-');
				}
				else{
					// 일반고객
					$('#reserveReadyInsertModal #list1 .modalUserType').html('<img src="'+obj.userType.replace("C:", "")+'" alt="고객구분" />');
					$('#reserveReadyInsertModal #list1 .modalBirthday').text(obj.birthday);
					$('#reserveReadyInsertModal #list1 .modalGender').text(obj.gender);
					$('#reserveReadyInsertModal #list1 .modalNationality').text(obj.nationality);
					$('#reserveReadyInsertModal #list1 .modalMemo').text(obj.memo);
				}
			}, reqParam);
		});
		
		// tab1 : 담당자 수정하기 이벤트
		$('#reserveReadyInsertModal #list1 .manager_btn').on("click", function(){
			$('#reserveReadyInsertModal #list1 .read_box').hide();
			$('#reserveReadyInsertModal #list1 .search_box.member_box').show();
		});
		
		// tab1 : 담당자 수정 취소하기 이벤트
		$('#reserveReadyInsertModal #list1 .cancel_btn').on("click", function(){
			$('#reserveReadyInsertModal #list1 .read_box').show();
			$('#reserveReadyInsertModal #list1 .search_box.member_box').hide();
		});
		
		// tab1 : 담당자 변경 이벤트
		let modalMemberTarget = $('#reserveReadyInsertModal #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);
		});
	},
	/* 예약경로 콤보데이터 설정 (동적추가) */
	setReserveCategoryCombo:function() {
		let category = fn_selectCategoryList2();
		let reservationCategory = category.find(cat => cat.categoryName === '예약경로');

		if (reservationCategory) {
			fn_selectModalOtherOption2(reservationCategory.categoryCode);
		}
		// 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;
	},
	/* 닥터/상담 콤보데이터 설정 (동적추가) */
	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 += '		<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" class="txt" 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>';
		$('#reserveReadyInsertModal #list1 .reserveRowBox').append(addRowHtml).trigger("create");
		reserveReadyInsertModal.setReserveCategoryCombo();
		// 현재 row
		let parentTarget = $('#reserveReadyInsertModal #list1 .modal_table_content:last');
		
		// 예약 일자
		parentTarget.find('input[name="modalReserveDate"]').datetimepicker({
			allowInputToggle: true,
			format: 'YYYY-MM-DD',
			defaultDate: moment()
		}).on("dp.change", function(e){
			// 날짜가 변경될 때 실행
			// console.log(e.oldDate.format("YYYY-MM-DD"));
			// console.log(e.date.format("YYYY-MM-DD"));

			// 예약 시간 셋팅
			fn_searchSetTime('reserveReadyInsertModal #list1 .modal_table_content:last .select_option_list.time', e.date.format("YYYY-MM-DD"));

			// 초기화
			// 예약경로
			$("#reserveReadyInsertModal #list1 [name=modalReserveCategoryItemCode]").val("");
			$("#reserveReadyInsertModal #list1 [name=modalReserveCategoryItemCode]").siblings("button").text("예약경로");
			// 진로유형
			$("#reserveReadyInsertModal #list1 [name=modalTreatmentProcedureId]").val("");
			$("#reserveReadyInsertModal #list1 [name=modalTreatmentProcedureName]").val("");
			// 닥터/상담
			$("#reserveReadyInsertModal #list1 [name=modalReserveMemberId]").val("");
			$("#reserveReadyInsertModal #list1 [name=modalReserveMemberId]").siblings("button").text("닥터/상담");
			$("#reserveReadyInsertModal #list1 [name=modalReserveMemberId]").siblings("ul").find("li").remove();
			// 예약메모
			$("#reserveReadyInsertModal #list1 [name=modalEtc]").val("");
		});
		parentTarget.find('input[name="modalReserveDate"]').data("DateTimePicker").minDate(fn_getToDate());
		
		let selectDate = $('#reserveReadyInsertModal #list1').find('input[name="modalReserveDate"]').val();
	    // 예약 시간 셋팅
		fn_searchSetTime('reserveReadyInsertModal #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 = reserveReadyInsertModal.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( reserveReadyInsertModal.callback )  {
			reserveReadyInsertModal.callback(checkedData);
		}
		reserveReadyInsertModal.close();
	},
	// 고객 조회
	searchUser:function(state) {
		let muUserId = reserveReadyInsertModal.reqParam.muUserId;

		if(true != fn_emptyCheck(muUserId)){
			modalEvent.warning("", "고객 정보가 없습니다.");
			return;
		}
		
		let formData = new FormData();
		formData.append("menuClass", menuClass);
		formData.append("muUserId", muUserId);

		$.ajax({
			url: encodeURI('/webuser/selectUser.do'),
			data: formData,
			dataType: "json",
			processData: false,
			contentType: false,
			type: 'POST',
			async: true,
			success: function(data){
				if('0'==data.msgCode){
					$('#reserveReadyInsertModal #list1 input[name="modalUserId"]').val(data.userDetail[0].muUserId);
					$('#reserveReadyInsertModal #list1 input[name="modalUserName"]').val(data.userDetail[0].userName);
					
					$('#reserveReadyInsertModal #list1 .modalPhoneNumber').text(fn_setFormatPhone(data.userDetail[0].phoneNumber));
					
					if("T" == data.userDetail[0].userType2){
						// 간편예약 고객
						$('#reserveReadyInsertModal #list1 .modalUserType').html('-');
						$('#reserveReadyInsertModal #list1 .modalBirthday').text('-');
						$('#reserveReadyInsertModal #list1 .modalGender').text('-');
						$('#reserveReadyInsertModal #list1 .modalNationality').text('-');
						$('#reserveReadyInsertModal #list1 .modalMemo').text('-');
					}
					else{
						// 일반고객
						$('#reserveReadyInsertModal #list1 .modalUserType').html('<img src="'+data.userDetail[0].filePath+'" alt="고객구분" />');
						$('#reserveReadyInsertModal #list1 .modalBirthday').text(data.userDetail[0].birthday);
						$('#reserveReadyInsertModal #list1 .modalGender').text(data.userDetail[0].gender);
						$('#reserveReadyInsertModal #list1 .modalNationality').text(data.userDetail[0].nationalityName);
						$('#reserveReadyInsertModal #list1 .modalMemo').text(data.userDetail[0].memo);
					}
					
				}
				else{
					modalEvent.danger("조회 오류", data.msgDesc);
				}
			},
			error : function(xhr, status, error) {
				modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
			},
			beforeSend:function(){

			},
			complete:function(){

			}
		});
	},
	save:function(state) {
		// tab1 : 바로접수
		let muUserId                = $('#reserveReadyInsertModal #list1 input[name="modalUserId"]').val();
		let userName                = $('#reserveReadyInsertModal #list1 input[name="modalUserName"]').val();
		let reserveDate             = $('#reserveReadyInsertModal #list1 input[name="modalReserveDate"]').val();
		let reserveTime             = $('#reserveReadyInsertModal #list1 input[name="modalReserveTime"]').val();
		let reserveCategoryItemCode = $('#reserveReadyInsertModal #list1 input[name="modalReserveCategoryItemCode"]').val();
		let reserveCategoryItemName = $('#reserveReadyInsertModal #list1 input[name="modalReserveCategoryItemCode"]').siblings('button').text();
		let muTreatmentProcedureId  = $('#reserveReadyInsertModal #list1 input[name="modalTreatmentProcedureId"]').val();
		let reserveMemberId         = $('#reserveReadyInsertModal #list1 input[name="modalReserveMemberId"]').val();
		let etc                     = $('#reserveReadyInsertModal #list1 input[name="modalEtc"]').val();
		let muMemberId              = $('#reserveReadyInsertModal #list1 input[name="modalMemberId"]').val();
		
		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(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;
		}
		
		if(true != fn_emptyCheck(muMemberId)){
			modalEvent.warning("등록", "담당자 정보가 없습니다.");	
			return;
		}
		
		modalEvent.info("등록", "바로접수 정보를 등록하시겠습니까?", function(){
			let formData = new FormData();
			formData.append("menuClass", menuClass);
			formData.append("muUserId", muUserId);
			formData.append("userName", userName);
			formData.append("reserveDate", reserveDate);
			formData.append("reserveTime", reserveTime);
			formData.append("reserveCategoryItemCode", reserveCategoryItemCode);
			formData.append("reserveCategoryItemName", reserveCategoryItemName);
			formData.append("muTreatmentProcedureId", muTreatmentProcedureId);
			formData.append("reserveMemberId", reserveMemberId);
			formData.append("etc",etc);
			formData.append("muMemberId",muMemberId);
	
			$.ajax({
				url: encodeURI('/webreserve/insertReserveReady.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( reserveReadyInsertModal.callback )  {
								reserveReadyInsertModal.callback();
							}
							reserveReadyInsertModal.close();
						});
					}
					else{
						modalEvent.danger("등록 오류", data.msgDesc);
					}
				},
				error : function(xhr, status, error) {
					modalEvent.danger("등록 오류", "등록 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
				},
				beforeSend:function(){
					
				},
				complete:function(){
					
				}
			});
		});
	},
	/*
	 * 팝업
	 * callback : 콜백함수, reqParam: 팝업파라미터
	 */
	popup:function(callback, reqParam) {
		// 초기화 후 열기
		reserveReadyInsertModal.init();
		
		//콜백함수 지정.
		reserveReadyInsertModal.callback = callback;
		reserveReadyInsertModal.reqParam = reqParam;
		reserveReadyInsertModal.dataList = null;
		
		// tab1 : 예약
		reserveReadyInsertModal.addRow();
		
		// 담당자
		$('#reserveReadyInsertModal input[name="modalMemberId"]').val(loginMemberId);
		$('#reserveReadyInsertModal input[name="modalMemberName"]').val(loginMemberName);
		
		let muUserId = reserveReadyInsertModal.reqParam.muUserId;
		
		if(null==muUserId||''==muUserId){
			
		}
		else{
			reserveReadyInsertModal.searchUser();
		}
		
		setTimeout(function(){
			$('#reserveReadyInsertModal').modal({keyboard:false, backdrop:'static'});
		}, 200);
	},
	/*
	 * 팝업 닫기
	 */
	close:function() {
		$('#reserveReadyInsertModal').modal('hide');
		
		setTimeout(function(){
			$('#reserveReadyInsertModal').remove();
		},500);
	},
	HtmlTemplate : `
	<div id="reserveReadyInsertModal" 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="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>
    `
};