439 lines
21 KiB
TypeScript
439 lines
21 KiB
TypeScript
"use client"
|
|
|
|
import { postData } from '@/components/lib/api'
|
|
import FileUploadForm from "@/components/ui/fileUploadForm"
|
|
import FormSection from "@/components/ui/formSection"
|
|
import BaseLayout from "@/ii/BaseLayout"
|
|
import { DatePicker, filePicked } from "@common/business_components/ui"
|
|
import { Input } from "@common/components/ui"
|
|
import { zodResolver } from "@hookform/resolvers/zod"
|
|
import { Label } from '@radix-ui/react-label'
|
|
import { useState } from "react"
|
|
import { useFieldArray, useForm } from "react-hook-form"
|
|
import { z } from "zod"
|
|
import { excelToMatchingResultData, excelToRainData } from '../../components/lib/utils/excelToJson'
|
|
import { EditableFormTable, type EditableTableHeadItem } from '../../components/ui/EditableFormTable'
|
|
|
|
|
|
// zod 스키마 정의
|
|
const formSchema = z.object({
|
|
enoCd: z.string(), // 환경청코드
|
|
ctpvCd: z.string(), // 시도코드
|
|
sggCd: z.string(), // 시군구코드
|
|
swageTmplntCd: z.string(), // 하수처리장코드
|
|
swtrmtZoneCd: z.string(), // 하수처리구역코드
|
|
rtkSource: z.string(), // RTK계수 출처
|
|
rdiiArea: z.string(), // RDII 기여면적
|
|
unitFactors: z.array(z.object({ // 단위도 계수
|
|
response: z.string(),
|
|
R: z.string(),
|
|
T: z.string(),
|
|
K: z.string(),
|
|
})),
|
|
initialDepths: z.array(z.object({ // 초기 차단 깊이
|
|
response: z.string(),
|
|
Dmax: z.string(),
|
|
Drec: z.string(),
|
|
Do: z.string(),
|
|
})),
|
|
// osumap: z.instanceof(File).optional(), // 오수관망도
|
|
// matching: z.instanceof(File).optional(), // 수용가-맨홀 매칭결과
|
|
aplcnYm: z.string(), // 상수사용량 적용기간 (YYYYMM 형식)
|
|
rate: z.string(), // 오수전환율
|
|
// rain: z.instanceof(File).optional(), // 강우자료
|
|
analysisInfo: z.string().optional(), // 분석 정보
|
|
date: z.date(),
|
|
// date: z.coerce.date(),
|
|
})
|
|
// zod 스키마 타입 추론
|
|
type FormSchemaType = z.infer<typeof formSchema>;
|
|
// 기본 폼 값 정의 (테스트 편의를 위해 초기값 설정, 추후 삭제 필요)
|
|
const defaultFormValues: FormSchemaType = {
|
|
enoCd: "",
|
|
ctpvCd: "",
|
|
sggCd: "",
|
|
swageTmplntCd: "",
|
|
swtrmtZoneCd: "",
|
|
rtkSource: "출처",
|
|
rdiiArea: "123", // 문자열로 기본값 설정
|
|
unitFactors: [
|
|
{ response: "Short-Term", R: "0.040", T: "0.5", K: "1" }, // 문자열로 기본값 설정
|
|
{ response: "Medium-Term", R: "0.005", T: "1", K: "2" },
|
|
{ response: "Long-Term", R: "0.005", T: "2", K: "3" },
|
|
],
|
|
initialDepths: [
|
|
{ response: "Short-Term", Dmax: "0", Drec: "0", Do: "0" }, // 문자열로 기본값 설정
|
|
{ response: "Medium-Term", Dmax: "0", Drec: "0", Do: "0" },
|
|
{ response: "Long-Term", Dmax: "0", Drec: "0", Do: "0" },
|
|
],
|
|
// osumap: undefined,
|
|
// matchingResultFile: undefined,
|
|
aplcnYm: "",
|
|
rate: "0.8", // 문자열로 기본값 설정
|
|
// rainFile: undefined,
|
|
analysisInfo: "test 분석정보",
|
|
date: new Date(),
|
|
};
|
|
|
|
// 각 파일 업로드 폼의 데이터를 저장할 인터페이스 정의
|
|
interface UploadedFileInfo {
|
|
file: File | null;
|
|
atflCd: string | null;
|
|
atflId: string | null;
|
|
}
|
|
|
|
// 초기 파일 정보 상태
|
|
const initialFileInfo: UploadedFileInfo = { file: null, atflCd: null, atflId: null };
|
|
|
|
interface ApiSelectOption {
|
|
text: string;
|
|
val: string;
|
|
}
|
|
|
|
export default function RTKForm() {
|
|
const [formResetKey, setFormResetKey] = useState(0); // FileUploadForm 리셋을 위한 key 상태
|
|
const [isLoadingResult, setIsLoadingResult] = useState<boolean>(false); // 로딩 상태
|
|
|
|
// FileUploadForm에서 전달받은 파일 정보를 저장할 상태 배열
|
|
// 각 인덱스는 FileUploadForm의 fileIdx와 매칭됨
|
|
const [uploadedFilesData, setUploadedFilesData] = useState<UploadedFileInfo[]>([
|
|
initialFileInfo, // 0: 오수관망도
|
|
initialFileInfo, // 1: 수용가-맨홀 매칭결과
|
|
initialFileInfo, // 2: 강우자료
|
|
]);
|
|
|
|
const [select1, setSelect1] = useState('0'); // 환경청코드 (enoCd)
|
|
const [select2, setSelect2] = useState('0'); // 시도코드 (ctpvCd)
|
|
const [select3, setSelect3] = useState<ApiSelectOption>({ val: '0', text: '전체' }); // 시군구 (sggCd)
|
|
const [select4, setSelect4] = useState<string | number>('0'); // 하수처리장 (swageTmplntCd)
|
|
const [select5, setSelect5] = useState<string | number>('0'); // 하수처리구역 (swtrmtZoneCd)
|
|
|
|
|
|
// form 인스턴스 생성
|
|
const form = useForm<FormSchemaType>({
|
|
resolver: zodResolver(formSchema),
|
|
defaultValues: defaultFormValues
|
|
});
|
|
|
|
// 폼 초기화 함수
|
|
const resetAllForms = () => {
|
|
form.reset(defaultFormValues); // 폼 값 초기화
|
|
setUploadedFilesData([ // 파일 업로드 상태 초기화 (3개 파일)
|
|
initialFileInfo,
|
|
initialFileInfo,
|
|
initialFileInfo,
|
|
]);
|
|
setFormResetKey(prevKey => prevKey + 1); // FileUploadForm 재마운트를 위해 key 변경
|
|
setSelect1('0');
|
|
setSelect2('0');
|
|
setSelect3({ val: '0', text: '전체' });
|
|
setSelect4('0');
|
|
setSelect5('0');
|
|
};
|
|
|
|
// 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");
|
|
// 추후 API 엔드포인트에 맞게 URL 수정 필요
|
|
const data = await postData('v1/rdiiAnls', analysisData);
|
|
if (data) {
|
|
alert("분석 데이터가 성공적으로 제출되었습니다.");
|
|
resetAllForms(); // 성공 시 폼 초기화 함수 호출
|
|
} else alert("분석 데이터 제출 중 오류가 발생했습니다.");
|
|
};
|
|
|
|
// 침입수 분석 실행 버튼 클릭 핸들러
|
|
const handleAnalysisClick = async () => {
|
|
setIsLoadingResult(true); // 로딩 상태 시작
|
|
const formData = form.getValues();
|
|
console.log(uploadedFilesData);
|
|
const file1 = uploadedFilesData[0]; // 오수관망도
|
|
const file2 = uploadedFilesData[1]; // 수용가-맨홀 매칭결과
|
|
const file3 = uploadedFilesData[2]; // 강우자료
|
|
|
|
console.log("오수관망도 정보:", file1?.file);
|
|
console.log("수용가-맨홀 매칭결과 정보:", file2);
|
|
console.log("강우자료:", file3);
|
|
|
|
// 모든 필수 파일이 선택되었는지 확인
|
|
if (!file1?.file || !file2?.file || !file3?.file) {
|
|
setIsLoadingResult(false);
|
|
alert('모든 분석용 파일을 선택해주세요.');
|
|
return;
|
|
}
|
|
|
|
const filePickers = [
|
|
{ file: file2, parser: excelToMatchingResultData },
|
|
{ file: file3, parser: excelToRainData },
|
|
];
|
|
|
|
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 rainData = parsedResults.find(r => r && r.fileName === file3.file?.name)?.parsedData;
|
|
|
|
// 새로운 JSON 데이터 생성
|
|
const combinedAnalysisData = {
|
|
enoCd: select1.toString(), // 환경청코드
|
|
aplcnYm: new Date(formData.date).toISOString().substring(0, 7).replace("-", ""), // 적용연월 (YYYYMM 형식)
|
|
ctpvCd: select2.toString(), // 시도코드
|
|
sggCd: select3.val.toString(), // 시군구코드
|
|
swageTmplntCd: select4.toString(), // 하수처리장코드
|
|
swtrmtZoneCd: select5.toString(), // 하수처리구역코드
|
|
atflCd: file1?.atflCd, // 첨부파일CD (오수관망도)
|
|
atflId: file1?.atflId, // 첨부파일ID (오수관망도)
|
|
atflInpNm: file1?.file?.name || "", // 오수관망도 파일명
|
|
atflMpngNm: file2?.file?.name || "", // 수용가-맨홀 매칭결과 파일명
|
|
atflRainNm: file3?.file?.name || "", // 강우자료 파일명
|
|
cntbArea: parseFloat(formData.rdiiArea) || null, // RDII 기여면적(ha)
|
|
srcNm: formData.rtkSource, // 출처이름 (RTK계수 출처)
|
|
|
|
shortPrdR: parseFloat(formData.unitFactors[0]?.R || "0"),
|
|
shortPrdT: parseFloat(formData.unitFactors[0]?.T || "0"),
|
|
shortPrdK: parseFloat(formData.unitFactors[0]?.K || "0"),
|
|
|
|
mdPrdR: parseFloat(formData.unitFactors[1]?.R || "0"),
|
|
mdPrdT: parseFloat(formData.unitFactors[1]?.T || "0"),
|
|
mdPrdK: parseFloat(formData.unitFactors[1]?.K || "0"),
|
|
|
|
longPrdR: parseFloat(formData.unitFactors[2]?.R || "0"),
|
|
longPrdT: parseFloat(formData.unitFactors[2]?.T || "0"),
|
|
longPrdK: parseFloat(formData.unitFactors[2]?.K || "0"),
|
|
|
|
shortPrdMaxDpth: parseFloat(formData.initialDepths[0]?.Dmax || "0"),
|
|
shortPrdRcvryRt: parseFloat(formData.initialDepths[0]?.Drec || "0"),
|
|
shortPrdBgngDpth: parseFloat(formData.initialDepths[0]?.Do || "0"),
|
|
|
|
mdPrdMaxDpth: parseFloat(formData.initialDepths[1]?.Dmax || "0"),
|
|
mdPrdRcvryRt: parseFloat(formData.initialDepths[1]?.Drec || "0"),
|
|
mdPrdBgngDpth: parseFloat(formData.initialDepths[1]?.Do || "0"),
|
|
|
|
longTermMaxDpth: parseFloat(formData.initialDepths[2]?.Dmax || "0"),
|
|
longTermRcvryRt: parseFloat(formData.initialDepths[2]?.Drec || "0"),
|
|
longTermBgngDpth: parseFloat(formData.initialDepths[2]?.Do || "0"),
|
|
|
|
drtwSwtcRt: parseFloat(formData.rate || "0"), // 오수전환율
|
|
anlsInfo: formData.analysisInfo, // 분석정보
|
|
|
|
tbSnRcptrMhlMpng: matchingResultData, // 수용가-맨홀 매칭결과
|
|
tbSnRainData: rainData, // 강우자료
|
|
};
|
|
|
|
console.log("통합 분석 데이터 (JSON):", combinedAnalysisData);
|
|
|
|
// 수정된 registFile 함수를 호출하여 combinedAnalysisData를 전송합니다.
|
|
await registFile(combinedAnalysisData);
|
|
setIsLoadingResult(false);
|
|
} catch (error) {
|
|
setIsLoadingResult(false);
|
|
console.error("파일 파싱 중 오류 발생:", error);
|
|
alert("파일 처리 중 오류가 발생했습니다.");
|
|
return;
|
|
}
|
|
}
|
|
|
|
const { fields: unitFactorFields } = useFieldArray({
|
|
control: form.control,
|
|
name: "unitFactors"
|
|
})
|
|
|
|
const { fields: initialDepthFields } = useFieldArray({
|
|
control: form.control,
|
|
name: "initialDepths"
|
|
})
|
|
|
|
const onSubmit = (data: z.infer<typeof formSchema>) => {
|
|
console.log("✅ 제출 데이터:", data)
|
|
}
|
|
|
|
// 단위도 계수 테이블 설정 (EditableTableHeadItem 타입 사용 및 id 수정)
|
|
const unitFactorHeadlist: EditableTableHeadItem<FormSchemaType['unitFactors'][number]>[] = [
|
|
{ id: 'response', title: 'Response', editable: false, width: '150px' }, // width 속성 추가
|
|
{ id: 'R', title: 'R', editable: true, inputProps: { type: 'text' } },
|
|
{ id: 'T', title: 'T', editable: true, inputProps: { type: 'text' } },
|
|
{ id: 'K', title: 'K', editable: true, inputProps: { type: 'text' } }
|
|
];
|
|
|
|
// 초기 차단 깊이 테이블 설정 (EditableTableHeadItem 타입 사용)
|
|
const initialDepthHeadlist: EditableTableHeadItem<FormSchemaType['initialDepths'][number]>[] = [
|
|
{ id: 'response', title: 'Response', editable: false, width: '150px' }, // width 속성 추가
|
|
{ id: 'Dmax', title: 'Dmax', editable: true, inputProps: { type: 'text' } },
|
|
{ id: 'Drec', title: 'Drec', editable: true, inputProps: { type: 'text' } },
|
|
{ id: 'Do', title: 'Do', editable: true, inputProps: { type: 'text' } }
|
|
];
|
|
|
|
// 테이블 페이지 변경 핸들러
|
|
const handlePageChange = (page: number) => {
|
|
console.log('Page changed:', page)
|
|
}
|
|
|
|
return (
|
|
// <BaseLayout searchBox={{ title: '분석 대상지역 선택' }} titleName={{ mainTitle: 'RDII 분석', firstCardTitle: 'RDII 분석자료 입력', secondCardTitle: '실측자료 등록' }} form={form} onSubmitEvent={() => { }} graphBtn={false} >
|
|
<BaseLayout
|
|
selectBox={{ title: '분석 대상지역 선택' }}
|
|
titleName={{ mainTitle: 'RDII 분석', firstCardTitle: 'RDII 분석자료 입력', secondCardTitle: '실측자료 등록' }}
|
|
form={form} // react-hook-form 인스턴스 전달
|
|
onSubmitEvent={() => { }} // BaseLayout의 form 태그에 연결될 onSubmit
|
|
graphBtn={false}
|
|
analysisBtn={'RDII분석 실행'}
|
|
enoCd={select1}
|
|
setEnoCd={setSelect1}
|
|
ctpvCd={select2}
|
|
setCtpvCd={setSelect2}
|
|
sigungu={select3}
|
|
setSigungu={setSelect3}
|
|
selectedSwageTreatmentPlant={select4}
|
|
onSwageTreatmentPlantChange={setSelect4}
|
|
selectedSwageProcessingZone={select5}
|
|
onSwageProcessingZoneChange={setSelect5}
|
|
isLoading={isLoadingResult}
|
|
onAnalysis={handleAnalysisClick}
|
|
>
|
|
{[<div className="space-y-[1.2rem] overflow-x-auto pt-4 pb-4 px-2" key="form-section">
|
|
<div className="grid grid-cols-2 gap-4">
|
|
<FormSection name="rtkSource" form={form} titleNm="○ RTK계수 출처">
|
|
<Input {...form.register("rtkSource")} className="h-12 text-center text-xl w-[225px]" />
|
|
</FormSection>
|
|
<FormSection name="rdiiArea" form={form} titleNm="○ RDII 기여면적(ha)">
|
|
<Input {...form.register("rdiiArea")} className="h-12 text-center text-xl w-[225px]" />
|
|
</FormSection></div>
|
|
<div className="grid grid-cols-2 gap-4">
|
|
<div>
|
|
<Label className="mb-2 text-xl font-medium">○ 단위도 계수</Label>
|
|
<EditableFormTable
|
|
form={form}
|
|
name="unitFactors"
|
|
fields={unitFactorFields}
|
|
headlist={unitFactorHeadlist}
|
|
tableClassName="w-[400px]"
|
|
/>
|
|
</div>
|
|
<div>
|
|
<Label className="mb-[1.2rem] text-xl font-medium">○ 초기 차단 깊이</Label>
|
|
<EditableFormTable
|
|
form={form}
|
|
name="initialDepths"
|
|
fields={initialDepthFields}
|
|
headlist={initialDepthHeadlist}
|
|
tableClassName="w-[400px]"
|
|
/>
|
|
</div>
|
|
</div>
|
|
<div className="grid grid-cols-2 gap-4">
|
|
<FormSection name="suyeonga" form={form} titleNm="○ 오수관망도"><div className="w-[350px]">
|
|
<FileUploadForm
|
|
key={`file-upload-0-${formResetKey}`} // 폼 초기화를 위한 key
|
|
onFileSelect={(file, cd, id) => handleFileSelection(0, file, cd, id)}
|
|
showButton={false}
|
|
showPreview={true}
|
|
accept={""}
|
|
fileIdx={0} />
|
|
</div></FormSection>
|
|
<FormSection name="regopm" form={form} titleNm="○ 수용가-맨홀 매칭결과"><div className="w-[350px]">
|
|
<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} />
|
|
</div></FormSection>
|
|
<FormSection name="rain" form={form} titleNm="○ 강우자료"><div className="w-[350px]">
|
|
<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} />
|
|
</div></FormSection>
|
|
<FormSection name='rate' form={form} titleNm='○ 오수전환율'>
|
|
<Input {...form.register("rate")} className="h-12 text-center text-xl w-[225px] ml-5" />
|
|
</FormSection>
|
|
<FormSection name='date' form={form} titleNm='○ 상수사용량 적용기간'>
|
|
{/* <DatePicker
|
|
selected={form.watch("date")}
|
|
onSelect={(date: Date | undefined) => {
|
|
if (date) {
|
|
form.setValue("date", date, { shouldValidate: true });
|
|
}
|
|
}}
|
|
mode={"single"}
|
|
className="ml-5"
|
|
/> */}
|
|
<DatePicker
|
|
mode={"single"} // mode는 DayPickerSingleProps에서 오므로 그대로 사용 가능
|
|
field={{
|
|
value: form.watch("date"), // react-hook-form의 "date" 필드 값 사용
|
|
onChange: (date: Date | undefined) => {
|
|
if (date) {
|
|
form.setValue("date", date, { shouldValidate: true });
|
|
}
|
|
}
|
|
}}
|
|
// className을 직접 사용하거나, DatePicker 내부에서 selectClass를 처리하도록 수정 필요
|
|
// 여기서는 DatePicker의 selectClass prop을 사용하고, date-picker.css의 스타일을 적용
|
|
selectClass="ml-5 date-picker-trigger"
|
|
/>
|
|
</FormSection>
|
|
<FormSection name='rate' form={form} titleNm='○ 분석 정보'>
|
|
<Input {...form.register("analysisInfo")} className="h-12 text-center text-xl w-[225px] ml-5" />
|
|
</FormSection>
|
|
</div>
|
|
{/* <div className="flex justify-end mt-1">
|
|
<Button size="sm" type="submit" onClick={handleAnalysisClick}>RDII분석 실행</Button>
|
|
</div> */}
|
|
</div>
|
|
]}
|
|
</BaseLayout >
|
|
)
|
|
}
|