/**
* legal_cert_print.js - 수료증 출력 클라이언트 스크립트
*/
document.addEventListener('DOMContentLoaded', () => {
// 1. URL 쿼리 파라미터 파싱
const urlParams = new URLSearchParams(window.location.search);
const year = urlParams.get('year') || '';
const comp = urlParams.get('comp') || '';
const memberId = urlParams.get('member_id') || '';
const categoryGroup = urlParams.get('category_group') || '';
// 파라미터 유효성 검사
if (!year || !comp || !memberId || !categoryGroup) {
alert('잘못된 접근이거나 필수 출력 정보 파라미터가 누락되었습니다.');
document.body.innerHTML = `
출력 오류
수료증을 조회하기 위한 파라미터(년도, 회사코드, 사번, 교육과정코드)가 올바르지 않습니다.
`;
return;
}
// API 요청 주소
const requestUrl = `../bbs/get_legal_cert_print.php?year=${encodeURIComponent(year)}&comp=${encodeURIComponent(comp)}&member_id=${encodeURIComponent(memberId)}&category_group=${encodeURIComponent(categoryGroup)}`;
console.log('[CertPrint] Fetching certificate data from API...', requestUrl);
// 2. 백엔드 API에서 수료증 데이터 가져오기
fetch(requestUrl)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(res => {
console.log('[CertPrint] API Response:', res);
// 추출된 수료자 사번 리스트 (member_ids)를 개발자 도구 콘솔에 명시적으로 출력
if (res.debug && res.debug.matched_member_ids) {
console.log('[CertPrint] ★ 추출된 수료자 사번 리스트 (member_ids) ★:', res.debug.matched_member_ids);
}
if (!res.success) {
console.error('[CertPrint] Certificate load failed. Debug details:', res.debug || res);
let debugHtml = '';
if (res.debug) {
debugHtml = `
[서버 디버그 정보]
- 입력 연도: ${res.debug.api_params?.year || '-'}
- 입력 법인: ${res.debug.api_params?.comp || '-'}
- 입력 사번: ${res.debug.api_params?.member_id || '-'}
- 입력 과정: ${res.debug.api_params?.category_group || '-'}
- 대상 과정 교육수: ${res.debug.total_legal_cnt || 0}개
- 조건 충족 수료자수: ${res.debug.matched_member_ids?.length || 0}명 (${res.debug.matched_member_ids?.join(', ') || '없음'})
- 프로시저 호출 정보: ${res.debug.procedure_calls?.length || 0}건 호출 시도
`;
}
document.body.innerHTML = `
수료증 조회 실패
${res.message || '수료증 정보를 조회할 수 없습니다.'}
자세한 쿼리 파라미터는 브라우저 콘솔로그(F12)에서도 확인하실 수 있습니다.
${debugHtml}
`;
return;
}
const items = Array.isArray(res.data) ? res.data : [res.data];
const templatePage = document.querySelector('.cert-page');
const parent = templatePage.parentNode;
items.forEach((item, idx) => {
let currentPage = templatePage;
if (idx > 0) {
currentPage = templatePage.cloneNode(true);
parent.appendChild(currentPage);
}
// 3. 성명 정제 (이름 뒤에 사번이 대괄호로 오는 경우 정제 ex. 홍길동[M24031] -> 홍길동)
let rawName = item.name || '';
let cleanName = rawName;
if (rawName.includes('[')) {
cleanName = rawName.split('[')[0].trim();
}
// 4. 발급번호 매핑 (앞뒤에 '제', '호' 붙이기)
let certIssueNo = item.cert_issue_no || '';
let formattedCertNo = certIssueNo;
if (certIssueNo && !certIssueNo.startsWith('제')) {
formattedCertNo = `제 ${certIssueNo} 호`;
}
// 5. 프론트엔드 DOM 요소 바인딩 (각 복사된 페이지 내부 요소 쿼리)
currentPage.querySelector('#val-cert-no').textContent = formattedCertNo || '제 호';
currentPage.querySelector('#val-name').textContent = cleanName || '-';
currentPage.querySelector('#val-category').textContent = item.category_name || '-';
currentPage.querySelector('#val-period').textContent = item.period || '-';
currentPage.querySelector('#val-hours').textContent = item.total_content_tm || '-';
currentPage.querySelector('#val-prt-date').textContent = item.prt_dt || '- 년 - 월 - 일';
currentPage.querySelector('#val-company').textContent = item.belong_comp || '-';
currentPage.querySelector('#val-ceo').textContent = item.ceo_name || '-';
// 6. 기업별 동적 스탬프 및 로고 워터마크 파일 바인딩
const watermarkImg = currentPage.querySelector('#val-watermark');
const stampImg = currentPage.querySelector('#val-stamp');
// 로고 워터마크 이미지 바인딩
if (item.logo_url && item.logo_url.trim() !== '') {
watermarkImg.src = item.logo_url;
watermarkImg.style.display = 'block';
console.log(`[CertPrint] Page ${idx+1} Logo Watermark loaded:`, item.logo_url);
} else {
watermarkImg.style.display = 'none';
console.log(`[CertPrint] Page ${idx+1} No Logo Watermark.`);
}
// 스탬프 직인 이미지 바인딩
if (item.stamp_url && item.stamp_url.trim() !== '') {
stampImg.src = item.stamp_url;
stampImg.style.display = 'block';
console.log(`[CertPrint] Page ${idx+1} Signature Stamp loaded:`, item.stamp_url);
} else {
stampImg.style.display = 'none';
console.log(`[CertPrint] Page ${idx+1} No Signature Stamp.`);
}
});
})
.catch(err => {
console.error('[CertPrint] Fetch Error:', err);
alert('데이터 통신 오류가 발생했습니다. 잠시 후 다시 시도해 주세요.');
});
});