452 lines
20 KiB
JavaScript
452 lines
20 KiB
JavaScript
document.addEventListener('DOMContentLoaded', () => {
|
|
// --- DOM Elements ---
|
|
const machineComponent = document.getElementById('machine-component');
|
|
const settingsModal = document.getElementById('settings-modal');
|
|
const closeModalBtn = document.getElementById('close-modal-btn');
|
|
const cancelSettingsBtn = document.getElementById('cancel-settings-btn');
|
|
const saveSettingsBtn = document.getElementById('save-settings-btn');
|
|
const addStepBtn = document.getElementById('add-step-btn');
|
|
const stepsContainer = document.getElementById('steps-container');
|
|
const machineNameInput = document.getElementById('machine-name-input');
|
|
const batchQuantityInput = document.getElementById('batch-quantity-input');
|
|
const hasCacheCheckbox = document.getElementById('has-cache-checkbox');
|
|
const cacheQuantityInput = document.getElementById('cache-quantity-input');
|
|
const totalTimeDisplay = document.getElementById('total-time-display');
|
|
const calculatedPpmDisplay = document.getElementById('calculated-ppm-display');
|
|
const machineNameDisplay = document.getElementById('machine-name-display');
|
|
const theoreticalPpmDisplay = document.getElementById('theoretical-ppm');
|
|
const modalTitle = document.getElementById('modal-title');
|
|
const statusIndicator = machineComponent.querySelector('.status-indicator'); // Get status indicator
|
|
const machineStatus = document.getElementById('machine-status'); // Get status text element
|
|
|
|
// --- State ---
|
|
let steps = []; // Array to hold step data
|
|
let initialSettings = {}; // To store settings when modal opens
|
|
let isActive = false; // Track if the machine is considered active
|
|
let isDisabled = false; // Track if machine is disabled (batch=0)
|
|
|
|
// --- Functions ---
|
|
|
|
// Helper function to update status text AND indicator light
|
|
const updateMachineStatus = (newStatusText) => {
|
|
machineStatus.textContent = newStatusText;
|
|
statusIndicator.classList.remove('active', 'disabled'); // Clear previous state classes
|
|
isDisabled = false;
|
|
isActive = false;
|
|
|
|
if (newStatusText === '运行中') {
|
|
statusIndicator.classList.add('active');
|
|
isActive = true;
|
|
} else if (newStatusText === '禁用中') {
|
|
statusIndicator.classList.add('disabled');
|
|
isDisabled = true;
|
|
} else {
|
|
// Default: Waiting (yellow pulse) - no specific class needed
|
|
}
|
|
|
|
// Store the current text and state in case modal is opened later
|
|
if (initialSettings) { // Prevent error during initial load
|
|
initialSettings.statusText = newStatusText;
|
|
initialSettings.isActive = isActive;
|
|
initialSettings.isDisabled = isDisabled;
|
|
}
|
|
};
|
|
|
|
// --- Validation Helpers ---
|
|
const clearValidationErrors = () => {
|
|
const errorMessages = settingsModal.querySelectorAll('.error-message');
|
|
errorMessages.forEach(msg => {
|
|
msg.textContent = '';
|
|
msg.style.display = 'none';
|
|
});
|
|
const invalidInputs = settingsModal.querySelectorAll('.invalid');
|
|
invalidInputs.forEach(input => input.classList.remove('invalid'));
|
|
};
|
|
|
|
const showValidationError = (inputElement, message) => {
|
|
inputElement.classList.add('invalid');
|
|
const errorSpanId = inputElement.id + '-error'; // Assumes error span ID convention
|
|
const errorSpan = document.getElementById(errorSpanId);
|
|
if (errorSpan) {
|
|
errorSpan.textContent = message;
|
|
errorSpan.style.display = 'block';
|
|
}
|
|
// Focus the first invalid element found
|
|
if (!settingsModal.querySelector('.invalid:focus')) {
|
|
inputElement.focus();
|
|
}
|
|
};
|
|
|
|
// Function to remove error state when user types
|
|
const clearErrorOnInput = (event) => {
|
|
const inputElement = event.target;
|
|
inputElement.classList.remove('invalid');
|
|
const errorSpanId = inputElement.id + '-error';
|
|
const errorSpan = document.getElementById(errorSpanId);
|
|
if (errorSpan) {
|
|
errorSpan.textContent = '';
|
|
errorSpan.style.display = 'none';
|
|
}
|
|
};
|
|
|
|
// --- Main Validation Logic ---
|
|
const validateSettings = () => {
|
|
clearValidationErrors();
|
|
let isValid = true;
|
|
const errors = [];
|
|
|
|
// 1. Check Machine Name
|
|
if (!machineNameInput.value.trim()) {
|
|
showValidationError(machineNameInput, '机构名称不能为空');
|
|
isValid = false;
|
|
errors.push('机构名称不能为空');
|
|
}
|
|
|
|
// 2. Check Batch Quantity
|
|
const batchQuantityValue = batchQuantityInput.value;
|
|
if (batchQuantityValue === '' || !Number.isInteger(Number(batchQuantityValue)) || Number(batchQuantityValue) < 0) {
|
|
showValidationError(batchQuantityInput, '批量处理数量必须是非负整数');
|
|
isValid = false;
|
|
errors.push('批量处理数量必须是非负整数');
|
|
}
|
|
|
|
// 3. Check Steps
|
|
steps.forEach((step, index) => {
|
|
const stepIndexDisplay = index + 1;
|
|
// Check Step Name
|
|
if (!step.nameInput.value.trim()) {
|
|
showValidationError(step.nameInput, `步骤 ${stepIndexDisplay} 名称不能为空`);
|
|
isValid = false;
|
|
errors.push(`步骤 ${stepIndexDisplay} 名称不能为空`);
|
|
}
|
|
// Add listeners to step inputs dynamically if not already added
|
|
if (!step.nameInput.dataset.listenerAdded) {
|
|
step.nameInput.addEventListener('input', clearErrorOnInput);
|
|
step.nameInput.dataset.listenerAdded = 'true';
|
|
}
|
|
// Note: We are not validating start/work time based on requirements, only name
|
|
});
|
|
|
|
// 4. Check Cache Quantity (if applicable)
|
|
if (hasCacheCheckbox.checked) {
|
|
const cacheQuantityValue = cacheQuantityInput.value;
|
|
if (cacheQuantityValue === '' || !Number.isInteger(Number(cacheQuantityValue)) || Number(cacheQuantityValue) <= 0) {
|
|
showValidationError(cacheQuantityInput, '缓存数量必须是大于0的整数');
|
|
isValid = false;
|
|
errors.push('缓存数量必须是大于0的整数');
|
|
}
|
|
}
|
|
|
|
if (!isValid) {
|
|
// Optionally display a summary alert, though inline errors are better UX
|
|
// alert('请修正以下错误:\n- ' + errors.join('\n- '));
|
|
}
|
|
|
|
return isValid;
|
|
};
|
|
|
|
// Calculate Total Time and Theoretical PPM
|
|
const calculateMetrics = () => {
|
|
let totalDuration = 0;
|
|
let maxEndTime = 0;
|
|
|
|
steps.forEach(step => {
|
|
const startTime = parseFloat(step.startTimeInput.value) || 0;
|
|
const workTime = parseFloat(step.workTimeInput.value) || 0;
|
|
const endTime = startTime + workTime;
|
|
if (endTime > maxEndTime) {
|
|
maxEndTime = endTime;
|
|
}
|
|
});
|
|
|
|
totalDuration = maxEndTime;
|
|
totalTimeDisplay.textContent = totalDuration.toFixed(2);
|
|
|
|
const batchQuantityRaw = batchQuantityInput.value;
|
|
let batchQuantity = 1; // Default if invalid for calculation display
|
|
|
|
// Use valid integer for calculation, default to 1 if invalid or 0
|
|
if (batchQuantityRaw !== '' && Number.isInteger(Number(batchQuantityRaw)) && Number(batchQuantityRaw) > 0) {
|
|
batchQuantity = parseInt(batchQuantityRaw);
|
|
}
|
|
|
|
let calculatedPpm = 0;
|
|
if (totalDuration > 0) {
|
|
calculatedPpm = (60 / totalDuration) * batchQuantity;
|
|
}
|
|
calculatedPpmDisplay.textContent = calculatedPpm.toFixed(2);
|
|
};
|
|
|
|
// Update Step Titles (e.g., "步骤 1", "步骤 2")
|
|
const updateStepTitles = () => {
|
|
steps.forEach((step, index) => {
|
|
step.element.querySelector('.step-title').textContent = `步骤 ${index + 1}`;
|
|
step.element.dataset.index = index; // Update data-index for reordering
|
|
});
|
|
calculateMetrics(); // Recalculate when steps change order/number
|
|
};
|
|
|
|
// Create HTML for a single step
|
|
const createStepElement = (stepData = {}, index) => {
|
|
const stepId = `step-${Date.now()}-${Math.random()}`;
|
|
const stepDiv = document.createElement('div');
|
|
stepDiv.classList.add('step-item');
|
|
stepDiv.id = stepId;
|
|
stepDiv.dataset.index = index;
|
|
|
|
stepDiv.innerHTML = `
|
|
<div class="step-header">
|
|
<span class="step-title">步骤 ${index + 1}</span>
|
|
<div class="step-controls">
|
|
<button class="step-btn move-up-btn" title="上移">↑</button>
|
|
<button class="step-btn move-down-btn" title="下移">↓</button>
|
|
<button class="step-btn delete-step-btn" title="删除">✖</button>
|
|
</div>
|
|
</div>
|
|
<div class="step-inputs">
|
|
<div class="form-group">
|
|
<label for="step-name-${stepId}">名称:</label>
|
|
<input type="text" id="step-name-${stepId}" class="step-name-input" value="${stepData.name || `步骤${index + 1}`}" maxlength="12" required>
|
|
<span class="error-message step-error" id="step-name-error-${stepId}"></span>
|
|
</div>
|
|
<div class="form-group">
|
|
<label for="step-start-${stepId}">开始时间(秒):</label>
|
|
<input type="number" id="step-start-${stepId}" class="step-start-input" value="${stepData.startTime || 0}" min="0" step="0.1">
|
|
<span class="error-message step-error" id="step-start-error-${stepId}"></span>
|
|
</div>
|
|
<div class="form-group">
|
|
<label for="step-work-${stepId}">工作时间(秒):</label>
|
|
<input type="number" id="step-work-${stepId}" class="step-work-input" value="${stepData.workTime || 0}" min="0" step="0.1">
|
|
<span class="error-message step-error" id="step-work-error-${stepId}"></span>
|
|
</div>
|
|
</div>
|
|
`;
|
|
|
|
// Add event listeners for controls within this step
|
|
stepDiv.querySelector('.delete-step-btn').addEventListener('click', () => deleteStep(stepId));
|
|
stepDiv.querySelector('.move-up-btn').addEventListener('click', () => moveStep(stepId, -1));
|
|
stepDiv.querySelector('.move-down-btn').addEventListener('click', () => moveStep(stepId, 1));
|
|
|
|
// Add listeners to inputs for real-time calculation and error clearing
|
|
const nameInput = stepDiv.querySelector('.step-name-input');
|
|
const startTimeInput = stepDiv.querySelector('.step-start-input');
|
|
const workTimeInput = stepDiv.querySelector('.step-work-input');
|
|
|
|
[startTimeInput, workTimeInput, batchQuantityInput].forEach(input => {
|
|
input.addEventListener('input', calculateMetrics);
|
|
});
|
|
// Add input listener for validation clearing (only needed once per element)
|
|
if (!nameInput.dataset.listenerAdded) {
|
|
nameInput.addEventListener('input', clearErrorOnInput);
|
|
nameInput.dataset.listenerAdded = 'true';
|
|
}
|
|
|
|
return { element: stepDiv, id: stepId, nameInput, startTimeInput, workTimeInput };
|
|
};
|
|
|
|
// Add a new step
|
|
const addStep = (stepData = {}) => {
|
|
const newIndex = steps.length;
|
|
const newStep = createStepElement(stepData, newIndex);
|
|
stepsContainer.appendChild(newStep.element);
|
|
steps.push(newStep);
|
|
updateStepTitles();
|
|
};
|
|
|
|
// Delete a step
|
|
const deleteStep = (stepId) => {
|
|
const stepIndex = steps.findIndex(s => s.id === stepId);
|
|
if (stepIndex > -1) {
|
|
steps[stepIndex].element.remove();
|
|
steps.splice(stepIndex, 1);
|
|
updateStepTitles();
|
|
}
|
|
};
|
|
|
|
// Move a step up or down
|
|
const moveStep = (stepId, direction) => {
|
|
const index = steps.findIndex(s => s.id === stepId);
|
|
const newIndex = index + direction;
|
|
|
|
if (newIndex >= 0 && newIndex < steps.length) {
|
|
// Visual feedback
|
|
const currentElement = steps[index].element;
|
|
currentElement.classList.add('moving');
|
|
setTimeout(() => {
|
|
currentElement.classList.remove('moving');
|
|
// Also remove from the swapped element if it had the class briefly
|
|
if (steps[newIndex] && steps[newIndex].element) {
|
|
steps[newIndex].element.classList.remove('moving');
|
|
}
|
|
}, 300); // Match CSS transition duration
|
|
|
|
// Swap in the steps array
|
|
[steps[index], steps[newIndex]] = [steps[newIndex], steps[index]];
|
|
|
|
// Re-insert elements in the DOM based on the new order
|
|
stepsContainer.innerHTML = ''; // Clear container
|
|
steps.forEach(step => stepsContainer.appendChild(step.element)); // Re-append in new order
|
|
|
|
updateStepTitles();
|
|
}
|
|
};
|
|
|
|
// Toggle Cache Quantity Input
|
|
const toggleCacheInput = () => {
|
|
const isChecked = hasCacheCheckbox.checked;
|
|
cacheQuantityInput.disabled = !isChecked;
|
|
if (isChecked) {
|
|
cacheQuantityInput.required = true; // Make required when checked
|
|
} else {
|
|
cacheQuantityInput.required = false; // Not required when unchecked
|
|
cacheQuantityInput.value = ''; // Clear value when disabled
|
|
// Clear potential validation error when disabling
|
|
cacheQuantityInput.classList.remove('invalid');
|
|
const errorSpan = document.getElementById('cache-quantity-input-error');
|
|
if (errorSpan) {
|
|
errorSpan.textContent = '';
|
|
errorSpan.style.display = 'none';
|
|
}
|
|
}
|
|
};
|
|
|
|
// Open Settings Modal
|
|
const openModal = () => {
|
|
clearValidationErrors(); // Clear errors when opening
|
|
// Store current settings to revert on cancel
|
|
initialSettings = {
|
|
name: machineNameInput.value,
|
|
batchQuantity: batchQuantityInput.value,
|
|
hasCache: hasCacheCheckbox.checked,
|
|
cacheQuantity: cacheQuantityInput.value,
|
|
stepsData: steps.map(s => ({ // Only store values, not elements
|
|
name: s.nameInput.value,
|
|
startTime: s.startTimeInput.value,
|
|
workTime: s.workTimeInput.value
|
|
})),
|
|
// Store current display state
|
|
isActive: statusIndicator.classList.contains('active'),
|
|
isDisabled: statusIndicator.classList.contains('disabled'), // Store disabled state
|
|
statusText: machineStatus.textContent,
|
|
theoreticalPPM: theoreticalPpmDisplay.textContent, // Store the actual text content
|
|
currentStep: document.getElementById('current-step').textContent,
|
|
currentPPM: document.getElementById('current-ppm').textContent
|
|
};
|
|
|
|
// Update modal title
|
|
modalTitle.textContent = `编辑-${initialSettings.name || '一般机构'}`;
|
|
|
|
settingsModal.style.display = 'flex';
|
|
calculateMetrics(); // Ensure calculations are up-to-date when opening
|
|
};
|
|
|
|
// Close Settings Modal
|
|
const closeModal = () => {
|
|
settingsModal.style.display = 'none';
|
|
};
|
|
|
|
// Revert settings to initial state (on cancel or 'X' click)
|
|
const revertSettings = () => {
|
|
clearValidationErrors(); // Clear validation errors on revert/cancel
|
|
machineNameInput.value = initialSettings.name;
|
|
batchQuantityInput.value = initialSettings.batchQuantity;
|
|
hasCacheCheckbox.checked = initialSettings.hasCache;
|
|
cacheQuantityInput.value = initialSettings.cacheQuantity;
|
|
toggleCacheInput(); // This also handles required attribute
|
|
|
|
// Rebuild steps from initial data
|
|
stepsContainer.innerHTML = '';
|
|
steps = [];
|
|
initialSettings.stepsData.forEach(stepData => addStep(stepData));
|
|
|
|
// Revert main display state using the helper function for status
|
|
machineNameDisplay.textContent = initialSettings.name;
|
|
theoreticalPpmDisplay.textContent = initialSettings.theoreticalPPM; // Use stored text
|
|
updateMachineStatus(initialSettings.statusText); // This updates text AND indicator class
|
|
document.getElementById('current-step').textContent = initialSettings.currentStep;
|
|
document.getElementById('current-ppm').textContent = initialSettings.currentPPM;
|
|
|
|
closeModal();
|
|
};
|
|
|
|
// Save Settings
|
|
const saveSettings = () => {
|
|
if (!validateSettings()) {
|
|
console.log("Validation failed."); // Debug log
|
|
// Optionally show a general error message at the top/bottom?
|
|
// alert("请检查表单中的错误并修正。");
|
|
return; // Stop saving if validation fails
|
|
}
|
|
|
|
console.log("Validation passed."); // Debug log
|
|
|
|
// Validation passed, proceed with saving
|
|
const newName = machineNameInput.value.trim();
|
|
const batchQty = parseInt(batchQuantityInput.value); // Already validated as integer
|
|
|
|
machineNameDisplay.textContent = newName;
|
|
calculateMetrics(); // Recalculate with potentially changed batch qty
|
|
theoreticalPpmDisplay.textContent = calculatedPpmDisplay.textContent + 'PPM';
|
|
|
|
// Update status based on batch quantity
|
|
if (batchQty === 0) {
|
|
updateMachineStatus('禁用中');
|
|
} else {
|
|
// Set to '运行中' or potentially another state based on future logic
|
|
// For now, assume it goes to '运行中' if not disabled
|
|
updateMachineStatus('运行中');
|
|
}
|
|
|
|
// Update current step/ppm (example) - might need real logic later
|
|
document.getElementById('current-step').textContent = steps.length > 0 ? steps[0].nameInput.value : '无步骤';
|
|
document.getElementById('current-ppm').textContent = '0.00PPM'; // Reset or calculate actual current
|
|
|
|
closeModal();
|
|
};
|
|
|
|
// --- Event Listeners ---
|
|
machineComponent.addEventListener('dblclick', openModal);
|
|
closeModalBtn.addEventListener('click', revertSettings);
|
|
cancelSettingsBtn.addEventListener('click', revertSettings);
|
|
saveSettingsBtn.addEventListener('click', saveSettings);
|
|
addStepBtn.addEventListener('click', () => addStep());
|
|
hasCacheCheckbox.addEventListener('change', toggleCacheInput);
|
|
|
|
// Add listeners to clear errors on input for main fields
|
|
machineNameInput.addEventListener('input', clearErrorOnInput);
|
|
batchQuantityInput.addEventListener('input', clearErrorOnInput);
|
|
cacheQuantityInput.addEventListener('input', clearErrorOnInput);
|
|
|
|
// --- Initialization ---
|
|
const initialize = () => {
|
|
// Add default steps as per the image
|
|
addStep({ name: '步骤1', startTime: 0, workTime: 3 });
|
|
addStep({ name: '步骤2', startTime: 2, workTime: 3 });
|
|
|
|
// Set initial values based on the image (or defaults)
|
|
machineNameInput.value = '一般机构';
|
|
batchQuantityInput.value = 1;
|
|
hasCacheCheckbox.checked = true; // From image
|
|
cacheQuantityInput.value = 3; // From image
|
|
toggleCacheInput(); // Enable/disable and set required
|
|
|
|
// Initial calculation and display update
|
|
machineNameDisplay.textContent = machineNameInput.value;
|
|
calculateMetrics();
|
|
theoreticalPpmDisplay.textContent = calculatedPpmDisplay.textContent + 'PPM';
|
|
|
|
// Set default component state (can be customized)
|
|
document.getElementById('current-step').textContent = '步骤1'; // Example
|
|
document.getElementById('current-ppm').textContent = '0.00PPM'; // Example
|
|
updateMachineStatus('等待中'); // Use helper to set initial status
|
|
|
|
// Store initial theoretical PPM text correctly for revert
|
|
if (!initialSettings.theoreticalPPM) { // Ensure it's set only once initially
|
|
initialSettings.theoreticalPPM = theoreticalPpmDisplay.textContent;
|
|
}
|
|
// Clear any potential initial validation states on load
|
|
clearValidationErrors();
|
|
};
|
|
|
|
initialize();
|
|
});
|