Files
frontend/apps/wr/components/ui/modal/chkgd/chkgdExcel/chkgdExcel.tsx
T

287 lines
9.0 KiB
TypeScript

import { useWrStore } from "@/app/store";
import { type rainChkZodType } from "@/app/store/prfmncReg/chkgdnReg/rainChkgdn";
import { excelToRainChkData } from "@/app/store/prfmncReg/chkgdnReg/rainChkgdn/excel";
import { chkgdRegExcel } from "@/app/store/prfmncReg/chkgdnReg/rainChkgdn/headList";
import type { rswtChkZodType } from "@/app/store/prfmncReg/chkgdnReg/rswrtChkgdn";
import {
excelToRswtGuideData,
excelToRswtPolution,
} from "@/app/store/prfmncReg/chkgdnReg/rswrtChkgdn/excel";
import { showConfirmToast } from "@/components/lib/func/commom";
import {
filePicked,
filePickedArray,
Form,
FormField,
FormUi,
SelectBox,
Title,
} from "@common/business_components/ui";
import { Button, Input } from "@common/components/ui";
import { zodResolver } from "@hookform/resolvers/zod";
import { useEffect, useRef, useState } from "react";
import { useForm } from "react-hook-form";
import toast from "react-hot-toast";
import type { z } from "zod";
export default function ChkgdExcel({
type,
setIsRegExcel,
setYearChange,
}: {
type: string;
setIsRegExcel: (open: boolean) => void;
setYearChange: (year: string) => void;
}) {
const {
rainChkExcelDataUPload,
rswtChkExceDataUpload,
setRainChkLoading,
} = useWrStore((state) => {
return state;
});
const [excelData, setExcelData] = useState<
rswtChkZodType[] | rainChkZodType[]
>();
const [file, setFile] = useState<File | null>(null);
const clearFile = () => {
if (fileInputRef.current) {
fileInputRef.current.value = ""; // ✅ 파일 선택 비우기
}
};
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const selectedFile = e.target.files?.[0];
if (selectedFile) {
setFile(selectedFile);
}
};
const [excelRswtData, setExcelRswtData] = useState<rswtChkZodType[]>();
const fileInputRef = useRef<HTMLInputElement>(null);
const currentYear = new Date().getFullYear();
const startYear = 1970;
const yearOptions: { val: string; text: string }[] = Array.from(
{ length: currentYear - startYear + 1 },
(_, i) => {
const y = startYear + i;
return { val: String(y), text: `${y}년` };
}
);
const defaultValues: z.infer<typeof chkgdRegExcel> = chkgdRegExcel.parse({
chckYr: String(currentYear),
});
const form = useForm<z.infer<typeof chkgdRegExcel>>({
resolver: zodResolver(chkgdRegExcel),
defaultValues: defaultValues,
});
useEffect(() => {
if (file) {
if (form.getValues("chckYr").length < 1) {
toast.error("파일업로드 이전에 등록년도를 작성해주세요 ");
setFile(null);
return;
}
if (file)
if (type === "RNB") {
setRainChkLoading(true);
filePicked(file, 0)
.then(async (res) => {
const excelData = excelToRainChkData(
res,
form.getValues("chckYr")
);
if (excelData.issues && excelData.issues.length > 0) {
excelData.issues.some((err, index) => {
showConfirmToast(err);
return index === 4; // true 반환 시 반복 종료
});
clearFile();
} else {
setExcelData(excelData.rainChkgdData);
}
})
.finally(() => {
setRainChkLoading(false);
});
} else if (type === "RST") {
filePickedArray(file, 0).then((res) => {
let issues: string[] = [];
if (res && res?.length > 1) {
const guideData = excelToRswtGuideData(
res[0],
form.getValues("chckYr"),
issues
);
const polutionData = excelToRswtPolution(res[1], issues);
issues = [...guideData.issues, ...polutionData.issues];
if (issues && issues.length > 0) {
issues.some((err, index) => {
showConfirmToast(err);
return index === 6; // true 반환 시 반복 종료
});
clearFile();
} else {
const keyGenerator = (item: rswtChkZodType) =>
`${item.bdstRuseFcltSn}|${item.chckYmd}|${item.utztnUsgCd}`;
const totalData: rswtChkZodType[] = guideData.data.map(
(guide) => {
const fusion = polutionData.data.find(
(polution) =>
guide.bdstRuseFcltSn === polution.bdstRuseFcltSn &&
guide.chckYmd === polution.chckYmd &&
guide.utztnUsgCd === polution.utztnUsgCd
);
if (fusion) {
return {
...guide,
rswtrPollutions: fusion?.rswtrPollutions,
rswtrDetails: fusion?.rswtrDetails,
};
} else {
return {
...guide,
};
}
}
);
const guideKey = new Set(guideData.data.map(keyGenerator));
const onlypolution = polutionData.data.filter(
(item) => !guideKey.has(keyGenerator(item))
);
const listTotalData: rswtChkZodType[] = [
...totalData,
...onlypolution,
];
setExcelRswtData(listTotalData);
}
}
});
}
}
}, [file]);
// function findMatchingItems<T>(
// arrayA: T[],
// arrayB: T[],
// keySelector: (item: T) => string,
// condition?: (item: T) => boolean
// ): T[] {
// const bKeySet = new Set(arrayB.map(keySelector));
// return arrayA.filter(
// (item) =>
// (!condition || condition(item)) && bKeySet.has(keySelector(item))
// );
// }
const onSubmit = (values: z.infer<typeof chkgdRegExcel>) => {
if (values.chckYr === "") {
toast.error("등록년도를 작성해주세요");
return;
}
if (type === "RNB") {
if (excelData === undefined || excelData?.length === 0) {
toast.error("빈 파일 및 파일 오류 입니다.");
return;
} else {
rainChkExcelDataUPload(
excelData as rainChkZodType[],
form.getValues("chckYr")
);
setIsRegExcel(false);
setYearChange(form.getValues("chckYr"));
}
} else if (type === "RST") {
if (excelRswtData === undefined || excelRswtData?.length === 0) {
toast.error("빈 파일 및 파일 오류 입니다.");
return;
} else {
rswtChkExceDataUpload(excelRswtData as rswtChkZodType[]);
setIsRegExcel(false);
setYearChange(form.getValues("chckYr"));
}
}
};
return (
<>
<div>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
<div>
<Title
title={
type === "RNB"
? "빗물 이용시설"
: "중수도 이용시설" + "점검 결과등록"
}
></Title>
</div>
<div className="flex justify-between">
<h3 className="text-2xl font-bold text-gray-900 mt-1 ml-7">
{"점검정보 입력"}
</h3>
<Button className="" type="submit">
저장
</Button>
</div>
<div>
<FormField
control={form.control}
name="chckYr"
render={({ field }) => (
<FormUi label="등록년도">
<SelectBox
className="w-1/4 text-3xl"
selectClass={""}
label=""
selectArray={yearOptions}
value={field.value}
onSelectValue={(val) => field.onChange(String(val))}
/>
</FormUi>
)}
/>
<FormField
control={form.control}
name="file"
render={({ field }) => (
<FormUi label="점검결과 파일">
<div className="space-y-4 p-4">
<Input
ref={fileInputRef}
type="file"
onChange={(file) => {
handleFileChange(file);
////TODO : 폼 을 써야하는 지 확인 필요
console.log(field.value);
}}
accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
/>
</div>
</FormUi>
)}
/>
</div>
</form>
</Form>
</div>
</>
);
}