Files
sam-kd/guiderail/load_modal_loadForm.php

699 lines
23 KiB
PHP
Raw Permalink Normal View History

<script>
// alertToast 함수 정의
function alertToast(message) {
// 기본 배경 색상 (초록)
let backgroundColor = "linear-gradient(to right, #00b09b, #96c93d)";
// 조건에 따라 색상 변경
if (message.includes("추가")) {
backgroundColor = "linear-gradient(to right, #2196F3, #21CBF3)"; // 파란 계열
} else if (message.includes("삭제")) {
backgroundColor = "linear-gradient(to right, #f44336, #e57373)"; // 빨간 계열
} else if (message.includes("복사")) {
backgroundColor = "linear-gradient(to right, #4CAF50, #81C784)"; // 녹색 계열
}
Toastify({
text: message,
duration: 2000,
close: true,
gravity: "top",
position: "center",
style: {
background: backgroundColor
},
}).showToast();
}
// guiderail.json 파일의 내용을 JavaScript 배열로 로드
var guiderailImages = <?php
$jsonFile = $_SERVER['DOCUMENT_ROOT'].'/guiderail/guiderail.json';
if(file_exists($jsonFile)){
echo file_get_contents($jsonFile);
} else {
echo '[]';
}
// echo '<pre>';
// print_r($jsonFile);
// echo '</pre>';
?>;
function loadForm_guiderail(mode, num = null) {
if (num == null) {
$("#mode").val('insert');
} else {
$("#mode").val(mode);
$("#num").val(num);
}
console.log('mode :', mode);
var tablename= 'guiderail';
$.ajax({
type: "POST",
url: "/guiderail/fetch_modal.php",
data: { mode: mode, num: num , tablename : tablename},
dataType: "html",
success: function(response) {
$(".modal_detail").html(response);
$("#myModal").show();
// --- 여기부터 로직 수정/추가 ---
// 1. 전역 변수로 조립 부품 데이터 관리
let assemblyParts = [];
// 2. 기존 데이터 로드 (수정/조회 시)
function loadInitialAssemblyData() {
const initialData = $("#bending_components_data").val();
if (initialData) {
try {
assemblyParts = JSON.parse(initialData);
} catch(e) {
console.error("Error parsing initial assembly data:", e);
assemblyParts = [];
}
}
}
loadInitialAssemblyData();
// 초기 데이터 로드 후 테이블 렌더링
if (assemblyParts.length > 0) {
renderAssemblyTable();
}
// 3. 모델 유형(표준/비표준) 라디오 버튼 이벤트 처리
$('input[name="model_type"]').on('change', function() {
if ($(this).val() === 'standard') {
$('#standardModelArea').show();
$('#assemblyModelArea').hide();
} else {
$('#standardModelArea').hide();
$('#assemblyModelArea').show();
}
});
// 4. '+ 부품 추가' 버튼 클릭 -> 신규 모달 열기
$("#addPartBtn").on("click", function() {
// 검색 모달을 열고, 초기 목록을 불러오기 위해 첫 검색 실행
$('#bendingSearchModal').modal('show');
searchBendingItems();
});
// 5. 절곡 부품을 검색하고 모달에 표시하는 함수
function searchBendingItems() {
const query = $('#bendingSearchInput').val();
$.ajax({
url: "/bending/searchbending.php",
type: 'GET', // searchbending.php는 GET 방식 사용
data: { search: query },
success: function(htmlResponse) {
const tableBody = $("#bendingSearchResults");
tableBody.empty();
// 반환된 HTML에서 각 'tr'을 파싱하여 체크박스 추가
const rows = $(htmlResponse);
rows.each(function() {
const num = $(this).find('.select-bending-item').data('num');
if (num) {
// 첫 번째 <td>에 체크박스 추가
const checkboxTd = `
<td class="text-center">
<input class="form-check-input bending-item-checkbox" type="checkbox" data-num="${num}">
</td>`;
$(this).prepend(checkboxTd);
// 마지막 '선택' 버튼이 있는 <td> 제거
$(this).find('td:last-child').remove();
tableBody.append(this);
}
});
},
error: function() {
$("#bendingSearchResults").html('<tr><td colspan="10" class="text-center text-danger">검색 중 오류가 발생했습니다.</td></tr>');
}
});
}
// 6. 부품 검색 모달의 검색 버튼 및 Enter 키 이벤트
$('#bendingSearchBtn').on('click', searchBendingItems);
$('#bendingSearchInput').on('keypress', function(e) {
if (e.which === 13) {
searchBendingItems();
}
});
// 7. 부품 검색 모달의 '전체 선택' 체크박스 이벤트
$('#selectAllBendingItems').on('change', function() {
$('#bendingSearchResults .bending-item-checkbox').prop('checked', this.checked);
});
// 8. 부품 검색 모달의 '선택 적용' 버튼 이벤트
$('#applyBendingSelectionBtn').on('click', function() {
const selectedNums = [];
$('#bendingSearchResults .bending-item-checkbox:checked').each(function() {
selectedNums.push($(this).data('num'));
});
if (selectedNums.length === 0) {
alert('적용할 부품을 하나 이상 선택하세요.');
return;
}
// 선택된 부품들의 상세 정보(스냅샷)를 비동기적으로 가져오기
const fetchPromises = selectedNums.map(num => {
return $.ajax({
url: "/bending/fetch_bending_detail.php",
type: "POST",
data: { num: num },
dataType: 'json'
});
});
// 모든 정보가 성공적으로 로드되면 실행
Promise.all(fetchPromises).then(results => {
results.forEach(partData => {
if(partData && !partData.error) {
partData.qty = 1; // 기본 수량 1로 설정
assemblyParts.push(partData);
}
});
renderAssemblyTable(); // 전체 부품 목록으로 테이블 다시 그리기
$('#bendingSearchModal').modal('hide'); // 작업 완료 후 모달 닫기
}).catch(error => {
console.error("부품 상세 정보를 가져오는 데 실패했습니다.", error);
alert("부품 정보를 가져오는 중 오류가 발생했습니다.");
});
});
// 9. 조립 부품 배열(assemblyParts)을 기반으로 테이블을 다시 그리는 함수
function renderAssemblyTable() {
const tableBody = $("#assemblyTable tbody");
tableBody.empty(); // 기존 내용 삭제
// 기본 7행 구성
const rowLabels = ['번호', '품명', '재질', '수량', '폭합', '음영', 'A각 표시'];
// 각 행 생성
rowLabels.forEach((label, rowIndex) => {
const $row = $('<tr>');
// 첫 번째 셀: 라벨
$row.append($('<td>').addClass('lightgray').text(label));
// 두 번째 셀: input-container
const $cell = $('<td>').addClass('input-container');
if (rowIndex === 0) {
// 번호 행: 이미지와 번호 표시
assemblyParts.forEach((part, colIndex) => {
const $colCell = $('<div>').addClass('col-cell');
// 이미지 표시
if (part.imgdata) {
const $img = $('<img>')
.attr('src', '/bending/img/' + part.imgdata)
.css({ width: '40px', height: '24px', 'object-fit': 'cover' });
$colCell.append($img);
}
// 번호 표시
const $span = $('<span>')
.addClass('form-control text-center')
.css({
display: 'inline-block',
width: '40px',
height: '24px',
'text-align': 'center',
'line-height': '24px',
'font-size': '0.8rem'
})
.text(colIndex + 1);
$colCell.append($span);
$cell.append($colCell);
});
} else if (rowIndex === 1) {
// 품명 행
assemblyParts.forEach((part, colIndex) => {
const $colCell = $('<div>').addClass('col-cell');
const $input = $('<input>')
.attr('type', 'text')
.addClass('form-control text-center')
.css({ width: '40px', height: '24px', 'font-size': '0.8rem' })
.attr('name', 'itemNameList[]')
.val(part.itemName || '')
.attr('autocomplete', 'off');
$colCell.append($input);
$cell.append($colCell);
});
} else if (rowIndex === 2) {
// 재질 행
assemblyParts.forEach((part, colIndex) => {
const $colCell = $('<div>').addClass('col-cell');
const $input = $('<input>')
.attr('type', 'text')
.addClass('form-control text-center')
.css({ width: '40px', height: '24px', 'font-size': '0.8rem' })
.attr('name', 'materialList[]')
.val(part.material || '')
.attr('autocomplete', 'off');
$colCell.append($input);
$cell.append($colCell);
});
} else if (rowIndex === 3) {
// 수량 행
assemblyParts.forEach((part, colIndex) => {
const $colCell = $('<div>').addClass('col-cell');
const $input = $('<input>')
.addClass('form-control text-center')
.css({ width: '40px', height: '24px', 'font-size': '0.8rem' })
.attr('name', 'qtyList[]')
.val(part.qty || 1)
.attr('autocomplete', 'off')
.on('change', function() {
const newQty = parseInt($(this).val());
if (newQty > 0) {
assemblyParts[colIndex].qty = newQty;
}
});
$colCell.append($input);
$cell.append($colCell);
});
} else if (rowIndex === 4) {
// 폭합 행
assemblyParts.forEach((part, colIndex) => {
const $colCell = $('<div>').addClass('col-cell');
const $input = $('<input>')
.attr('type', 'text')
.addClass('form-control text-center')
.css({ width: '40px', height: '24px', 'font-size': '0.8rem' })
.attr('name', 'widthsumList[]')
.val(part.widthsum || '')
.attr('autocomplete', 'off');
$colCell.append($input);
$cell.append($colCell);
});
} else if (rowIndex === 5) {
// 음영 행 (체크박스)
assemblyParts.forEach((part, colIndex) => {
const $colCell = $('<div>').addClass('col-cell');
const $input = $('<input>')
.attr('type', 'checkbox')
.addClass('form-check-input')
.css({ width: '16px', height: '16px' })
.attr('name', 'colorList[]')
.prop('checked', part.color || false);
$colCell.append($input);
$cell.append($colCell);
});
} else if (rowIndex === 6) {
// A각 표시 행 (체크박스)
assemblyParts.forEach((part, colIndex) => {
const $colCell = $('<div>').addClass('col-cell');
const $input = $('<input>')
.attr('type', 'checkbox')
.addClass('form-check-input')
.css({ width: '16px', height: '16px' })
.attr('name', 'AList[]')
.prop('checked', part.A || false);
$colCell.append($input);
$cell.append($colCell);
});
}
$row.append($cell);
tableBody.append($row);
});
// 삭제 버튼 추가
wrapColumnsAndAttachRemove();
}
// 10. 조립 부품 목록에서 '삭제' 버튼 및 '수량' 변경 이벤트 (이벤트 위임)
$("#assemblyTable").on("click", ".remove-part-btn", function() {
const index = $(this).closest("tr").data("index");
assemblyParts.splice(index, 1);
renderAssemblyTable();
}).on("change", ".assembly-qty-input", function() {
const index = $(this).closest("tr").data("index");
const newQty = parseInt($(this).val());
if (newQty > 0) {
assemblyParts[index].qty = newQty;
// 스냅샷 데이터도 업데이트
$(this).closest("tr").attr('data-snapshot', JSON.stringify(assemblyParts[index]).replace(/'/g, "&apos;"));
}
});
// 모달을 닫을 때 HTML 요소 제거
$(".closeBtn").on("click", function() {
$("#myModal").hide();
$(".modal_detail").html(''); // 모달 내용을 비움
$('.viewmode').prop('disabled', false); // 다시 활성화
});
// 가이드레일 선택에 따른 동작 구현
const checkImage = $('#checkImage');
const prodModelSelect = $('select[name="model_name"]');
const finishing_typeSelect = $('select[name="finishing_type"]');
// 선택된 값에 따라 이미지 설정
const initialCheckType = $("#model_name").val();
console.log('선택모델 : ' , $("#model_name").val());
console.log('선택마감 : ' , $("#finishing_type").val());
updateImage( $("#model_name").val(), $('input[name="check_type"]:checked').val() , $("#finishing_type").val());
// 라디오 버튼에 변화가 생길 때 이미지 업데이트
$('input[name="check_type"]').on('change', function() {
const selectedCheckType = $(this).val();
const selectedfinishing_type = $("#finishing_type").val();
updateImage(prodModelSelect.val(), selectedCheckType, selectedfinishing_type, 'update'); // check_type과 model_name 둘 다 전달
});
// select 요소가 변경될 때 이미지 업데이트
prodModelSelect.on('change', function() {
const selectedCheckType = $('input[name="check_type"]:checked').val();
const selectedfinishing_type = $("#finishing_type").val();
updateImage($(this).val(), selectedCheckType, selectedfinishing_type, 'update'); // check_type과 model_name 둘 다 전달
});
// select 요소가 변경될 때 이미지 업데이트
finishing_typeSelect.on('change', function() {
const initialModel = $("#model_name").val();
const selectedCheckType = $('input[name="check_type"]:checked').val();
const selectedfinishing_type = $("#finishing_type").val();
updateImage(initialModel, selectedCheckType, selectedfinishing_type, 'update'); // check_type과 model_name 둘 다 전달
});
// checkImage는 이미지 엘리먼트(jQuery 객체) 예: var checkImage = $('#checkImage');
function updateImage(model, checkType, finishing_type, mode = null) {
let imagePath = '';
console.log('guiderailImages',guiderailImages);
console.log('model',model);
console.log('finishing_type',finishing_type);
console.log('checkType',checkType);
// guiderailImages 배열에서 model과 check_type에 일치하는 항목 검색
if (Array.isArray(guiderailImages)) {
let found = guiderailImages.find(function(item) {
// model은 JSON의 model_name과 비교, checkType은 JSON의 check_type과 비교
return item.model_name === model && item.check_type === checkType && item.finishing_type === finishing_type ;
});
if (found) {
imagePath = found.image;
}
}
// checkImage는 이미지 엘리먼트(jQuery 객체)를 가리킵니다.
$('#checkImage').attr('src', imagePath);
}
$('#display_rail_length').val($('#rail_length').val());
$('#display_rail_width').val($('#rail_width').val());
// rail_length 입력이 변경될 때 아래 요소에 반영
$('#rail_length').on('input', function() {
$('#display_rail_length').val($(this).val());
});
// rail_width 입력이 변경될 때 아래 요소에 반영
$('#rail_width').on('input', function() {
$('#display_rail_width').val($(this).val());
});
$("#viewBtn").on("click", function() {
var num = $(this).data("num"); // 'data-num' 속성 값 가져오기
viewUnfold('modify', num); // 가져온 num 값을 함수에 전달
});
$("#copyBtn").on("click", function() { // 복사버튼
var num = $(this).data("num"); // 'data-num' 속성 값 가져오기
$("#myModal").hide();
$(".modal_detail").html(''); // 모달 내용을 비움
loadForm_guiderail('copy', num);
});
$("#modifyBtn").on("click", function() { // 수정버튼
var num = $(this).data("num"); // 'data-num' 속성 값 가져오기
$("#myModal").hide();
$(".modal_detail").html(''); // 모달 내용을 비움
loadForm_guiderail('modify', num);
});
// 조회인 경우 사용금지 처리
if (mode === 'view')
$('.viewmode').prop('disabled', true); // Disable all input, textarea, and select elements
else
$('.viewmode').prop('disabled', false); // Disable all input, textarea, and select elements
let isSaving = false;
$("#saveBtn").on("click", function() {
if (isSaving) return;
isSaving = true;
var header = $("#header").val();
// 모델 유형 확인
const modelType = $('input[name="model_type"]:checked').val();
if (modelType === 'assembly') {
// 조립 모델일 경우, 현재 부품 배열을 JSON 문자열로 만들어 숨겨진 필드에 저장
$("#bending_components_data").val(JSON.stringify(assemblyParts));
} else {
// 표준 모델일 경우, 숨겨진 필드를 비움
$("#bending_components_data").val('');
}
var formData = $("#board_form").serialize();
$.ajax({
url: "/guiderail/process.php",
type: "post",
data: formData,
dataType: 'json',
success: function(response) {
console.log('response data ', response);
Toastify({
text: "저장완료",
duration: 1000,
close: true,
gravity: "top",
position: "center",
backgroundColor: "#4fbe87",
}).showToast();
setTimeout(function() {
location.reload();
}, 1000);
},
error: function(jqxhr, status, error) {
console.log(jqxhr, status, error);
isSaving = false;
}
});
});
$("#deleteBtn").on("click", function() {
var level = '<?= $_SESSION["level"] ?>';
if (level !== '1') {
Swal.fire({
title: '삭제불가',
text: "관리자만 삭제 가능합니다.",
icon: 'error',
confirmButtonText: '확인'
});
return;
}
Swal.fire({
title: '자료 삭제',
text: "삭제는 신중! 정말 삭제하시겠습니까?",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: '삭제',
cancelButtonText: '취소'
}).then((result) => {
if (result.isConfirmed) {
$("#mode").val('delete');
var formData = $("#board_form").serialize();
$.ajax({
url: "/guiderail/process.php",
type: "post",
data: formData,
success: function(response) {
Toastify({
text: "파일 삭제완료",
duration: 2000,
close: true,
gravity: "top",
position: "center",
style: {
background: "linear-gradient(to right, #00b09b, #96c93d)"
},
}).showToast();
$("#myModal").hide();
location.reload();
},
error: function(jqxhr, status, error) {
console.log(jqxhr, status, error);
}
});
}
});
});
// 이벤트 위임 - 삭제 버튼 클릭
$(document).on('click', '.remove-col', function() {
const $wrapper = $(this).closest('.col-cell');
const idx = $wrapper.index(); // 몇 번째 열인지
// mode가 view가 아닐때 해당 열(인덱스) 전체를 지움
if ($('#mode').val() !== 'view') {
$('#assemblyTable tbody .input-container').each(function() {
$(this).find('.col-cell').eq(idx).remove();
});
// assemblyParts 배열에서도 해당 인덱스 제거
assemblyParts.splice(idx, 1);
// 번호 다시 매기기
$('#assemblyTable tbody tr:first .col-cell span').each(function(i) {
$(this).text(i + 1);
});
alertToast('열삭제');
}
});
},
error: function(jqxhr, status, error) {
console.log("AJAX Error: ", status, error);
}
});
} // end of loadForm_guiderail
function viewUnfold(mode, num = null) {
var tablename = 'guiderail';
$.ajax({
type: "POST",
url: "/guiderail/fetch_flat.php",
data: { mode: mode, num: num, tablename: tablename },
dataType: "html",
success: function(response) {
$(".modal-body .ModalFlat_detail").html(response);
$("#ModalFlat").show();
$('#displayFlat_rail_length').val($('#rail_length').val());
$('#displayFlat_rail_width').val($('#rail_width').val());
// 전개도 모달을 닫을 때 HTML 요소 제거
$("#closeBtn").on("click", function() {
$("#ModalFlat").hide();
$(".ModalFlat_detail").html(''); // 모달 내용을 비움
});
$(".closeBtn").on("click", function() {
$("#ModalFlat").hide();
$(".ModalFlat_detail").html(''); // 모달 내용을 비움
$('.viewmode').prop('disabled', false); // 다시 활성화
});
// PHP에서 /guiderail/guiderail.json 파일의 내용을 JavaScript 변수에 로드
var guiderailImages = <?php
$jsonFile = $_SERVER['DOCUMENT_ROOT'].'/guiderail/guiderail.json';
if(file_exists($jsonFile)){
echo file_get_contents($jsonFile);
} else {
echo '[]';
}
?>;
// checkImage는 이미지 엘리먼트(jQuery 객체) 예: var checkImage = $('#checkImage');
function updateImage(model, checkType, finishing_type ) {
let imagePath = '';
console.log('guiderailImages',guiderailImages);
console.log('model',model);
console.log('finishing_type',finishing_type);
console.log('checkType',checkType);
// guiderailImages 배열에서 model과 check_type에 일치하는 항목 검색
if (Array.isArray(guiderailImages)) {
let found = guiderailImages.find(function(item) {
// model은 JSON의 model_name과 비교, checkType은 JSON의 check_type과 비교
return item.model_name === model && item.check_type === checkType && item.finishing_type === finishing_type ;
});
if (found) {
imagePath = found.image;
}
}
$('#checkImageFlat').attr('src', imagePath);
}
// PHP 변수($selected_model_name, $check_type)를 JavaScript로 전달하여 updateImage() 함수 호출
var selectedProdModel = $("#selected_model_name").val();
var selected_check_type = $("#selected_check_type").val();
var selected_finishing_type = $("#selected_finishing_type").val();
console.log('selectedProdModel', selectedProdModel);
console.log('selected_check_type', selected_check_type);
console.log('selected_finishing_type', selected_finishing_type);
updateImage(selectedProdModel, selected_check_type, selected_finishing_type);
},
error: function(jqxhr, status, error) {
console.log("AJAX Error: ", status, error);
}
});
}
function viewWork(num) {
// 이벤트의 기본 동작을 방지 (모달창 닫힘 방지)
event.preventDefault();
var tablename = 'guiderail'
var url = "view.php?mode=view&num=" + num + "&tablename=" + tablename;
customPopup(url, '절곡 작업지시서', 1200, 850);
}
// 테이블을 다시 그린 직후, 또는 addColumn/addInitialColumn 끝에 호출하세요.
function wrapColumnsAndAttachRemove() {
$('#assemblyTable tbody tr').each(function(rowIdx) {
const $cell = $(this).find('td.input-container');
// 이미 wrap 되어 있지 않은 직접 자식(input, span 등)만 골라서 감싸기
$cell
.contents()
.filter(function() {
return this.nodeType === 1 && !$(this).closest('.col-cell').length;
})
.each(function() {
$(this).wrap('<div class="col-cell"></div>');
});
});
// 첫 번째 행(col-cell)마다 삭제 버튼 붙이기 (한번만)
$('#assemblyTable tbody tr:first .col-cell').each(function(idx) {
if (!$(this).find('.remove-col').length) {
$(this).append('<button type="button" class="remove-col"></button>');
}
});
}
</script>