
/* ##############################################################
	설  명 : [Modal]상담차트 상세/저장 팝업
	작성일 : 2023. 01. 19.
	작성자 : NTsoft
	수정일 	        수정자 	 수정내용
	-------         -------- ---------------------------
	2023. 01. 19.	NTsoft 	 최초 생성
*/
let userConsultingChartUpdateModal = {
	callback : null,
	reqParam : null,
	dataList : null,
	/* 모달 초기화 작업 */
	init : function () {
		$('#userConsultingChartUpdateModal').remove();
		$('body').append( this.HtmlTemplate);
		//그리드 이벤트
		this.setEvent();
	},
	/* 그리드 이벤트 설정 */
	setEvent:function() {
		$('#userConsultingChartUpdateModal .btnCancle').on("click", function(){
			userConsultingChartUpdateModal.close();
		});

		$('#userConsultingChartUpdateModal .btnSave').on("click", function(){
			userConsultingChartUpdateModal.save("I");
		});
		$('#userConsultingChartUpdateModal .more_btn').on("click", function(){
			fn_selectConsultingMenuCode();
		});


		$("#userConsultingChartUpdateModal input[name='modalReserveDate']").datetimepicker({
			allowInputToggle: true,
			format: 'YYYY-MM-DD',
			defaultDate: moment()
		});


		$("#userConsultingChartUpdateModal input[name='modalPushDate']").datetimepicker({
			allowInputToggle: true,
			format: 'YYYY-MM-DD',
			defaultDate: moment()
		});

		// 시술 선택 이벤트
		let treatmentProcedureTarget = $('#userConsultingChartUpdateModal 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 = $('#userConsultingChartUpdateModal input[name="modalReserveMemberId"]').next(".select_option_list");

				let modalReserveDate = $('#userConsultingChartUpdateModal input[name="modalReserveDate"]').val();
				let reserveMemberHTML = userConsultingChartUpdateModal.setReserveMemberDoctorCombo(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);
		});

		// 진료 예약 이벤트
		$('#userConsultingChartUpdateModal .reserve_bth').on("click", function(){
			userConsultingChartUpdateModal.reserveSave();
		});

		// 진료 예약 이벤트
		$('#userConsultingChartUpdateModal .send_bth').on("click", function(){
			userConsultingChartUpdateModal.smsSave();
		});

        $('#userConsultingChartUpdateModal #smsContent').on("keyup", function(){
            fn_getByteText(this, 2000);
        });
	},
	/* 닥터 콤보데이터 설정 (동적추가) */
	setReserveMemberDoctorCombo: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 type       = comboData[i].type;
			let typeName   = comboData[i].typeName;

			if("D" == type){
				comboHTML += '<li id="li_'+muMemberId+'" class="option_list_item">'+typeName+' '+memberName+'</li>';
			}
		}
		return comboHTML;
	},
	/* 데이터 선택 */
	setSelect:function(selectNumber) {
		let checkedData = dataList[selectNumber];
		if(dataList==null||checkedData==undefined){
			return ;
		}

		if( userConsultingChartUpdateModal.callback )  {
			userConsultingChartUpdateModal.callback(checkedData);
		}
		userConsultingChartUpdateModal.close();
	},
	// 상세 조회
	search:function(state) {
		let muUserConsultingChartId = userConsultingChartUpdateModal.reqParam.muUserConsultingChartId;
		let muUserId                = userConsultingChartUpdateModal.reqParam.muUserId;

		if(true != fn_emptyCheck(muUserConsultingChartId)){
			modalEvent.warning("저장", "상담차트 정보가 없습니다.");
			return;
		}

		if(true != fn_emptyCheck(muUserId)){
			modalEvent.warning("저장", "고객 정보가 없습니다.");
			return;
		}

		let formData = new FormData();
		formData.append("muUserConsultingChartId", muUserConsultingChartId);
		formData.append("muUserId", muUserId);

		$.ajax({
			url: encodeURI('/webuserconsultingchart/selectUserConsultingChart.do'),
			data: formData,
			dataType: "json",
			processData: false,
			contentType: false,
			type: 'POST',
			async: true,
			success: function(data){
				if('0'==data.msgCode){
					// 고객 인적사항
					$('#userConsultingChartUpdateModal input[name="modalUserId"]').val(data.rows[0].muUserId);
					$('#userConsultingChartUpdateModal .modalUserName').text(data.rows[0].userName);

					$('#userConsultingChartUpdateModal .modalBirthday').text(data.rows[0].birthday);
					$('#userConsultingChartUpdateModal .modalAge').text(data.rows[0].age);
					$('#userConsultingChartUpdateModal .modalGender').text(data.rows[0].gender);
					$('#userConsultingChartUpdateModal .modalNationality').text(data.rows[0].nationality);
					$('#userConsultingChartUpdateModal .modalUserType').html(data.rows[0].userType?'<img src="'+data.rows[0].userType.replace("C:", "")+'" alt="고객구분" />':'-');
					$('#userConsultingChartUpdateModal .modalPhoneNumber').text(fn_setFormatPhone(data.rows[0].phoneNumber));
					$('#userConsultingChartUpdateModal textarea[name="modalEtc"]').val(data.rows[0].memo);

					// 멤버쉽 충전금액 추가 필요.

					// 최근상담차트 Top5
					let listHTML = '';
					for(let i = 0; i < data.userConsultingChartList.length; i++){
						let writeDate              = data.userConsultingChartList[i].writeDate;
						let treatmentName          = data.userConsultingChartList[i].treatmentName;
						let treatmentProcedureName = data.userConsultingChartList[i].treatmentProcedureName;

						listHTML += '<tr>';
						listHTML += '	<td>'+writeDate+'</td>';
						listHTML += '	<td>'+treatmentName+'</td>';
						listHTML += '	<td>'+treatmentProcedureName+'</td>';
						listHTML += '</tr>';
					}
					$('#userConsultingChartUpdateModal .modalUserConsultingChartTop5List').html(listHTML);

					// 상담차트
					$('#userConsultingChartUpdateModal .modalWriteDate').text(data.rows[0].writeDate);
					$('#userConsultingChartUpdateModal .modalWriteMemberName').text(data.rows[0].writeMemberName);
					$('#userConsultingChartUpdateModal textarea[name="modalContent"]').val(data.rows[0].content);

				}
				else{
					modalEvent.danger("조회 오류", data.msgDesc);
				}
			},
			error : function(xhr, status, error) {
				modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
			},
			beforeSend:function(){

			},
			complete:function(){

			}
		});
	},
	// 저장
	save:function(state) {
		let muUserConsultingChartId = userConsultingChartUpdateModal.reqParam.muUserConsultingChartId;
		let muUserId                = userConsultingChartUpdateModal.reqParam.muUserId;
		let content                 = $('#userConsultingChartUpdateModal textarea[name="modalContent"]').val();

		if(true != fn_emptyCheck(muUserConsultingChartId)){
			modalEvent.warning("저장", "상담차트 정보가 없습니다.");
			return;
		}

		if(true != fn_emptyCheck(muUserId)){
			modalEvent.warning("저장", "고객 정보가 없습니다.");
			return;
		}

		if(true != fn_emptyCheck(content)){
			modalEvent.warning("저장", "상담 내용 정보가 없습니다.");
			return;
		}

		modalEvent.info("저장", "상담차트 정보를 저장하시겠습니까?", function(){
			let formData = new FormData();
			formData.append("menuClass", menuClass);
			formData.append("muUserConsultingChartId", muUserConsultingChartId);
			formData.append("muUserId", muUserId);
			formData.append("content", content);

			$.ajax({
				url: encodeURI('/webuserconsultingchart/updateUserConsultingChart.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( userConsultingChartUpdateModal.callback )  {
								userConsultingChartUpdateModal.callback();
							}
							userConsultingChartUpdateModal.close();
						});
					}
					else{
						modalEvent.danger("저장 오류", data.msgDesc);
					}
				},
				error : function(xhr, status, error) {
					modalEvent.danger("저장 오류", "저장 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
				},
				beforeSend:function(){

				},
				complete:function(){

				}
			});
		});
	},
	// 예약 등록
	reserveSave:function(state) {
		let muUserId                = userConsultingChartUpdateModal.reqParam.muUserId;
		let userName                = $('#userConsultingChartUpdateModal .modalUserName').text();
		let muMemberId              = loginMemberId;

		// 예약 정보
		let reserveDate             = $('#userConsultingChartUpdateModal input[name="modalReserveDate"]').val();
		let reserveTime             = $('#userConsultingChartUpdateModal input[name="modalReserveTime"]').val();
		let reserveCategoryItemId   = '';
		let muTreatmentProcedureId  = $('#userConsultingChartUpdateModal input[name="modalTreatmentProcedureId"]').val();
		let reserveMemberId         = $('#userConsultingChartUpdateModal input[name="modalReserveMemberId"]').val();
		let etc                     = '';

		// 예약 정보
		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;
		}

		if(true != fn_emptyCheck(reserveDate)){
			modalEvent.warning("등록", "예약일자 정보가 없습니다.");
			return;
		}

		if(true != fn_emptyCheck(reserveTime)){
			modalEvent.warning("등록", "예약시간 정보가 없습니다.");
			return;
		}

		if(true != fn_emptyCheck(muTreatmentProcedureId)){
			modalEvent.warning("등록", "진료유형 정보가 없습니다.");
			return;
		}

		if(true != fn_emptyCheck(reserveMemberId)){
			modalEvent.warning("등록", "닥터/상담자 정보가 없습니다.");
			return;
		}

		let reserveTempArray = new Array();
		let arr_sub = new Object();
		arr_sub.reserveDate            = reserveDate;
		arr_sub.reserveTime            = reserveTime;
		arr_sub.reserveCategoryItemId  = reserveCategoryItemId;
		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("muMemberId", muMemberId);
			formData.append("reserveRows",JSON.stringify(reserveArray));

			$.ajax({
				url: encodeURI('/webreserve/insertReserve.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( userConsultingChartUpdateModal.callback )  {
								userConsultingChartUpdateModal.callback();
							}
							userConsultingChartUpdateModal.close();*/
						});
					}
					else{
						modalEvent.danger("저장 오류", data.msgDesc);
					}
				},
				error : function(xhr, status, error) {
					modalEvent.danger("저장 오류", "저장 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
				},
				beforeSend:function(){

				},
				complete:function(){

				}
			});
		});
	},
	// 알림 발송
	smsSave:function(state) {
		let muUserId        = userConsultingChartUpdateModal.reqParam.muUserId;

		let smsType         = $("#smsTypeCheck").val();
		let smsSendDate     = $('#userConsultingChartUpdateModal #smsSendDate').val();
		let smsSendTime     = $('#userConsultingChartUpdateModal #smsSendTime').val();
		let smsContent      = $('#userConsultingChartUpdateModal #smsContent').val();

		if(true != fn_emptyCheck(muUserId)){
			modalEvent.warning("등록", "고객 정보가 없습니다.");
			return;
		}

		if(true != fn_emptyCheck(smsSendDate)){
			modalEvent.warning("등록", "발송일자 정보가 없습니다.");
			return;
		}

		if(true != fn_emptyCheck(smsSendTime)){
			modalEvent.warning("등록", "발송시간 정보가 없습니다.");
			return;
		}

		if(true != fn_emptyCheck(smsContent)){
			modalEvent.warning("등록", "내용 정보가 없습니다.");
			return;
		}

		// let text = smsSendDate+" "+smsSendTime+" 알림 발송 정보를 등록하시겠습니까?";


		modalEvent.info("등록", smsSendDate+" "+smsSendTime+" 알림 발송 정보를 등록하시겠습니까?", function(){
			let formData = new FormData();
			formData.append("menuClass", menuClass);
			formData.append("muUserId", muUserId);
			formData.append("smsSendDate", smsSendDate);
			formData.append("smsSendTime", smsSendTime);
			formData.append("smsContent", smsContent);
			formData.append("smsType", smsType);

			$.ajax({
				url: encodeURI('/websms/insertSmsConsultingChart.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( userConsultingChartUpdateModal.callback )  {
								userConsultingChartUpdateModal.callback();
							}
							userConsultingChartUpdateModal.close();*/
						});
					}
					else{
						modalEvent.danger("저장 오류", data.msgDesc);
					}
				},
				error : function(xhr, status, error) {
					modalEvent.danger("저장 오류", "저장 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
				},
				beforeSend:function(){

				},
				complete:function(){

				}
			});
		});
	},
	/*
	 * 팝업
	 * callback : 콜백함수, reqParam: 팝업파라미터
	 */
	popup:function(callback, reqParam) {
		// 초기화 후 열기
		userConsultingChartUpdateModal.init();

		//콜백함수 지정.
		userConsultingChartUpdateModal.callback = callback;
		userConsultingChartUpdateModal.reqParam = reqParam;
		userConsultingChartUpdateModal.dataList = null;


		fn_setTimeValue("selModalReserveTime", "00:00");
		fn_setTimeValue("selSmsSendTime", "00:00");

		setTimeout(function(){
			$('#userConsultingChartUpdateModal').modal({keyboard:false, backdrop:'static'});
		}, 200);

		userConsultingChartUpdateModal.search();

	},
	/*
	 * 팝업 닫기
	 */
	close:function() {
		$('#userConsultingChartUpdateModal').modal('hide');

		setTimeout(function(){
			$('#userConsultingChartUpdateModal').remove();
		},500);
	},
	HtmlTemplate : `
	<div id="userConsultingChartUpdateModal" class="modal charting_modal consulting fade" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="">
			<div class="modal-dialog">
				<div class="modal-content">
					<div class="modal-header"></div>
					<div class="modal-body">
						<div class="charting_left">
							<p class="title modalUserName"></p>
							<ul class="charting_list">
								<li>
									<label>인적사항</label>
									<p>
										<span class="modalBirthday"></span>
										<span class="modalAge"></span>
										<span class="modalGender"></span>
										<span class="modalNationality"></span>
									</p>
								</li>
								<li>
									<label>고객구분</label>
									<p class="modalUserType"></p>
								</li>
								<li>
									<label>연락처</label>
									<p class="modalPhoneNumber"></p>
								</li>
								<li>
									<label>멤버십 충전금</label>
									<p>0</p>
								</li>
							</ul>
							
							<div class="textarea_box">
								<label>특이 사항</label>
								<p class="title_info">*시술 및 약물 관련 특이사항</p>
								<textarea name="modalMemo" placeholder="" readonly></textarea>
							</div>
							
							<div class="table_box">
								<label>상담차트 내역</label>
								
								<table>
									<thead>
										<tr>
											<th>작성일시</th>
											<th>진료 유형</th>
											<th>시술(상품)명</th>
										</tr>
									</thead>
									<tbody class="modalUserConsultingChartTop5List"></tbody>
								</table>
							</div>
							
							<div class="botton_box">
								<button class="more_btn">차트내역 더보기</button>
							</div>
						</div>
						<div class="charting_right">
							<div class="right_top">
								<p class="chart_numder">차트번호 U20220405-0000-A1</p>
								<p class="title">상담 차트</p>
								<div class="right_text">
									<p class="first">
										작성일자
										<span class="modalWriteDate"></span>
									</p>
									<p>
										작성자
										<span class="modalWriteMemberName"></span>
									</p>
								</div>
							</div>
							
							<div class="right_bottom">
								<div class="textarea_box">
									<label>상담 내용</label>
									<textarea name="modalContent" placeholder="상담 내용을 입력해주세요."></textarea>
								</div>
								
								<div class="diagnosis_box">
									<div class="form_box">
										<label>진료예약</label>
										
										<div class="calendar_box">
											<div class="date_box">
												<img src="/image/web/calendar.svg" alt="calendar"/>
												<input type="date" class="date_picker" name="modalReserveDate">
											</div>
										</div>
										
										<div class="select_box dropdown">
											<button class="label" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">00:00</button>
											<input type="hidden" name="modalReserveTime">
				
											<ul class="select_option_list dropdown-menu" id="selModalReserveTime"></ul>
										</div>
										
										<div class="search_box" data-target=".medical_type" style="transition: all 0.2s ease-in-out 0s;">
											<img src="/image/web/search_B.svg" alt="search"/>
											<input type="hidden" name="modalTreatmentProcedureId" />
											<input type="text" name="modalTreatmentProcedureName" placeholder="진료유형" readonly />
										</div>
											
										<div class="select_box dropdown">
											<button class="label" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">닥터</button>
											<input type="hidden" name="modalReserveMemberId">
											<ul class="select_option_list dropdown-menu"></ul>
										</div>
										
										<div class="button_box">
											<button class="reserve_bth"><img src="/image/web/calendar_w.svg" alt="calendar"/>예약 등록</button>
										</div>
									</div>
								</div>
								
								<div class="send_box">
									<div class="form_box">
										<label>알림 발송</label>
										
										<div class="calendar_box">
											<div class="date_box">
												<img src="/image/web/calendar.svg" alt="calendar"/>
												<input type="date" class="date_picker" name="modalPushDate" id="smsSendDate">
											</div>
										</div>
										
										<div class="select_box dropdown">
											<button class="label" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">00:00</button>
											<input type="hidden" name="modalPushTime" id="smsSendTime">
				
											<ul class="select_option_list dropdown-menu" id="selSmsSendTime"></ul>
										</div>
										
										<div class="button_box send_box">
											<button class="send_bth"><img src="/image/web/calendar_w.svg" alt="calendar"/>알림 발송</button>
										</div>
										
										<div class="textarea_box">
											<textarea name="modalPushContent" placeholder="내용을 입력해주세요." id="smsContent"></textarea>
											<input type="hidden" id="smsTypeCheck" value="S">
										</div>
										
										
										
										<div class="button_box">
											<button class="cancel_btn btnCancle">취소</button>
											<button class="save_bth btnSave">저장</button>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	`
};
function fn_selectConsultingMenuCode(){
	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 pagingParam = "?menuClass="+data.menuCode;
				pagingParam    += "&muUserId="+userConsultingChartUpdateModal.reqParam.muUserId;
				fn_leftFormAction("/webuserconsultingchart/selectListUserConsultingChartIntro.do"+pagingParam);
			}
			else{
				modalEvent.danger("조회 오류", data.msgDesc);
			}
		},
		error : function(xhr, status, error) {
			modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
		},
		beforeSend:function(){
		},
		complete:function(){
		}
	});
}