// 거주인 녹취정보 상세 페이지 JavaScript
// 외부 의존성: jQuery, Bootstrap 5, SweetAlert2, Naver Maps, Dropzone 6.0, Sortable.js 1.15
var map;
var dz = null; // Dropzone 인스턴스
var sortable = null; // Sortable 인스턴스
$(function () {
trade_type_onchange();
if (isDefined(window.rcpt_hscp_nm)) {
$(".spc").hide();
}
map = new naver.maps.Map('mapArea', {
center: new naver.maps.LatLng(window.lat, window.lng),
useStyleMap: true,
zoom: 17,
minZoom: 10,
mapTypeControl: true,
mapTypeControlOptions: {
style: naver.maps.MapTypeControlStyle.BUTTON,
position: naver.maps.Position.TOP_LEFT
},
zoomControl: true,
zoomControlOptions: {
position: naver.maps.Position.TOP_RIGHT
}
});
marker = new naver.maps.Marker({
position: new naver.maps.LatLng(window.lat, window.lng),
map: map
});
// Dropzone auto discover 비활성화
Dropzone.autoDiscover = false;
// 파일업로드 open
$("#btnUploadModal").on("click", function () {
$("#uploadModal").modal("show");
});
});
//공백 값 체크
function isDefined(str) {
var isResult = false;
str_temp = str + "";
str_temp = str_temp.replace(" ", "");
if (str_temp != "undefined" && str_temp != "" && str_temp != "null") {
isResult = true;
}
return isResult;
}
// 부모 창에서 삭제된 이미지 제거하는 함수
function removeImageFromParent(imgType, imgSq) {
console.log('[removeImageFromParent] 이미지 제거:', imgType, imgSq);
// 이미지 타입에 따라 다른 처리
switch(imgType) {
case 'I1': // 홍보확인서 - 단일 이미지를 photo.gif로 변경
$('#photo-display2_I1').attr('src', '/plugin/img/photo.gif')
.parent('a').replaceWith('
');
break;
case 'I8': // 분양권 - 해당 div 제거
$('img[src*="' + imgSq + '"]').closest('div[style*="width: 150px"]').remove();
break;
case 'I4': // 매물사진 - 해당 thumb-card 제거
$('input[name="i4_seq[]"][value="' + imgSq + '"]').closest('.thumb-card').remove();
break;
case 'I9': // 360이미지 - 해당 thumb-card 제거
$('input[name^="img_location_' + imgSq + '"]').closest('.thumb-card').remove();
break;
case 'I10': // 촬영동의서 - 이미지를 photo.gif로 변경
$('img[alt="촬영동의서"]').attr('src', '/plugin/img/photo.gif')
.parent('a').replaceWith('
');
break;
case 'I2': // 현장확인내역서 - 이미지를 photo.gif로 변경
$('img[alt="현장확인내역서"]').attr('src', '/plugin/img/photo.gif')
.parent('a').replaceWith('
');
break;
case 'V1': // 동영상 - 이미지를 photo.gif로 변경
$('img[alt="동영상"]').attr('src', '/plugin/img/photo.gif')
.parent('a').replaceWith('
');
break;
case 'I5': // 평면도 - 이미지를 photo.gif로 변경
$('img[alt="평면도"]').attr('src', '/plugin/img/photo.gif')
.parent('a').replaceWith('
');
break;
case 'I11': // 체크리스트 - 이미지를 photo.gif로 변경
$('img[alt="체크리스트"]').attr('src', '/plugin/img/photo.gif')
.parent('a').replaceWith('
');
break;
default:
console.log('[removeImageFromParent] 알 수 없는 이미지 타입:', imgType);
}
}
// 부모 창에 업로드된 이미지 추가/업데이트하는 함수
function updateImageInParent(imgType, imageData) {
console.log('[updateImageInParent] 이미지 업데이트:', imgType, imageData);
if (!imageData || !imageData.img_path || !imageData.img_filenm) {
console.error('[updateImageInParent] 이미지 데이터 부족:', imageData);
return;
}
// 이미지 URL 생성
const imgPath = imageData.img_path + imageData.img_filenm;
const thumbPath = imageData.img_path + imageData.img_filenm.replace(/\.\w+$/, '_thumb.jpg');
// 클라우드 URL 처리
const NCLOUD_URL = 'https://kr.object.ncloudstorage.com/confirms-object/';
const fullImageUrl = imageData.cloud_upload_yn === 'Y' ? NCLOUD_URL + imgPath : imgPath;
const thumbImageUrl = imageData.cloud_upload_yn === 'Y' ? NCLOUD_URL + thumbPath : thumbPath;
// 이미지 타입에 따라 다른 처리
switch(imgType) {
case 'I1': // 홍보확인서 - 단일 이미지 업데이트
const $i1Container = $('#photo-display2_I1').closest('.ratio');
$i1Container.html(`
`);
break;
case 'I10': // 촬영동의서
const $i10Container = $('img[alt="촬영동의서"]').closest('.ratio');
$i10Container.html(`
`);
break;
case 'I2': // 현장확인내역서
const $i2Container = $('img[alt="현장확인내역서"]').closest('.ratio');
$i2Container.html(`
`);
break;
case 'I8': // 분양권 - 새 이미지 추가
const $i8Container = $('img[alt="분양권"]').closest('.d-flex');
// photo.gif인 placeholder 제거
$i8Container.find('img[src="/plugin/img/photo.gif"]').closest('div[style*="width: 150px"]').remove();
// 새 이미지 추가
const i8Html = `
`);
break;
case 'I5': // 평면도
const $i5Container = $('img[alt="평면도"]').closest('.ratio');
$i5Container.html(`
`;
if (imgId) {
const existing = $(`#${imgId}`);
if (existing.length > 0) {
if (existing.parent('a').length > 0) {
existing.parent('a').replaceWith(defaultHtml);
} else {
existing.replaceWith(defaultHtml);
}
}
} else {
const existing = $(`img[alt="${altText}"]`);
if (existing.length > 0) {
if (existing.parent('a').length > 0) {
existing.parent('a').replaceWith(defaultHtml);
} else {
existing.replaceWith(defaultHtml);
}
}
}
return;
}
const originalUrl = img.original_url || img.thumbnail_url;
const thumbnailUrl = img.thumbnail_url || img.original_url;
const html = `
삭제 중...
' }); // 해당 타입의 이미지 목록 조회 후 삭제 $.ajax({ url: '/article/receipt/getImages', method: 'GET', data: { rsrv_sq: rsrvSq, img_type: imgType }, success: function(response) { console.log('[deleteAllImagesByType] 조회 응답:', response); if (response.success && response.images && response.images.length > 0) { const images = response.images; const imageCount = images.length; // 삭제 Promise 배열 const deletePromises = images.map(img => { return $.ajax({ url: '/article/receipt/removeUploadFile', method: 'POST', data: { rcpt_sq: rcptSq, img_sq: img.img_sq } }); }); // 모든 삭제 완료 대기 Promise.all(deletePromises) .then(function(results) { console.log('[deleteAllImagesByType] 모든 삭제 완료:', results); // 성공/실패 카운트 const successCount = results.filter(r => r.code === '0').length; const failCount = imageCount - successCount; // 로딩 화면 제거 blockUI.unblockPage(); if (failCount > 0) { alert(`${successCount}개 삭제 성공, ${failCount}개 실패`); } else { alert(`${imgTypeName} 이미지 ${successCount}개가 삭제되었습니다.`); } // AJAX로 이미지 재로딩 loadAllImages(rsrvSq); }) .catch(function(error) { console.error('[deleteAllImagesByType] 삭제 오류:', error); // 로딩 화면 제거 blockUI.unblockPage(); alert('이미지 삭제 중 오류가 발생했습니다.'); loadAllImages(rsrvSq); // 오류 발생해도 재로딩 }); } else { // 로딩 화면 제거 blockUI.unblockPage(); alert(`삭제할 ${imgTypeName} 이미지가 없습니다.`); } }, error: function(xhr, status, error) { console.error('[deleteAllImagesByType] 조회 오류:', error); // 로딩 화면 제거 blockUI.unblockPage(); alert('이미지 조회 중 오류가 발생했습니다.'); } }); } // 매물사진 Sortable 초기화 var propertyImagesSortable = null; function initPropertyImagesSortable() { const container = document.getElementById('property-images-container'); if (!container) { console.warn('[initPropertyImagesSortable] 컨테이너를 찾을 수 없음'); return; } // 기존 Sortable 제거 if (propertyImagesSortable) { propertyImagesSortable.destroy(); propertyImagesSortable = null; } // 이미지가 없으면 초기화하지 않음 const items = container.querySelectorAll('.property-image-item[data-img-sq]'); if (items.length === 0) { console.log('[initPropertyImagesSortable] 이미지가 없어서 Sortable 초기화 안 함'); return; } propertyImagesSortable = new Sortable(container, { animation: 150, ghostClass: 'sortable-ghost', dragClass: 'sortable-drag', draggable: '.property-image-item', onStart: function(evt) { // 드래그 시작시 클릭 이벤트 막기 const links = container.querySelectorAll('a'); links.forEach(link => { link.style.pointerEvents = 'none'; }); }, onEnd: function(evt) { console.log('[PropertyImagesSortable] 순서 변경:', evt.oldIndex, '->', evt.newIndex); updatePropertyImageOrderBadges(); // 드래그 종료 후 클릭 이벤트 복구 (약간의 딜레이 후) setTimeout(function() { const links = container.querySelectorAll('a'); links.forEach(link => { link.style.pointerEvents = ''; }); }, 100); } }); console.log('[initPropertyImagesSortable] Sortable 초기화 완료, 이미지 수:', items.length); } // 매물사진 순서 배지 업데이트 function updatePropertyImageOrderBadges() { const items = document.querySelectorAll('#property-images-container .property-image-item'); items.forEach((item, index) => { const badge = item.querySelector('.image-order-badge'); if (badge) { badge.textContent = index + 1; } }); console.log('[updatePropertyImageOrderBadges] 배지 업데이트 완료'); } // 360이미지 촬영위치 저장 function save360ImageLocations() { console.log('[save360ImageLocations] 촬영위치 저장 시작'); const rsrvSq = $("#frm_file_info [name=rsrv_sq]").val(); if (!rsrvSq) { alert('예약번호가 없습니다.'); return; } // img_location으로 시작하는 모든 input 수집 const locationInputs = $('input[id^="img_location_"]'); if (locationInputs.length === 0) { alert('저장할 360이미지가 없습니다.'); return; } // 각 input의 값을 수집하고 저장 const savePromises = []; let savedCount = 0; locationInputs.each(function() { const imgSq = $(this).attr('id').replace('img_location_', ''); const location = $(this).val(); console.log('[save360ImageLocations] img_sq:', imgSq, 'location:', location); const promise = $.ajax({ url: '/article/receipt/saveImgLocation', method: 'POST', data: { img_sq: imgSq, rsrv_sq: rsrvSq, location: location } }).done(function(response) { if (response.code === '0') { savedCount++; console.log('[save360ImageLocations] 저장 완료:', imgSq); } else { console.error('[save360ImageLocations] 저장 실패:', response.msg); } }).fail(function(xhr, status, error) { console.error('[save360ImageLocations] AJAX 오류:', error); }); savePromises.push(promise); }); // 모든 저장 완료 대기 Promise.all(savePromises).then(function() { console.log('[save360ImageLocations] 모든 촬영위치 저장 완료:', savedCount); alert(`촬영위치가 저장되었습니다. (${savedCount}개)`); }).catch(function(error) { console.error('[save360ImageLocations] 저장 중 오류:', error); alert('촬영위치 저장 중 오류가 발생했습니다.'); }); } // 이미지 타입별 일괄 다운로드 function downloadImagesByType(imgType, imgTypeName) { const rsrvSq = $("#frm_file_info [name=rsrv_sq]").val(); if (!rsrvSq) { alert('예약번호가 없습니다.'); return; } // 해당 타입의 이미지 개수 확인 let imageCount = 0; if (allImagesCache && allImagesCache.length > 0) { imageCount = allImagesCache.filter(img => img.img_type === imgType).length; } if (imageCount === 0) { alert('다운로드할 ' + imgTypeName + ' 이미지가 없습니다.'); return; } if (!confirm(`${imgTypeName} ${imageCount}장을 다운로드하시겠습니까?`)) { return; } // 로딩 화면 표시 blockUI.blockPage({ message: '다운로드 준비 중...
' }); // 다운로드 URL 생성 및 실행 const downloadUrl = `/article/receipt/downloadAllImages?rsrv_sq=${rsrvSq}&img_type=${imgType}`; // iframe을 사용한 다운로드 (페이지 리로드 방지) const iframe = document.createElement('iframe'); iframe.style.display = 'none'; iframe.src = downloadUrl; document.body.appendChild(iframe); // 다운로드 완료 후 정리 (3초 후) setTimeout(function() { blockUI.unblockPage(); document.body.removeChild(iframe); console.log(`[downloadImagesByType] ${imgTypeName} 다운로드 완료`); }, 3000); } // 매물사진 순서 저장 function savePropertyImageOrder() { const items = document.querySelectorAll('#property-images-container .property-image-item[data-img-sq]'); if (items.length === 0) { alert('저장할 이미지가 없습니다.'); return; } // 순서 데이터 수집 const orderData = []; items.forEach((item, index) => { const imgSq = item.getAttribute('data-img-sq'); if (imgSq) { orderData.push({ img_sq: imgSq, view_odr: index + 1 }); } }); console.log('[savePropertyImageOrder] 저장할 순서:', orderData); if (!confirm(`매물사진 순서를 저장하시겠습니까? (총 ${orderData.length}장)`)) { return; } // 로딩 화면 표시 blockUI.blockPage({ message: '저장 중...
' }); // 서버에 저장 요청 $.ajax({ url: '/article/receipt/updateImageOrder', method: 'POST', data: { rcpt_sq: $("#frm_file_info [name=rcpt_sq]").val(), img_type: 'I4', orders: JSON.stringify(orderData) }, success: function(response) { blockUI.unblockPage(); if (response.code === '0' || response.success) { alert('매물사진 순서가 저장되었습니다.'); // 재로딩하여 최신 상태 반영 const rsrvSq = $("#frm_file_info [name=rsrv_sq]").val(); if (rsrvSq) { loadAllImages(rsrvSq); } } else { alert('순서 저장 중 오류가 발생했습니다: ' + (response.msg || response.message || '알 수 없음')); } }, error: function(xhr, status, error) { blockUI.unblockPage(); console.error('[savePropertyImageOrder] 오류:', error); alert('순서 저장 중 오류가 발생했습니다.'); } }); } function trade_type_onchange() { var trade_type = $('#trade_type').val(); if (trade_type == 'B2' || trade_type == 'B3') { // 월세... $('#div_trade_type_price_monthly').show(); } else { $('#div_trade_type_price_monthly').hide(); } } // 가격수정 btn function editPriceInfo() { var rcpt_product = $('#rcpt_product').val(); var trade_type = $('#trade_type').val(); $("#trade_type").prop("disabled", false); $("#rcpt_product_info2").prop("disabled", false); $("#rcpt_product_info3").prop("disabled", false); if (trade_type == "A1") { if (rcpt_product == 'A01' || rcpt_product == 'A02' || rcpt_product == 'A03' || rcpt_product == 'B01' || rcpt_product == 'B02' || rcpt_product == 'B03') { $("#rcpt_product_info4").prop("disabled", false); $("#rcpt_product_info5").prop("disabled", false); } } } // 가격수정 저장 function modifyPriceInfo(btn) { // 거래구분 값 검증 var tradeType = $("#trade_type").val(); if (!tradeType || tradeType.trim() === "") { Swal.fire({ text: "거래구분을 선택해주세요.", icon: "warning", confirmButtonText: "확인" }); return; } Swal.fire({ text: "저장 하시겠습니까?", icon: "warning", showCancelButton: true, confirmButtonText: "예", cancelButtonText: "아니오", confirmButtonColor: "#3085d6", cancelButtonColor: "#d33", }).then((result) => { if (result.isConfirmed) { var params = { 'rcpt_sq': window.rcpt_sq, 'rcpt_key': $("#rcpt_key").val(), 'rcpt_no': $("#rcpt_atclno").val(), 'trade_type': tradeType, 'rcpt_product_info2': $("#rcpt_product_info2").val(), 'rcpt_product_info3': $("#rcpt_product_info3").val(), 'rcpt_product_info4': $("#rcpt_product_info4").val(), 'rcpt_product_info5': $("#rcpt_product_info5").val(), 'rcpt_ptp_no': $("#rcpt_ptp_no").val(), 'agent_tel': $("#agent_tel").val(), 'rcpt_hscp_no': $(btn).data('hscp_no'), 'rcpt_ptp_no': $(btn).data('ptp_no'), }; console.log( params ); // callAjax("/article/receipt/modifyPriceInfo", params, fn_result); } }); } // 연락가능전화 저장 function fn_save_tel() { Swal.fire({ text: "저장 하시겠습니까?", icon: "warning", showCancelButton: true, confirmButtonText: "예", cancelButtonText: "아니오", confirmButtonColor: "#3085d6", cancelButtonColor: "#d33", }).then((result) => { if (result.isConfirmed) { var params = { 'rcpt_sq': window.rcpt_sq, 'agent_tel': $("#agent_tel").val(), }; callAjax("/article/receipt/saveAptMemo", params, fn_result); } }); } // 평면도요청 저장 function res_ground() { Swal.fire({ text: "저장 하시겠습니까?", icon: "warning", showCancelButton: true, confirmButtonText: "예", cancelButtonText: "아니오", confirmButtonColor: "#3085d6", cancelButtonColor: "#d33", }).then((result) => { if (result.isConfirmed) { callAjax("/article/receipt/resGround", $("#rcptFrm").serialize(), fn_result); } }); } // 거주여부 변경 이벤트 function dbYn_change(value) { // 거주여부가 Y이면 DB활용동의여부 활성화, N이면 비활성화 if (value === 'Y') { $('#dbUsageAgrYn').prop('disabled', false); } else { $('#dbUsageAgrYn').prop('disabled', true); $('#dbUsageAgrYn').val('N'); } } // 거주여부 저장 function saveResDbYn() { Swal.fire({ text: "저장 하시겠습니까?", icon: "warning", showCancelButton: true, confirmButtonText: "예", cancelButtonText: "아니오", confirmButtonColor: "#3085d6", cancelButtonColor: "#d33", }).then((result) => { if (result.isConfirmed) { callAjax("/article/receipt/resDbYn", $("#rcptFrm").serialize(), fn_result); } }); } //등록일로부터 3개월 체크 function assign(mon, menuid) { var frm = document.getElementById('rcptFrm'); var to = frm.rsrv_date.value; var mon_chk = mon.split("-"); var to_chk = to.split("-"); var date1 = new Date(mon_chk[0], mon_chk[1], mon_chk[2]).valueOf(); var date2 = new Date(to_chk[0], to_chk[1], to_chk[2]).valueOf(); if (date2 - date1 < 0) { assignRegist(menuid); } else { Swal.fire({ title: "등록일로부터 3개월 이전만 가능합니다.", icon: "warning" }) return; } } /** * 배정자 등록 */ function assignRegist(menuid) { var frm = document.rcptFrm; if (frm.rsrv_date.value == "") { Swal.fire({ title: "방문희망일시를 선택해 주세요.", icon: "warning" }) return; } var date = new Date(); var yy = date.getFullYear(); var mm = date.getMonth() + 1; var dd = date.getDate(); if (mm < 10) mm = "0" + mm; if (dd < 10) dd = "0" + dd; var today = yy + mm + dd; var rsrv = frm.rsrv_date.value.replace(/-/gi, ""); if (parseInt(today) > parseInt(rsrv)) { Swal.fire({ title: "방문희망일시는 금일 이전날짜는 불가능합니다.", icon: "warning" }) return; } if (frm.rsrv_tm_ap.value == "") { Swal.fire({ title: "오전/오후를 선택해 주세요.", icon: "warning" }) return; } if (frm.rsrv_tm_hour.value == "") { Swal.fire({ title: "시간을 선택해 주세요.", icon: "warning" }) return; } if (frm.bonbu.value == "") { Swal.fire({ title: "본부를 선택해 주세요.", icon: "warning" }) return; } if (frm.dept_sq.value == "") { Swal.fire({ title: "팀을 선택해 주세요.", icon: "warning" }) return; } if (frm.usr_sq.value == "") { Swal.fire({ title: "담당자를 선택해 주세요.", icon: "warning" }) return; } swal.fire({ text: "저장 하시겠습니까?", icon: "warning", showCancelButton: true, confirmButtonText: "예", cancelButtonText: "아니오", confirmButtonColor: "#3085d6", cancelButtonColor: "#d33", }).then((result) => { if (result.isConfirmed) { callAjax("/article/receipt/assignRegist", $("#rcptFrm").serialize(), fn_result); } }); } // 동영상 촬영여부저장 function requestMovie() { Swal.fire({ text: "저장 하시겠습니까?", icon: "warning", showCancelButton: true, confirmButtonText: "예", cancelButtonText: "아니오", confirmButtonColor: "#3085d6", cancelButtonColor: "#d33", }).then((result) => { if (result.isConfirmed) { callAjax("/article/receipt/requestMovie", $("#rcptFrm").serialize(), fn_result); } }); } // 중개사메모 저장 function requestMessage() { Swal.fire({ text: "저장 하시겠습니까?", icon: "warning", showCancelButton: true, confirmButtonText: "예", cancelButtonText: "아니오", confirmButtonColor: "#3085d6", cancelButtonColor: "#d33", }).then((result) => { if (result.isConfirmed) { callAjax("/article/receipt/requestMessage", $("#rcptFrm").serialize(), fn_result); } }); } // 예약취소 function rsrvcancel() { var stat = frm.rcpt_stat1.value; var cd2 = frm.result_cd2.value; if (stat == '70' && cd2 == '9030') { Swal.fire({ title: "방문 전 취소가 불가능합니다.", icon: "warning" }) return; } if (frm.result_cd2.value == "") { Swal.fire({ title: "분류1을 선택해 주세요.", icon: "warning" }) return; } if (frm.result_cd3.value == "") { Swal.fire({ title: "분류2를 선택해 주세요.", icon: "warning" }) return; } if (frm.result_msg.value == "") { Swal.fire({ title: "취소사유를 입력해 주세요.", icon: "warning" }) return; } Swal.fire({ text: "취소 하시겠습니까?", icon: "warning", showCancelButton: true, confirmButtonText: "예", cancelButtonText: "아니오", confirmButtonColor: "#3085d6", cancelButtonColor: "#d33", }).then((result) => { if (result.isConfirmed) { callAjax("/article/receipt/rsrvcancel", $("#rcptFrm").serialize(), fn_result); } }); } // 상태변경 function chgStatus(cd, rcpt_product, chg_floor_yn) { if (cd == "") return; var frm = document.rcptFrm; var i1 = frm.I1.value; // 홍보확인서 var i4 = frm.I4.value; // 매물사진 var rr_yn = frm.req_rec_yn.value; //녹취필요여부 var chk_record = frm.chk_record.value; //녹취파일 확인 체크 var r_yn = frm.rec_yn.value; //녹취 완료여부 var req_rec_yn = "N"; var rcpt_product = frm.rcpt_product.value; var r = ''; } // 문자발송 modal function viewSmsPop(cd) { if (window.smsArr.length > 0) { var tel = ""; if (cd == "S7" || cd == "S14") { tel = window.rec_tel; } else if (cd == "S10") { tel = window.agent_contact_tel; } else if (cd == "15") { tel = window.agent_contact_tel; } else { tel = window.agent_head_tel; } for (const sms of window.smsArr) { if (sms.cd == cd) { $("#smsForm [name=cd]").val(cd); $("#smsForm [name=phone]").val(tel); $("#smsForm [name=content]").val(sms.cd_nm); } } } $("#smsModal").modal("show"); } // 문자발송 function sendSms() { if ($("#smsForm [name=phone]").val() == "") { Swal.fire({ title: "수신번호를 입력해 주세요.", icon: "warning" }) return; } if ($("#smsForm [name=content]").val() == "") { Swal.fire({ title: "내용을 입력해 주세요.", icon: "warning" }) return; } Swal.fire({ text: "SMS를 발송하시겠습니까?", icon: "warning", showCancelButton: true, confirmButtonText: "예", cancelButtonText: "아니오", confirmButtonColor: "#3085d6", cancelButtonColor: "#d33", }).then((result) => { if (result.isConfirmed) { callAjax("/article/receipt/sendSms", $("#smsForm").serialize(), fn_result); } }); } function showFileName(input) { if (input.files && input.files.length > 0) { document.getElementById('file_name').textContent = input.files[0].name; } } // 거주인 녹취정보 저장 function saveRecInfo() { const rec_tel1 = $("#rec_tel1").val(); const rec_tel2 = $("#rec_tel2").val(); const rec_tel3 = $("#rec_tel3").val(); if (rec_tel1 == "" || rec_tel2 == "" || rec_tel3 == "") { Swal.fire({ title: "거주자 전화번호를 입력해 주세요.", icon: "warning" }); return; } Swal.fire({ text: "거주인정보를 저장하시겠습니까?", icon: "warning", showCancelButton: true, confirmButtonText: "예", cancelButtonText: "아니오", confirmButtonColor: "#3085d6", cancelButtonColor: "#d33", }).then((result) => { if (result.isConfirmed) { var form = $('#rcptFrm')[0]; var formData = new FormData(form); $.ajax({ url: "/article/receipt/saveRecInfo", method: 'POST', data: formData, processData: false, contentType: false, cache: false, beforeSend: function () { blockUI.blockPage({ message: tpl }) }, complete: function () { blockUI.unblockPage() }, success: function (result) { if (result.code == '0') { Swal.fire({ title: "정상 처리되었습니다.", icon: "success", draggable: true }).then(() => { // 서버에서 반환된 데이터로 화면 갱신 if (result.data) { updateRecInfoUI(result.data); } }); } else { Swal.fire({ title: result.msg, icon: "error", draggable: true }) } } }); } }); } // 거주인 정보 UI 업데이트 function updateRecInfoUI(data) { // 전화번호 업데이트 if (data.rec_tel) { const telParts = data.rec_tel.split('-'); $('input[name="rec_tel1"]').val(telParts[0] || ''); $('input[name="rec_tel2"]').val(telParts[1] || ''); $('input[name="rec_tel3"]').val(telParts[2] || ''); } // 거주인 이름 업데이트 $('input[name="rec_nm"]').val(data.rec_nm || ''); // 거주인 요청사항 업데이트 $('textarea[name="rec_remark"]').val(data.remark || ''); // 음성파일 정보 업데이트 const fileInfoHtml = data.record ? ` ` : '등록된 파일 없음'; // 음성파일 영역 업데이트 (파일 업로드 버튼 앞까지) const fileContainer = $('input[name="rec_file"]').closest('td').find('.d-flex').first(); fileContainer.find('.d-flex.align-items-center.gap-2.flex-wrap, .text-muted.small').first().replaceWith(fileInfoHtml); // 녹취파일 체크박스 활성화 및 체크 if (data.record) { $('#chk_record').prop('disabled', false).prop('checked', true); } else { $('#chk_record').prop('disabled', true).prop('checked', false); } // 파일명 표시 초기화 $('#file_name').text(''); $('input[name="rec_file"]').val(''); } // 거주인 정보 다시 불러오기 function loadRecInfo() { const rcpt_sq = $('input[name="rcpt_sq"]').val(); $.ajax({ url: "/article/receipt/getRecInfo", method: 'GET', data: { rcpt_sq: rcpt_sq }, dataType: 'json', success: function (result) { if (result.code == '0' && result.data) { updateRecInfoUI(result.data); } }, error: function() { console.error('거주인 정보를 불러오는데 실패했습니다.'); } }); } function fn_preview(src, type = 'img') { const $img = $('#imgPreview'); const $video = $('#vdoPreview'); const video = document.getElementById('vdoPreview'); const source = document.getElementById('videoSource'); if (type === 'vdo') { // 이미지 숨김 $img.hide().attr('src', ''); // video source 세팅 source.src = src; // video 표시 + 로드 $video.show(); video.load(); $('#previewTitle').text('동영상 미리보기'); } else { // video 정지 및 초기화 video.pause(); source.src = ''; video.load(); $video.hide(); // 이미지 표시 $img.attr('src', src).show(); $('#previewTitle').text('이미지 미리보기'); } const modal = new bootstrap.Modal(document.getElementById('previewModal')); modal.show(); } function callAjax(target, params, callback) { $.ajax({ url: target, contentType: 'application/x-www-form-urlencoded;charset=UTF-8', method: "POST", data: params, beforeSend: function () { blockUI.blockPage({ message: tpl }) }, complete: function () { blockUI.unblockPage() }, success: function (result) { callback(result); } }); } function fn_result(result) { if (result.code == '0') { Swal.fire({ title: "정상 처리되었습니다.", icon: "success", draggable: true }); // 정보변경 이력 갱신 loadHistory(); } else { Swal.fire({ title: result.msg, icon: "error", draggable: true }) } } // 정보변경 이력 AJAX 로드 function loadHistory() { const rcptSq = $("#rcptFrm input[name='rcpt_sq']").val(); console.log('[loadHistory] rcpt_sq:', rcptSq); if (!rcptSq) { console.warn('[loadHistory] rcpt_sq가 없습니다.'); return; } $.ajax({ url: "/article/receipt/getHistory", type: "GET", data: { rcpt_sq: rcptSq }, success: function(result) { console.log('[loadHistory] 응답:', result); if (result.code === '0' && result.data) { console.log('[loadHistory] 이력 데이터:', result.data); updateHistoryUI(result.data); } else { console.warn('[loadHistory] 올바르지 않은 응답:', result); } }, error: function(xhr, status, error) { console.error('[History] 로드 실패:', error); console.error('[History] 응답:', xhr.responseText); } }); } // 정보변경 이력 UI 업데이트 function updateHistoryUI(historyData) { const $historyTable = $('#history-table'); if (!$historyTable.length) { console.error('[updateHistoryUI] 정보변경 이력 테이블을 찾을 수 없습니다.'); return; } let $tbody = $historyTable.find('tbody'); if (!$tbody.length) { // tbody가 없으면 생성 const $thead = $historyTable.find('thead'); if ($thead.length) { $tbody = $('').insertAfter($thead); } } $tbody.empty(); if (historyData && historyData.length > 0) { historyData.forEach(h => { const row = `