/**
* 이벤트 보기 관련 기능 모듈
*/
const EventView = (function() {
// 비공개 변수
let _bnfInnb = 0; // 혜택 고유번호
let _eventDesc = ''; // 이벤트 설명
let _loadingTime = 0; // 로딩 시간(초)
let _mileageAmount = 0; // 마일리지 금액
let _timer = null; // 타이머 객체
let _countdownValue = 0; // 카운트다운 값
let _isParticipated = false;// 참여 여부
let _eventUrl = ''; // 이벤트 URL
let _reviewCheckInterval; // 모달이 열려있는지 확인하는 인터벌
/**
* 토스트 메시지 표시 함수
* @param {string} message - 표시할 메시지
*/
function _showToast(message) {
// 기존에 토스트 요소가 있으면 제거
$('.toastPop').remove();
// 토스트 요소 생성 및 추가
const $toast = $('
' + message + '
');
$('body').append($toast);
// 토스트 표시 및 자동 제거
setTimeout(function() {
$toast.addClass('show');
setTimeout(function() {
$toast.removeClass('show');
// 애니메이션 완료 후 요소 제거
setTimeout(function() {
$toast.remove();
}, 300);
}, 2000);
}, 100);
}
/**
* 이벤트 모달 생성 함수
*/
function _createEventModal() {
// 기존 모달이 있다면 제거
$('#event-modal').remove();
// 모달 HTML 구조 생성
const modalHTML = `
`;
// 모달을 페이지에 추가
$('body').append(modalHTML);
// 모달 닫기 버튼에 이벤트 핸들러 직접 연결
$('#event-modal-close-btn, .eventModal__close').on('click', function() {
_closeEventModal();
});
}
/**
* 이벤트 모달 닫기 함수
*/
function _closeEventModal() {
console.log('이벤트 모달 닫기 함수 호출');
// jQuery를 사용하여 모달 직접 닫기
$('#event-modal').fadeOut(300, function() {
// 모달이 완전히 닫힌 후 iframe 소스 비우기
$('#eventIframe').attr('src', 'about:blank');
});
// 타이머 정지
if (_timer) {
clearInterval(_timer);
}
if (_reviewCheckInterval) {
clearInterval(_reviewCheckInterval);
}
// 남은 시간이 없으면 마일리지 적립
if (_countdownValue <= 0) {
_participateEvent();
_showToast('이벤트 보기 완료! 마일리지가 적립되었습니다.');
}
}
// 타이머 시작 함수
function _startTimer() {
// 이미 참여했는지 확인
_checkParticipationAvailable().then(function(available) {
if (!available) {
_isParticipated = true;
showCustomAlert("이미 참여한 이벤트입니다.");
// 이미 참여한 경우 UI 업데이트
_updateUIForCompletedEvent();
return;
}
// 모달 생성
_createEventModal();
// URL을 iframe에 로드
$('#eventIframe').attr('src', _eventUrl);
$('#event-modal').fadeIn(300);
// 카운트다운 표시 업데이트
_countdownValue = _loadingTime;
_updateTimerDisplay();
// 카운트다운 타이머 시작
_timer = setInterval(function() {
_countdownValue--;
_updateTimerDisplay();
if (_countdownValue <= 0) {
clearInterval(_timer);
_participateEvent();
_showToast('이벤트 보기 완료! 마일리지가 적립되었습니다.');
}
}, 1000);
// 모달이 열려있는지 확인하는 인터벌 설정
_reviewCheckInterval = setInterval(function() {
// 모달이 닫혀있으면 처리
if ($('#event-modal').is(':hidden')) {
clearInterval(_reviewCheckInterval);
clearInterval(_timer);
}
}, 1000);
});
}
/**
* 타이머 표시 업데이트 함수
*/
function _updateTimerDisplay() {
$('#popupCountdown').text(_countdownValue);
}
/**
* 이벤트 참여 완료 후 UI 업데이트 함수
*/
function _updateUIForCompletedEvent() {
// 해당 이벤트의 마일리지 표시 요소를 찾아 '적립완료'로 변경
$('.li_mile[data-bnf-innb="' + _bnfInnb + '"]').addClass('on').html('적립완료');
}
/**
* 페이지 초기화 함수
* 페이지 로드 시 이미 참여한 이벤트 표시 업데이트
*/
function _initializePage() {
// 모든 이벤트 요소 확인
$('.li_mile').each(function() {
const bnfInnb = $(this).data('bnf-innb');
if (bnfInnb) {
// 각 이벤트마다 참여 여부 확인
_checkEventParticipation(bnfInnb);
}
});
}
/**
* 특정 이벤트 참여 여부 확인 및 UI 업데이트
* @param {number|string} bnfInnb - 이벤트 고유 번호
*/
function _checkEventParticipation(bnfInnb) {
$.ajax({
url: '/sopmal/bnft/checkParticipationAvailable',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
bnfInnb: bnfInnb
}),
success: function(response) {
try {
if (response && response.resBody && response.resBody.result) {
const resultObj = JSON.parse(response.resBody.result);
// 참여 불가능(이미 참여)한 경우 UI 업데이트
if (!resultObj.available) {
_updateUIForCompletedEvent(bnfInnb);
}
}
} catch (e) {
console.error('응답 처리 중 오류 발생:', e);
}
},
error: function(error) {
console.error('이벤트 참여 여부 확인 실패:', error);
}
});
}
// 참여 가능 여부 확인
function _checkParticipationAvailable() {
return new Promise(function(resolve, reject) {
$.ajax({
url: '/sopmal/bnft/checkParticipationAvailable',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
bnfInnb: _bnfInnb
}),
success: function(response) {
try {
// 응답 구조에 맞게 처리
if (response && response.resBody && response.resBody.result) {
// JSON 문자열을 객체로 파싱
const resultObj = JSON.parse(response.resBody.result);
resolve(resultObj.available);
} else {
console.error('응답 형식이 올바르지 않습니다:', response);
resolve(false);
}
} catch (e) {
console.error('응답 처리 중 오류 발생:', e);
resolve(false);
}
},
error: function(error) {
console.error('참여 가능 여부 확인 실패:', error);
resolve(false);
}
});
});
}
// 이벤트 참여 및 마일리지 적립
function _participateEvent() {
if (_isParticipated) return;
$.ajax({
url: '/sopmal/bnft/participateEvent',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
bnfInnb: _bnfInnb
}),
success: function(response) {
try {
// 응답 구조에 맞게 처리
if (response && response.resBody && response.resBody.result) {
// JSON 문자열을 객체로 파싱
const resultObj = JSON.parse(response.resBody.result);
if (resultObj.success) {
_isParticipated = true;
// UI 업데이트: 마일리지 -> 적립완료
_updateUIForCompletedEvent();
// 토스트 메시지 표시
_showToast('이벤트 보기 완료! 마일리지가 적립되었습니다.');
} else {
console.log('resultObj.message', resultObj.message);
showCustomAlert('마일리지 적립에 실패했습니다.');
}
} else {
console.error('응답 형식이 올바르지 않습니다:', response);
showCustomAlert('마일리지 적립에 실패했습니다.');
}
} catch (e) {
console.error('응답 처리 중 오류 발생:', e);
showCustomAlert('마일리지 적립 중 오류가 발생했습니다.');
}
},
error: function(error) {
console.error('이벤트 참여 실패:', error);
showCustomAlert('이벤트 참여 중 오류가 발생했습니다.');
}
});
}
// 이벤트 시작 함수
function start(bnfInnb, eventDesc, loadingTime, mileageAmount, eventUrl, startDate, endDate) {
// 날짜 검증 추가
if (startDate && endDate) {
const now = new Date();
const eventStart = new Date(startDate);
const eventEnd = new Date(endDate);
if (now < eventStart) {
_showToast("아직 시작되지 않은 이벤트입니다.");
return;
}
if (now > eventEnd) {
_showToast("종료된 이벤트입니다.");
return;
}
}
_bnfInnb = bnfInnb;
_eventDesc = eventDesc;
_loadingTime = loadingTime;
_mileageAmount = mileageAmount;
_eventUrl = eventUrl || '';
_isParticipated = false;
// 타이머 종료
if (_timer) {
clearInterval(_timer);
}
// 타이머 시작
_startTimer();
}
// 페이지 초기화 실행
$(document).ready(function() {
_initializePage();
});
// 공개 API
return {
start: start,
participateEvent: _participateEvent,
showToast: _showToast,
init: _initializePage // 페이지 초기화 함수 노출
};
})();