// 작업장 레이아웃 지도 관리
// 전역 변수
let layoutMapImage = null;
let mapRegions = [];
let canvas = null;
let ctx = null;
let isDrawing = false;
let startX = 0;
let startY = 0;
let currentRect = null;
// ==================== 레이아웃 지도 모달 ====================
/**
* 레이아웃 지도 모달 열기
*/
async function openLayoutMapModal() {
// window 객체에서 currentCategoryId 가져오기
const currentCategoryId = window.currentCategoryId;
if (!currentCategoryId) {
window.window.showToast('공장을 먼저 선택해주세요.', 'warning');
return;
}
const modal = document.getElementById('layoutMapModal');
if (!modal) return;
// 캔버스 초기화
canvas = document.getElementById('regionCanvas');
ctx = canvas.getContext('2d');
// 현재 카테고리의 레이아웃 이미지 및 영역 로드
await loadLayoutMapData();
// 작업장 선택 옵션 업데이트
updateWorkplaceSelect();
modal.style.display = 'flex';
document.body.style.overflow = 'hidden';
}
/**
* 레이아웃 지도 모달 닫기
*/
function closeLayoutMapModal() {
const modal = document.getElementById('layoutMapModal');
if (modal) {
modal.style.display = 'none';
document.body.style.overflow = '';
}
// 캔버스 이벤트 리스너 제거
if (canvas) {
canvas.removeEventListener('mousedown', startDrawing);
canvas.removeEventListener('mousemove', draw);
canvas.removeEventListener('mouseup', stopDrawing);
}
// 메인 페이지의 레이아웃 미리보기 업데이트
const currentCategoryId = window.currentCategoryId;
const categories = window.categories;
if (currentCategoryId && categories) {
const category = categories.find(c => c.category_id == currentCategoryId);
if (category && window.updateLayoutPreview) {
window.updateLayoutPreview(category);
}
}
}
/**
* 레이아웃 지도 데이터 로드
*/
async function loadLayoutMapData() {
try {
const currentCategoryId = window.currentCategoryId;
const categories = window.categories;
// 현재 카테고리 정보 가져오기
const category = categories.find(c => c.category_id == currentCategoryId);
if (!category) return;
// 레이아웃 이미지 표시
const currentImageDiv = document.getElementById('currentLayoutImage');
if (category.layout_image) {
// 이미지 경로를 전체 URL로 변환
const fullImageUrl = category.layout_image.startsWith('http')
? category.layout_image
: `${window.API_BASE_URL || 'http://localhost:30005/api'}${category.layout_image}`.replace('/api/', '/');
currentImageDiv.innerHTML = `
`;
// 캔버스에도 이미지 로드
loadImageToCanvas(fullImageUrl);
} else {
currentImageDiv.innerHTML = '업로드된 이미지가 없습니다';
}
// 영역 데이터 로드
const regionsResponse = await window.apiCall(`/workplaces/categories/${currentCategoryId}/map-regions`, 'GET');
if (regionsResponse && regionsResponse.success) {
mapRegions = regionsResponse.data || [];
} else {
mapRegions = [];
}
renderRegionList();
} catch (error) {
console.error('레이아웃 지도 데이터 로딩 오류:', error);
window.window.showToast('레이아웃 지도 데이터를 불러오는데 실패했습니다.', 'error');
}
}
/**
* 이미지를 캔버스에 로드
*/
function loadImageToCanvas(imagePath) {
const img = new Image();
img.onload = function() {
// 캔버스 크기를 이미지 크기에 맞춤 (최대 800px)
const maxWidth = 800;
const scale = img.width > maxWidth ? maxWidth / img.width : 1;
canvas.width = img.width * scale;
canvas.height = img.height * scale;
// 이미지 그리기
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
layoutMapImage = img;
// 기존 영역들 그리기
drawExistingRegions();
// 캔버스 이벤트 리스너 등록
setupCanvasEvents();
};
img.src = imagePath;
}
/**
* 작업장 선택 옵션 업데이트
*/
function updateWorkplaceSelect() {
const select = document.getElementById('regionWorkplaceSelect');
if (!select) return;
const currentCategoryId = window.currentCategoryId;
const workplaces = window.workplaces;
// 현재 카테고리의 작업장만 필터링
const categoryWorkplaces = workplaces.filter(w => w.category_id == currentCategoryId);
let options = '';
categoryWorkplaces.forEach(wp => {
// 이미 영역이 정의된 작업장은 표시
const hasRegion = mapRegions.some(r => r.workplace_id === wp.workplace_id);
options += ``;
});
select.innerHTML = options;
}
// ==================== 이미지 업로드 ====================
/**
* 이미지 미리보기
*/
function previewLayoutImage(event) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function(e) {
const currentImageDiv = document.getElementById('currentLayoutImage');
currentImageDiv.innerHTML = `
미리보기 (저장하려면 "이미지 업로드" 버튼을 클릭하세요)
`; }; reader.readAsDataURL(file); } /** * 레이아웃 이미지 업로드 */ async function uploadLayoutImage() { const fileInput = document.getElementById('layoutImageFile'); const file = fileInput.files[0]; if (!file) { window.showToast('이미지 파일을 선택해주세요.', 'warning'); return; } const currentCategoryId = window.currentCategoryId; if (!currentCategoryId) { window.showToast('공장을 먼저 선택해주세요.', 'error'); return; } try { // FormData 생성 const formData = new FormData(); formData.append('image', file); // 업로드 요청 const response = await fetch(`${window.API_BASE_URL || 'http://localhost:30005/api'}/workplaces/categories/${currentCategoryId}/layout-image`, { method: 'POST', headers: { 'Authorization': `Bearer ${localStorage.getItem('sso_token')}` }, body: formData }); const result = await response.json(); if (result.success) { window.showToast('이미지가 성공적으로 업로드되었습니다.', 'success'); // 이미지 경로를 전체 URL로 변환 const fullImageUrl = `${window.API_BASE_URL || 'http://localhost:30005/api'}${result.data.image_path}`.replace('/api/', '/'); // 이미지를 캔버스에 로드 loadImageToCanvas(fullImageUrl); // 현재 이미지 미리보기도 업데이트 const currentImageDiv = document.getElementById('currentLayoutImage'); if (currentImageDiv) { currentImageDiv.innerHTML = `정의된 영역이 없습니다
'; return; } let listHtml = '