"use client"; import React, { useState, useEffect } from 'react'; import { Dialog, DialogTitle, DialogContent, DialogActions, Button, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, Chip, Typography, } from '@mui/material'; import PrintIcon from '@mui/icons-material/Print'; import { fetchSemiFGItemCodes, fetchSemiFGItemCodesWithCategory, generateSemiFGProductionAnalysisReport, ItemCodeWithCategory, } from './semiFGProductionAnalysisApi'; interface SemiFGProductionAnalysisReportProps { criteria: Record; requiredFieldLabels: string[]; loading: boolean; setLoading: (loading: boolean) => void; reportTitle?: string; } export default function SemiFGProductionAnalysisReport({ criteria, requiredFieldLabels, loading, setLoading, reportTitle = '成品/半成品生產分析報告', }: SemiFGProductionAnalysisReportProps) { const [showConfirmDialog, setShowConfirmDialog] = useState(false); const [selectedItemCodesInfo, setSelectedItemCodesInfo] = useState([]); const [itemCodesWithCategory, setItemCodesWithCategory] = useState>({}); // Fetch item codes with category when stockCategory changes useEffect(() => { const stockCategory = criteria.stockCategory || ''; if (stockCategory) { fetchSemiFGItemCodesWithCategory(stockCategory) .then((items) => { const categoryMap: Record = {}; items.forEach((item) => { categoryMap[item.code] = item; }); setItemCodesWithCategory((prev) => ({ ...prev, ...categoryMap })); }) .catch((error) => { console.error('Failed to fetch item codes with category:', error); }); } }, [criteria.stockCategory]); const handlePrintClick = async () => { // Validate required fields if (requiredFieldLabels.length > 0) { alert(`缺少必填條件:\n- ${requiredFieldLabels.join('\n- ')}`); return; } // If no itemCode is selected, print directly without confirmation if (!criteria.itemCode) { await executePrint(); return; } // If itemCode is selected, show confirmation dialog const selectedCodes = criteria.itemCode.split(',').filter((code) => code.trim()); const itemCodesInfo: ItemCodeWithCategory[] = selectedCodes.map((code) => { const codeTrimmed = code.trim(); const categoryInfo = itemCodesWithCategory[codeTrimmed]; return { code: codeTrimmed, category: categoryInfo?.category || 'Unknown', name: categoryInfo?.name || '', }; }); setSelectedItemCodesInfo(itemCodesInfo); setShowConfirmDialog(true); }; const executePrint = async () => { setLoading(true); try { await generateSemiFGProductionAnalysisReport(criteria, reportTitle); setShowConfirmDialog(false); } catch (error) { console.error('Failed to generate report:', error); alert('An error occurred while generating the report. Please try again.'); } finally { setLoading(false); } }; return ( <> {/* Confirmation Dialog for 成品/半成品生產分析報告 */} setShowConfirmDialog(false)} maxWidth="md" fullWidth > 已選擇的物料編號以及列印成品/半成品生產分析報告 請確認以下已選擇的物料編號及其類別: 物料編號及名稱 類別 {selectedItemCodesInfo.map((item, index) => { const displayName = item.name ? `${item.code} ${item.name}` : item.code; return ( {displayName} ); })}
); }