/** * 섭취챌린지 알림설정 관련 JavaScript * * 이 파일은 섭취챌린지 알림설정 기능을 구현한 JavaScript 파일입니다. * 주요 기능: * 1. 알림 시간 설정 - 타임피커를 통해 시간, 분, 오전/오후 설정 * 2. 알림 활성화/비활성화 - 토글 스위치를 통한 알림 설정 관리 * 3. 미완료 알림 설정 - 섭취 미완료 시 알림 설정 기능 * 4. 서버 통신 - AJAX를 통한 알림 설정 정보 저장 및 조회 * * 사용 방법: * - 페이지 로드 시 자동으로 초기화되어 기존 알림 설정을 불러옴 * - 사용자가 알림 시간을 변경하면 서버에 자동으로 저장됨 * - 알림 토글 변경 시 즉시 서버에 반영됨 * */ const Intakchl = (() => { // 전역 변수 let currentNotificationId = null; let contextPath = ''; // 초기화 function init() { setupTimepicker(); setupHeaderTitle(); initializeAlerts(); initializeIncompleteNotification(); setupMainAlarmToggle(); renderTimeNotifications(); // MicroModal 초기화 추가 if(typeof MicroModal !== 'undefined') { MicroModal.init({ disableScroll: true, awaitCloseAnimation: true }); } else { console.error('MicroModal 라이브러리가 로드되지 않았습니다'); } } // 헤더 타이틀 설정 function setupHeaderTitle() { $(".header__title").text("알림설정"); } // 알림 메시지 초기화 function initializeAlerts() { if (notificationData.alertMessage) { showCustomAlert(notificationData.alertMessage); if (notificationData.goBack === 'Y') { $('#modal-alert .microModal__btn-primary').on('click', function() { window.history.back(); }); } } } // 미완료 알림 설정 초기화 function initializeIncompleteNotification() { if (notificationData.incompleteNotification) { const useAt = notificationData.incompleteNotification.useAt === "Y"; $("#mainAlarmToggle").prop("checked", useAt); } } // 메인 알림 토글 설정 function setupMainAlarmToggle() { $("#mainAlarmToggle").on("change", function() { updateIncompleteNotification($(this).is(":checked") ? "Y" : "N"); }); } // 타임피커 설정 function setupTimepicker() { // 시간 옵션 생성 const hourSelect = document.getElementById('hour-select'); hourSelect.innerHTML = ''; for (let i = 1; i <= 12; i++) { const option = document.createElement('option'); option.value = i.toString().padStart(2, '0'); option.textContent = i.toString().padStart(2, '0'); hourSelect.appendChild(option); } // 분 옵션 생성 const minuteSelect = document.getElementById('minute-select'); minuteSelect.innerHTML = ''; for (let i = 0; i < 60; i += 10) { const option = document.createElement('option'); option.value = i.toString().padStart(2, '0'); option.textContent = i.toString().padStart(2, '0'); minuteSelect.appendChild(option); } // 셀렉트 박스가 포커스를 잃었을 때 원래 값으로 돌아가기 ['ampm', 'hour', 'minute'].forEach(type => { const select = document.getElementById(`${type}-select`); select.addEventListener('blur', () => updateValue(type)); }); } // 타임피커 값 조정 function adjustValue(type, direction) { const elem = document.getElementById(type); const select = document.getElementById(`${type}-select`); if (type === 'ampm') { // 오전/오후 전환 elem.textContent = elem.textContent === '오전' ? '오후' : '오전'; } else if (type === 'hour') { // 1~12 사이에서 순환 let currentValue = parseInt(elem.textContent, 10); currentValue = (currentValue + direction + 12 - 1) % 12 + 1; elem.textContent = currentValue.toString().padStart(2, '0'); } else if (type === 'minute') { // 0~50 사이에서 10분 단위로 순환 let currentValue = parseInt(elem.textContent, 10); currentValue = (currentValue + direction * 10 + 60) % 60; elem.textContent = currentValue.toString().padStart(2, '0'); } } // 셀렉트 박스 표시 function showSelect(type) { const elem = document.getElementById(type); const select = document.getElementById(`${type}-select`); elem.style.display = 'none'; select.style.display = 'inline-block'; select.value = elem.textContent; select.focus(); } // 선택된 값으로 업데이트 function updateValue(type) { const elem = document.getElementById(type); const select = document.getElementById(`${type}-select`); elem.textContent = select.value; elem.style.display = 'inline-block'; select.style.display = 'none'; } // 미완료 알림 설정 업데이트 function updateIncompleteNotification(useAt) { if (notificationData.incompleteNotification) { $.ajax({ url: `${contextPath}/sopmal/bnft/updateIntakeChallengeIncompleteNotification`, type: "POST", data: JSON.stringify({ bnfPushEvtSetupInnb: notificationData.incompleteNotification.bnfPushEvtSetupInnb, useAt: useAt }), contentType: "application/json", success: function(response) { try { const result = JSON.parse(response.resBody.result); if (result.success) { showCustomAlert("알림 설정이 변경되었습니다."); } else { showCustomAlert("알림 설정 변경에 실패했습니다."); $("#mainAlarmToggle").prop("checked", useAt == "Y" ? false : true); } } catch (e) { console.error("응답 처리 중 오류 발생:", e); showCustomAlert("알림 설정 변경에 실패했습니다."); $("#mainAlarmToggle").prop("checked", useAt == "Y" ? false : true); } }, error: function() { showCustomAlert("알림 설정 변경 중 오류가 발생했습니다."); $("#mainAlarmToggle").prop("checked", useAt == "Y" ? false : true); } }); } } // 시간 알림 목록 렌더링 function renderTimeNotifications() { const alarmList = $(".alarmList"); alarmList.empty(); if (notificationData.timeNotifications && notificationData.timeNotifications.length > 0) { notificationData.timeNotifications.forEach(notification => { const li = $("
  • "); const time = notification.ntcnTme; const useAt = notification.useAt === "Y"; const id = notification.bnfNtkNtcnInnb; li.append('' + formatTime(time) + ''); li.append( '
    ' + '' + '
    ' ); alarmList.append(li); }); } // 시간 토글 변경 이벤트 바인딩 $(".time-toggle").on("change", function() { const id = $(this).data("id"); const useAt = $(this).is(":checked") ? "Y" : "N"; const time = $('a[data-id="' + id + '"]').data("time"); updateTimeNotification(id, useAt, time); }); // 시간 설정 모달 설정 - 이벤트 버블링 방지 추가 $("[data-micromodal-trigger='modal-1']").on("click", function(e) { e.preventDefault(); // 기본 동작 방지 e.stopPropagation(); // 이벤트 버블링 방지 const id = $(this).data("id"); const time = $(this).data("time"); setupTimeModal(id, time); MicroModal.show('modal-1'); }); } // 시간 표시 포맷 (HH:MM -> 오전/오후 HH:MM) function formatTime(timeStr) { if (!timeStr) return ""; const [hours, minutes] = timeStr.split(":"); const hour = parseInt(hours, 10); if (hour < 12) { return '오전 ' + (hour == 0 ? '12' : hour) + ':' + minutes; } else { return '오후 ' + (hour == 12 ? '12' : hour - 12) + ':' + minutes; } } // 시간 알림 업데이트 function updateTimeNotification(id, useAt, ntcnTme) { // bnfInnb 파라미터 추출 const urlParams = new URLSearchParams(window.location.search); const bnfInnb = urlParams.get('bnfInnb'); // 로그 출력 console.log('[알림 설정] bnfInnb 파라미터:', bnfInnb); // 매개변수 검증 추가 if (!id) { console.error("알림 ID가 누락되었습니다"); return; } // useAt이 없으면 현재 토글 상태에서 가져옴 if (useAt === undefined) { useAt = $('input[data-id="' + id + '"]').is(":checked") ? "Y" : "N"; } // ntcnTme이 없으면 현재 시간 데이터에서 가져옴 if (!ntcnTme) { ntcnTme = $('a[data-id="' + id + '"]').data("time"); } $.ajax({ url: `${contextPath}/sopmal/bnft/updateIntakeChallengeNotification`, type: "POST", data: JSON.stringify({ bnfNtkNtcnInnb: id, useAt: useAt, ntcnTme: ntcnTme, bnfInnb: bnfInnb }), contentType: "application/json", success: function(response) { try { // resBody.result가 문자열로 된 JSON이므로 파싱 필요 const result = JSON.parse(response.resBody.result); if (result.success) { // 성공적으로 업데이트 됨 } else { showCustomAlert("알림 설정 변경에 실패했습니다."); $('input[data-id="' + id + '"]').prop("checked", useAt == "Y" ? false : true); } } catch (e) { console.error("응답 처리 중 오류 발생:", e); showCustomAlert("알림 설정 변경에 실패했습니다."); $('input[data-id="' + id + '"]').prop("checked", useAt == "Y" ? false : true); } }, error: function() { showCustomAlert("알림 설정 변경 중 오류가 발생했습니다."); $('input[data-id="' + id + '"]').prop("checked", useAt == "Y" ? false : true); } }); } // 시간 설정 모달 초기화 function setupTimeModal(id, timeStr) { currentNotificationId = id; if (!timeStr) return; const [hours, minutes] = timeStr.split(":"); const hour = parseInt(hours, 10); // 오전/오후 설정 const ampm = hour < 12 ? "오전" : "오후"; $("#ampm").text(ampm); // 시간 설정 (12시간제) const hour12 = hour == 0 ? 12 : (hour > 12 ? hour - 12 : hour); $("#hour").text(hour12.toString().padStart(2, '0')); // 분 설정 $("#minute").text(minutes); // 모달 저장 버튼 이벤트 바인딩 수정 $("#modal-1 .btn.lg.full.theme").off("click").on("click", function(e) { e.preventDefault(); // 기본 동작 방지 e.stopPropagation(); // 이벤트 버블링 방지 saveTimeNotification(); // 여기서 모달 닫기는 saveTimeNotification 성공 시 내부에서 처리됨 }); } // 시간 설정 저장 function saveTimeNotification() { if (!currentNotificationId) return; // bnfInnb 파라미터 추출 const urlParams = new URLSearchParams(window.location.search); const bnfInnb = urlParams.get('bnfInnb'); const ampm = $("#ampm").text(); let hour = parseInt($("#hour").text(), 10); const minute = $("#minute").text(); // 24시간제로 변환 if (ampm === "오후" && hour !== 12) { hour += 12; } else if (ampm === "오전" && hour === 12) { hour = 0; } const timeStr = hour.toString().padStart(2, '0') + ':' + minute; // 현재 토글 상태 가져오기 const useAt = $('input[data-id="' + currentNotificationId + '"]').is(":checked") ? "Y" : "N"; $.ajax({ url: `${contextPath}/sopmal/bnft/updateIntakeChallengeNotification`, type: "POST", data: JSON.stringify({ bnfNtkNtcnInnb: currentNotificationId, ntcnTme: timeStr, useAt: useAt, // 토글 상태 추가 bnfInnb: bnfInnb }), contentType: "application/json", success: function(response) { try { // resBody.result가 문자열로 된 JSON이므로 파싱 필요 const result = JSON.parse(response.resBody.result); if (result.success) { // 시간 표시 업데이트 $('a[data-id="' + currentNotificationId + '"]').text(formatTime(timeStr)); $('a[data-id="' + currentNotificationId + '"]').data("time", timeStr); MicroModal.close('modal-1'); // 성공 시 모달 닫기 // 디버깅용 알림 추가 console.log("알림 시간이 변경되었습니다: " + formatTime(timeStr)); } else { showCustomAlert("알림 시간 변경에 실패했습니다."); } } catch (e) { console.error("응답 처리 중 오류 발생:", e); showCustomAlert("알림 시간 변경에 실패했습니다."); } }, error: function() { showCustomAlert("알림 시간 변경 중 오류가 발생했습니다."); } }); } // 기본 알림시간 초기화 function resetDefaultTimes() { if (confirm('알림 시간을 기본값으로 초기화하시겠습니까?')) { $.ajax({ url: `${contextPath}/sopmal/bnft/resetDefaultNotificationTimes`, type: 'POST', contentType: 'application/json', data: JSON.stringify({}), success: function(response) { try { // resBody.result가 문자열로 된 JSON이므로 파싱 필요 const result = JSON.parse(response.resBody.result); if (result.success) { showCustomAlert('알림 시간이 기본값으로 초기화되었습니다.'); window.location.reload(); } else { showCustomAlert('알림 시간 초기화에 실패했습니다.'); } } catch (e) { console.error("응답 처리 중 오류 발생:", e); showCustomAlert('알림 시간 초기화에 실패했습니다.'); } }, error: function() { showCustomAlert('알림 시간 초기화 중 오류가 발생했습니다.'); } }); } } // 개별 알림 삭제 function deleteNotification(id) { if (confirm('이 알림을 삭제하시겠습니까?')) { $.ajax({ url: `${contextPath}/sopmal/bnft/deleteNotification`, type: 'POST', contentType: 'application/json', data: JSON.stringify({ bnfNtkNtcnInnb: id }), success: function(response) { try { // resBody.result가 문자열로 된 JSON이므로 파싱 필요 const result = JSON.parse(response.resBody.result); if (result.success) { showCustomAlert('알림이 삭제되었습니다.'); window.location.reload(); } else { showCustomAlert('알림 삭제에 실패했습니다.'); } } catch (e) { console.error("응답 처리 중 오류 발생:", e); showCustomAlert('알림 삭제에 실패했습니다.'); } }, error: function() { showCustomAlert('알림 삭제 중 오류가 발생했습니다.'); } }); } } // 알림용 모달 표시 함수 function showCustomAlert(message) { // 기존 모달 스타일을 활용한 새로운 알림 모달 $('#modal-alert .microModal__content p').text(message); MicroModal.show('modal-alert'); } // 초기 데이터 설정 function setInitialData(data, path) { notificationData = data; contextPath = path; } // 공개 API return { init, adjustValue, showSelect, updateValue, resetDefaultTimes, deleteNotification, setInitialData, showCustomAlert }; })(); // 페이지 로드 시 초기화 $(document).ready(function() { // 초기화는 JSP에서 데이터 설정 후 호출됨 });