337 lines
16 KiB
TypeScript
337 lines
16 KiB
TypeScript
'use client'
|
|
import { postData } from '@/components/lib/api'
|
|
import FileUploadForm from '@/components/ui/fileUploadForm'
|
|
import FormSection from '@/components/ui/formSection'
|
|
import { filePicked } from '@common/business_components/ui'
|
|
import { Button, DatePicker, Input } from '@common/components/ui'
|
|
import { zodResolver } from '@hookform/resolvers/zod'
|
|
import { useState } from 'react'
|
|
import { useForm } from 'react-hook-form'
|
|
import { z } from 'zod'
|
|
import { excelToflowRateData, excelToMatchingResultData, excelToTimePatternData } from '../../components/lib/utils/excelToJson'
|
|
import BaseLayout from '../BaseLayout'
|
|
|
|
const formSchema = z.object({
|
|
managenm: z.string(),
|
|
region: z.string(),
|
|
suyeonga: z.number(),
|
|
inputdate: z.coerce.date(),
|
|
rtkSource: z.string(),
|
|
suyeongaPlace: z.string(),
|
|
pattern: z.string()
|
|
})
|
|
|
|
// 각 파일 업로드 폼의 데이터를 저장할 인터페이스 정의
|
|
interface UploadedFileInfo {
|
|
file: File | null;
|
|
atflCd: string | null;
|
|
atflId: string | null;
|
|
// 필요하다면 파일 이름 등 추가 정보 저장 가능
|
|
// fileName: string;
|
|
}
|
|
|
|
// 초기 파일 정보 상태
|
|
const initialFileInfo: UploadedFileInfo = { file: null, atflCd: null, atflId: null };
|
|
|
|
const region: { text: string, val: number }[] = [{ text: '양평', val: 1 }, { text: '강남', val: 2 }, { text: 'test', val: 3 }];
|
|
|
|
const IrSetting = () => {
|
|
const form = useForm<z.infer<typeof formSchema>>({
|
|
resolver: zodResolver(formSchema),
|
|
defaultValues: {
|
|
managenm: "",
|
|
region: "",
|
|
suyeonga: 0,
|
|
inputdate: new Date(),
|
|
rtkSource: "",
|
|
suyeongaPlace: "",
|
|
pattern: ""
|
|
}
|
|
})
|
|
|
|
// FileUploadForm에서 전달받은 파일 정보를 저장할 상태 배열
|
|
// 각 인덱스는 FileUploadForm의 fileIdx와 매칭됨
|
|
// 예: 0: 오수관망도, 1: 수용가-맨홀, 2: 오수량 시간패턴, 3: 유량자료
|
|
const [uploadedFilesData, setUploadedFilesData] = useState<UploadedFileInfo[]>([
|
|
initialFileInfo, // 0: 오수관망도
|
|
initialFileInfo, // 1: 수용가-맨홀 매칭결과
|
|
initialFileInfo, // 2: 오수량 시간패턴
|
|
initialFileInfo // 3: 유량자료 등록
|
|
]);
|
|
|
|
const [selectedDate, setSelectedDate] = useState(new Date());
|
|
const [input1, setInput1] = useState('');
|
|
const [input2, setInput2] = useState('');
|
|
const [select1, setSelect1] = useState('');
|
|
const [select2, setSelect2] = useState('');
|
|
const [select3, setSelect3] = useState('');
|
|
const [select4, setSelect4] = useState('');
|
|
const [select5, setSelect5] = useState('');
|
|
const [formResetKey, setFormResetKey] = useState(0); // FileUploadForm 리셋을 위한 key 상태
|
|
|
|
// 폼 초기화 함수
|
|
const resetAllForms = () => {
|
|
form.reset({ // react-hook-form 초기화
|
|
managenm: "",
|
|
region: "",
|
|
suyeonga: 0,
|
|
inputdate: new Date(),
|
|
rtkSource: "",
|
|
suyeongaPlace: "",
|
|
pattern: ""
|
|
});
|
|
setUploadedFilesData([ // 파일 업로드 상태 초기화
|
|
initialFileInfo,
|
|
initialFileInfo,
|
|
initialFileInfo,
|
|
initialFileInfo
|
|
]);
|
|
setSelectedDate(new Date()); // 날짜 선택 초기화
|
|
setInput1(''); // 입력 필드 초기화
|
|
setInput2(''); // 입력 필드 초기화
|
|
setSelect1(''); // 선택 필드 초기화
|
|
setSelect2('');
|
|
setSelect3('');
|
|
setSelect4('');
|
|
setSelect5('');
|
|
setFormResetKey(prevKey => prevKey + 1); // FileUploadForm 재마운트를 위해 key 변경
|
|
// FileUploadForm 내부의 파일명 표시 등을 초기화하려면
|
|
// FileUploadForm 컴포넌트 자체에 reset 로직 또는 key 변경을 통한 재마운트 전략이 필요할 수 있습니다.
|
|
// 현재 구조에서는 FileUploadForm의 내부 상태를 직접 초기화하기 어렵습니다.
|
|
// 가장 간단한 방법은 FileUploadForm에 key prop을 주고, 초기화 시 key를 변경하여 강제로 재렌더링하는 것입니다.
|
|
// 예: <FileUploadForm key={formResetKey} ... /> setFormResetKey(prev => prev + 1)
|
|
};
|
|
|
|
// FileUploadForm의 onFileSelect prop으로 전달될 콜백 함수
|
|
const handleFileSelection = (
|
|
index: number, // FileUploadForm의 fileIdx 값
|
|
selectedFile: File | null,
|
|
cd: string | null,
|
|
id: string | null
|
|
) => {
|
|
setUploadedFilesData(prevData => {
|
|
const newData = [...prevData];
|
|
newData[index] = {
|
|
file: selectedFile,
|
|
atflCd: cd,
|
|
atflId: id,
|
|
};
|
|
return newData;
|
|
});
|
|
console.log(`Page: File data received for form index ${index}`, { fileName: selectedFile?.name, cd, id });
|
|
};
|
|
|
|
|
|
const registFile = async (analysisData: any) => {
|
|
console.log("Submitting combined analysis data to backend:", analysisData);
|
|
// 추후 API 엔드포인트에 맞게 URL 수정 필요
|
|
const data = await postData('v1/inftwtAnls', analysisData);
|
|
if (data.ok) {
|
|
alert("분석 데이터가 성공적으로 제출되었습니다.");
|
|
resetAllForms(); // 성공 시 폼 초기화 함수 호출
|
|
} else {
|
|
alert("분석 데이터 제출 중 오류가 발생했습니다.");
|
|
// resetAllForms(); // 실패 시 폼 초기화 함수 호출
|
|
}
|
|
};
|
|
|
|
// 버튼 클릭 핸들러
|
|
const handleAnalysisClick = async () => {
|
|
console.log(uploadedFilesData);
|
|
const file1 = uploadedFilesData[0]; // 오수관망도
|
|
const file2 = uploadedFilesData[1]; // 수용가-맨홀 매칭결과
|
|
const file3 = uploadedFilesData[2]; // 오수량 시간패턴
|
|
const file4 = uploadedFilesData[3]; // 유량자료
|
|
|
|
console.log("오수관망도 정보:", file1?.file);
|
|
console.log("수용가-맨홀 매칭결과 정보:", file2);
|
|
console.log("오수량 시간패턴 정보:", file3);
|
|
console.log("유량자료 정보:", file4);
|
|
|
|
// 모든 필수 파일이 선택되었는지 확인 (UploadedFileInfo 객체와 그 안의 file 객체 모두 확인)
|
|
if (!file1?.file || !file2?.file || !file3?.file || !file4?.file) {
|
|
alert('모든 분석용 파일을 선택해주세요.');
|
|
return;
|
|
}
|
|
|
|
// filePickers 구성 시 uploadedFilesData의 file 객체 사용
|
|
const filePickers = [
|
|
// filePicked 유틸리티가 File 객체를 직접 받는지, ArrayBuffer 등을 받는지 확인 필요
|
|
// 여기서는 File 객체를 받고, 내부적으로 ArrayBuffer로 변환하여 parser에 전달한다고 가정
|
|
{ file: file2, parser: excelToMatchingResultData },
|
|
{ file: file3, parser: excelToTimePatternData },
|
|
{ file: file4, parser: excelToflowRateData }
|
|
// 오수관망도 파일은 파싱 대상이 아닐 수 있으므로, 필요에 따라 추가/제외
|
|
];
|
|
|
|
try {
|
|
const parsedResults = await Promise.all(
|
|
filePickers.map(async ({ file, parser }) => {
|
|
if (!file || !file.file) return null; // fileInfo 객체 및 file 객체 null 체크
|
|
|
|
// filePicked 함수에 File 객체와 headerNum 전달
|
|
const jsonData = await filePicked(file.file, 0);
|
|
|
|
if (jsonData === undefined) {
|
|
console.warn(`Warning: filePicked returned undefined for ${file.file.name}`);
|
|
return {
|
|
fileName: file.file.name,
|
|
atflCd: file.atflCd,
|
|
atflId: file.atflId,
|
|
parsedData: null // 또는 적절한 기본값
|
|
};
|
|
}
|
|
|
|
// jsonData를 각 parser 함수로 처리
|
|
// parser 함수가 filePicked가 반환하는 JSON 형식을 직접 처리한다고 가정
|
|
const parsedDataBySpecificFunction = parser(jsonData);
|
|
|
|
return {
|
|
fileName: file.file.name,
|
|
atflCd: file.atflCd,
|
|
atflId: file.atflId,
|
|
parsedData: parsedDataBySpecificFunction
|
|
};
|
|
})
|
|
);
|
|
|
|
// 각 파싱 결과 접근
|
|
const matchingResultData = parsedResults.find(r => r && r.fileName === file2.file?.name)?.parsedData;
|
|
const timePatternData = parsedResults.find(r => r && r.fileName === file3.file?.name)?.parsedData;
|
|
const flowRateData = parsedResults.find(r => r && r.fileName === file4.file?.name)?.parsedData;
|
|
|
|
// 새로운 JSON 데이터 생성
|
|
const combinedAnalysisData = {
|
|
enoCd: select1, // 환경청코드
|
|
ctpvCd: select2, // 시도코드
|
|
sggCd: select3, // 시군구코드
|
|
swageTmplntCd: select4, // 하수처리장코드
|
|
swtrmtZoneCd: select5, // 하수처리구역코드
|
|
aplcnYmd: selectedDate.toISOString(), // 적용연월
|
|
dtrwSwtcRt: input1, // 오수전환율
|
|
anlsInfo: input2, // 분석정보
|
|
atflCd: file1?.atflCd, // 첨부파일CD
|
|
atflId: file1?.atflId, // 첨부파일ID
|
|
tbSnRcptrMhlMpng: matchingResultData, // 수용가-맨홀 매칭결과
|
|
tbSnHrPttn: timePatternData, // 오수량 시간패턴
|
|
tbSnOilqData: flowRateData, // 유량자료
|
|
};
|
|
|
|
console.log("통합 분석 데이터 (JSON):", combinedAnalysisData);
|
|
|
|
// 수정된 registFile 함수를 호출하여 combinedAnalysisData를 전송합니다.
|
|
await registFile(combinedAnalysisData);
|
|
|
|
} catch (error) {
|
|
console.error("파일 파싱 중 오류 발생:", error);
|
|
alert("파일 처리 중 오류가 발생했습니다.");
|
|
return;
|
|
}
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<BaseLayout
|
|
titleName={{ mainTitle: '침입수 분석', firstCardTitle: '침입수 분석 자료 입력', secondCardTitle: '실측자료 등록' }}
|
|
form={form}
|
|
onSubmitEvent={() => { }}
|
|
graphBtn={false}
|
|
searchBox={{ title: '분석 대장지역 선택' }} >
|
|
<div className="grid gap-4">
|
|
<FormSection name='suyeongaPlace' form={form} titleNm='▷ 오수관망도'>
|
|
<FileUploadForm
|
|
key={`file-upload-0-${formResetKey}`} // 폼 초기화를 위한 key
|
|
onFileSelect={(file, cd, id) => handleFileSelection(0, file, cd, id)}
|
|
showButton={false}
|
|
showPreview={true}
|
|
accept={""}
|
|
fileIdx={0} />
|
|
</FormSection>
|
|
<FormSection name='suyeonga' form={form} titleNm='▷ 수용가-맨홀 매칭결과'>
|
|
<FileUploadForm
|
|
key={`file-upload-1-${formResetKey}`} // 폼 초기화를 위한 key
|
|
onFileSelect={(file, cd, id) => handleFileSelection(1, file, cd, id)}
|
|
showButton={false}
|
|
showPreview={true}
|
|
accept={".xls, .xlsx, .xlsm, .xltx"}
|
|
fileIdx={1} />
|
|
{/* <Input id="fileNm" ref={fileInputRef1} type="file" accept=".xls, .xlsx, .xlsm, .xltx" /> */}
|
|
</FormSection>
|
|
<FormSection name='pattern' form={form} titleNm='▷ 오수량 시간패턴'>
|
|
<FileUploadForm
|
|
key={`file-upload-2-${formResetKey}`} // 폼 초기화를 위한 key
|
|
onFileSelect={(file, cd, id) => handleFileSelection(2, file, cd, id)}
|
|
showButton={false}
|
|
showPreview={true}
|
|
accept={".xls, .xlsx, .xlsm, .xltx"}
|
|
fileIdx={2} />
|
|
{/* <Input id="fileNm" ref={fileInputRef2} type="file" accept=".xls, .xlsx, .xlsm, .xltx" /> */}
|
|
</FormSection>
|
|
<FormSection
|
|
name='inputdate'
|
|
form={form}
|
|
titleNm='▷ 상수사용량 적용기간'>
|
|
<DatePicker
|
|
className="ml-5"
|
|
selected={selectedDate}
|
|
onSelect={(date: Date | undefined) => { if (date) setSelectedDate(date) }}
|
|
mode={"single"} />
|
|
</FormSection>
|
|
<FormSection
|
|
name='rtkSource'
|
|
form={form}
|
|
titleNm='▷ 오수전환율'>
|
|
<Input
|
|
value={input1}
|
|
onChange={(e) => {
|
|
const newValue = e.target.value;
|
|
|
|
if (newValue === "") {
|
|
setInput1(newValue);
|
|
return;
|
|
}
|
|
|
|
// 숫자와 '.'만 허용하고, '.'은 최대 하나인지 확인
|
|
const isValidChars = /^[0-9]*\.?[0-9]*$/.test(newValue);
|
|
if (!isValidChars) return; // 유효하지 않은 문자 또는 여러 개의 '.' 포함
|
|
|
|
// '.' 기호가 포함된 경우, 처음이나 끝에 오면 안 됨
|
|
if (newValue.includes('.') && newValue.startsWith('.')) return; // '.'이 처음에는 올 수 없음
|
|
|
|
setInput1(newValue);
|
|
}}
|
|
className="ml-5 h-[3.2rem] text-center text-xl w-[150px]"
|
|
placeholder="예: 0.75" />
|
|
</FormSection>
|
|
<FormSection
|
|
name='analysis information'
|
|
form={form}
|
|
titleNm='▷ 분석 정보'>
|
|
<Input
|
|
value={input2}
|
|
onChange={(e) => setInput2(e.target.value)}
|
|
className="ml-5 h-[3.2rem] text-center text-xl w-[150px]" />
|
|
</FormSection>
|
|
</div>
|
|
<div className="flex items-center gap-4">
|
|
<FormSection
|
|
name='region' form={form} titleNm='▷ 유량자료 등록'>
|
|
<FileUploadForm
|
|
key={`file-upload-3-${formResetKey}`} // 폼 초기화를 위한 key
|
|
onFileSelect={(file, cd, id) => handleFileSelection(3, file, cd, id)}
|
|
showButton={false}
|
|
showPreview={true}
|
|
accept={".xls, .xlsx, .xlsm, .xltx"}
|
|
fileIdx={3} />
|
|
{/* <Input id="fileNm" ref={fileInputRef3} type="file" accept=".xls, .xlsx, .xlsm, .xltx" /> */}
|
|
</FormSection>
|
|
<div className="flex justify-center mt-1">
|
|
<Button type="submit" onClick={handleAnalysisClick}>침입수분석 실행</Button>
|
|
</div>
|
|
</div>
|
|
</BaseLayout>
|
|
</>
|
|
)
|
|
}
|
|
|
|
export default IrSetting |