import { useState, useMemo, useCallback } from "react"; import { useWatch, type Path, type PathValue, type UseFormReturn, } from "react-hook-form"; import { useQuery } from "@tanstack/react-query"; import { Button, Input, Table, TableBody, TableCell, TableHead, TableRow, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@common/components"; import { FormWrapper } from "@/widgets/form-wrapper"; import { CodeApi, CodeSelect } from "@/entities/code"; import { UserApi, type UserSaveData, type UserUpdateData, } from "@/entities/user"; import { FormField, FormItem, FormControl, FormMessage, } from "@/shared/ui/form"; import { ENDPOINT } from "@/shared/config"; import { useAlertStore, useMutationWrapper } from "@/shared/lib"; import { ZipSearchDialog } from "./zip-search-dialog"; import { AgencySearchDialog } from "./agency-search-dialog"; type UsersFormProps = { userId?: string; form: UseFormReturn; handleSave: (data: T) => Promise; handleDelete?: () => Promise; }; function UsersForm({ userId, form, ...props }: UsersFormProps) { const isModifyMode = !!userId; const [watchOgdpSeCd, watchDtlInstCd] = useWatch({ control: form.control, name: ["ogdpSeCd" as Path, "dtlInstCd" as Path], }); const alert = useAlertStore((state) => state.setMessage); const [isValidUserId, setIsValidUserId] = useState(false); const [isValidEmail, setIsValidEmail] = useState(false); const [passwordMatch, setPasswordMatch] = useState(true); const [instSeCdNm, setInstSeCdNm] = useState(""); const { data: authSeCd } = useQuery({ queryKey: [ENDPOINT.CMS_SERVICE.CODE, "AUTHSECD"], queryFn: () => CodeApi.getCode("AUTHSECD"), }); const { data: laeSeCd } = useQuery({ queryKey: [ENDPOINT.CMS_SERVICE.CODE, "LAESECD"], queryFn: () => CodeApi.getCode("LAESECD"), }); const { mutateAsync: checkDuplicateUserId } = useMutationWrapper({ mutationFn: (userId: string) => UserApi.existsUserId({ userId }), onSuccess: (duplicate) => { if (!duplicate) { alert("사용가능한 아이디입니다."); setIsValidUserId(true); return; } alert("중복된 아이디입니다."); }, }); const { mutateAsync: checkDuplicateEmail } = useMutationWrapper({ mutationFn: (email: string) => UserApi.existsEmail({ email }), onSuccess: (duplicate) => { if (!duplicate) { alert("사용가능한 이메일입니다."); setIsValidEmail(true); return; } alert("중복된 이메일입니다."); }, }); const authSeCdSelectData = useMemo(() => { if (watchOgdpSeCd === "1") return ( authSeCd?.filter( (code) => code.lwpoCd === "ROLE_USER1" || code.lwpoCd === "ROLE_USER2" || code.lwpoCd === "ROLE_USER3", ) ?? [] ); if (watchOgdpSeCd === "3" || watchOgdpSeCd === "4") return ( authSeCd?.filter( (code) => code.lwpoCd === "ROLE_USER4" || code.lwpoCd === "ROLE_USER5", ) ?? [] ); return []; }, [authSeCd, watchOgdpSeCd]); const laeSeCdSelectData = useMemo(() => { if (watchDtlInstCd === "ROLE_USER1") return laeSeCd?.filter((code) => code.lwpoCd === "G102") ?? []; if (watchDtlInstCd === "ROLE_USER2") return laeSeCd?.filter((code) => code.lwpoCd === "G101") ?? []; if (watchDtlInstCd === "ROLE_USER3") return laeSeCd?.filter((code) => code.lwpoCd.startsWith("G2")) ?? []; if (watchDtlInstCd === "ROLE_USER4") return ( laeSeCd?.filter( (code) => code.lwpoCd.startsWith("G3") && code.lwpoCd.length === 4, ) ?? [] ); if (watchDtlInstCd === "ROLE_USER5") return ( laeSeCd?.filter( (code) => code.lwpoCd.startsWith("G3") && code.lwpoCd.length === 7, ) ?? [] ); return []; }, [laeSeCd, watchDtlInstCd]); const enoCdSelectData = useMemo( () => laeSeCd?.filter((code) => code.lwpoCd?.startsWith("G2")) ?? [], [laeSeCd], ); const handlePasswordConfirmChange = useCallback((value: string) => { const password = form.getValues("password" as Path); setPasswordMatch(!password || value === password); }, []); const handleAddressSelect = useCallback( (data: { zip: string; addr: string }) => { form.setValue("zip" as Path, data.zip as PathValue>); form.setValue("addr" as Path, data.addr as PathValue>); }, [form], ); const handleAgencySelect = useCallback( (data: { lwpoCd: string; lwpoCdNm: string }) => { form.setValue( "instSeCd" as Path, data.lwpoCd as PathValue>, ); setInstSeCdNm(data.lwpoCdNm); }, [form], ); return (
{/* 아이디 */} 아이디 } render={({ field }) => (
{ field.onChange(e); setIsValidUserId(false); }} className="w-[24rem] !text-[1.3rem]" placeholder="아이디를 입력하세요" disabled={isModifyMode} /> {!isModifyMode && ( )}
)} />
{/* 비밀번호 */} 비밀번호 } render={({ field }) => ( )} /> {/* 비밀번호 확인 */} 비밀번호 확인
handlePasswordConfirmChange(e.target.value) } className="w-[24rem] !text-[1.3rem]" placeholder="비밀번호를 다시 입력하세요" /> {!passwordMatch && (

비밀번호가 일치하지 않습니다.

)}
{/* 비밀번호 힌트 */} 비밀번호 힌트 } render={({ field }) => ( )} /> {/* 비밀번호 정답 */} 비밀번호 정답 } render={({ field }) => ( )} /> {/* 이름 */} 이름 } render={({ field }) => ( )} /> {/* 연락처 */} 연락처 } render={({ field }) => ( )} /> } render={({ field }) => ( )} /> {/* 이메일 */} 이메일 } render={({ field }) => (
{ field.onChange(e); setIsValidEmail(false); }} className="w-[24rem] !text-[1.3rem]" placeholder="이메일을 입력하세요" />
)} />
{/* 주소 */} 주소
} render={({ field }) => ( )} />
} render={({ field }) => ( )} />
} render={({ field }) => ( )} /> {/* 기관구분 */} 기관구분 } render={({ field }) => ( { field.onChange(value); form.setValue( "dtlInstCd" as Path, "" as PathValue>, ); form.setValue( "laeSeCd" as Path, "" as PathValue>, ); form.setValue( "enoCd" as Path, "" as PathValue>, ); }} className="w-[16rem]" placeholder="기관 선택" /> )} /> {/* 세부기관 */} 세부기관 } render={({ field }) => ( )} /> {/* 소속 */} 소속 } render={({ field }) => ( )} /> {/* 환경청 */} 환경청 } render={({ field }) => ( )} /> {/* 환경청 기관/업체명 */} 기관/업체명
); } export { UsersForm };