"use client"; import { Alert, AlertTitle, Avatar, Box, Button, IconButton, MenuItem, Paper, TextField, Typography, } from "@mui/material"; import { ErrorMessage, Form, FormikProps } from "formik"; import { IdentityFormValues } from "@/core/types"; import { IdentityFormProps } from "./IdentityForm"; import { CheckCircle, Close, Person, UploadFile } from "@mui/icons-material"; import { genderOptions, religionOptions } from "@/core/constant"; import { useRef, useState } from "react"; import { DatePicker } from "@mui/x-date-pickers"; import axios from "axios"; import { toast } from "sonner"; import { useSendIdentityForm } from "@/hooks/identity.hook"; import callAPI from "@/core/caller"; export default function InnerIdentityForm( props: FormikProps & IdentityFormProps, ) { const handleBack = () => { // قبل از رفتن به عقب، مقادیر فعلی فرم را در استیت والد ذخیره کن props.update({ identity: props.values }); props.setStep(props.step - 1); }; const { mutateAsync, isPending } = useSendIdentityForm(); const [profileUploading, setProfileUploading] = useState(false); const [profileUploadProgress, setProfileUploadProgress] = useState(0); const [profileUploadError, setProfileUploadError] = useState(""); const [profilePreview, setProfilePreview] = useState(""); const [uploadedFileId, setUploadedFileId] = useState(""); const [selectedProfileFile, setSelectedProfileFile] = useState( null, ); // برای کنسل کردن آپلود const profileAbortControllerRef = useRef(null); // تابع کمکی اعتبارسنجی (می‌توانید همان تابع قبلی را استفاده کنید) const validateImageFile = (file: File) => { if (!file.type.startsWith("image/")) { return "فقط فایل تصویری مجاز است"; } const maxSize = 500 * 1024; // 500KB if (file.size > maxSize) { return "حجم عکس باید حداکثر ۵۰۰ کیلوبایت باشد"; } return ""; }; const handleProfilePhotoChange = async ( event: React.ChangeEvent, ) => { const file = event.target.files?.[0]; if (!file) return; // ۱. پیش‌نمایش موقت با استفاده از خودِ فایل (قبل از آپلود) // این کار باعث می‌شود کاربر فوراً عکس را ببیند و خطای URL نگیرید const localPreview = URL.createObjectURL(file); setProfilePreview(localPreview); setProfileUploading(true); setProfileUploadError(""); const formData = new FormData(); formData.append("file", file); try { const response = await callAPI.post("/files/upload", formData, { onUploadProgress: (p) => { setProfileUploadProgress( Math.round((p.loaded * 100) / (p.total || 100)), ); }, }); console.log(response); // ۲. بررسی دقیق پاسخ بک‌ند // فرض می‌کنیم بک‌ند شما { id: "...", url: "..." } برمی‌گرداند const { id, url } = response.data; if (id) { props.setFieldValue("profilePhotoId", id); // اگر بک‌ند URL کامل فرستاده، آن را جایگزین پیش‌نمایش موقت می‌کنیم if (url) setProfilePreview(url); } else { throw new Error("Invalid Response"); } } catch (error: any) { console.error("Upload Error:", error); setProfileUploadError( error.response?.data?.message || "خطا در آپلود فایل", ); setProfilePreview(""); // پاک کردن پیش‌نمایش در صورت خطا props.setFieldValue("profilePhotoId", ""); } finally { setProfileUploading(false); } }; const handleCancelUpload = () => { if (profileAbortControllerRef.current) { profileAbortControllerRef.current.abort(); } setProfileUploading(false); setProfileUploadProgress(0); }; const handleRemoveProfilePhoto = async () => { // اگر نیاز بود به بک‌اند درخواست حذف بزنید (اختیاری) await callAPI.post("/files/delete", { fileId: props.values.profilePhotoId, }); props.setFieldValue("profilePhotoId", null); setProfilePreview(""); setSelectedProfileFile(null); }; const handleNext = async () => { // اعتبارسنجی دستی کل فرم const errors = await props.validateForm(); props.update({ identity: props.values, }); // اگر در گام فعلی خطایی وجود ندارد، برو مرحله بعد if (Object.keys(errors).length === 0) { if (props.step === 12) { props.submitForm(); // ثبت نهایی } else { props.setStep(props.step + 1); } } try { const applicant = await mutateAsync(props.values); console.log(applicant); props.update({ identity: props.values, }); localStorage.setItem( "applicationDraft", JSON.stringify({ applicantId: applicant.id, registrationCenter: props.values, formStep: applicant.formStep, }), ); props.setStep((prev) => prev + 1); } catch (error: any) { console.log(error); toast.error(error?.message || "خطا در ثبت مرکز"); } }; return ( توجه پس از تكميل اين گام ، كدملي شما براي ادامه مراحل ذخيره خواهد شد
props.setFieldValue("firstName", e.target.value) } error={!!props.errors.firstName} helperText={props.errors.firstName} fullWidth required />
props.setFieldValue("lastName", e.target.value) } error={!!props.errors.lastName} helperText={props.errors.lastName} fullWidth required />
props.setFieldValue("fatherName", e.target.value) } fullWidth />
props.setFieldValue("nationalCode", e.target.value) } error={!!props.errors.nationalCode} helperText={props.errors.nationalCode} fullWidth required />
props.setFieldValue("birthDate", newValue) } maxDate={new Date()} slotProps={{ textField: { fullWidth: true, error: !!props.errors.birthDate, helperText: props.errors.birthDate, }, }} />
props.setFieldValue("birthPlace", e.target.value) } fullWidth required error={!!props.errors.birthPlace} helperText={props.errors.birthPlace} />
props.setFieldValue("gender", e.target.value)} error={!!props.errors.gender} helperText={props.errors.gender} fullWidth required > {genderOptions.map((item) => ( {item.label} ))}
props.setFieldValue("religion", e.target.value) } fullWidth required error={!!props.errors.religion} helperText={props.errors.religion} > {religionOptions.map((item) => ( {item} ))}
props.setFieldValue("nationality", e.target.value) } error={!!props.errors.nationality} helperText={props.errors.nationality} fullWidth required />
عکس پرسنلی {/* بخش پیش‌نمایش عکس */} {!profilePreview && ( )} {/* دکمه حذف عکس (فقط اگر عکسی وجود داشت) */} {profilePreview && !profileUploading && ( )} فقط فایل تصویری مجاز است و حجم آن باید حداکثر ۵۰۰ کیلوبایت باشد. {profileUploading && ( )} {/* نمایش نام فایل در حال آپلود */} {selectedProfileFile && profileUploading && ( فایل انتخاب‌شده: {selectedProfileFile.name} )} {/* نوار پیشرفت */} {profileUploading && ( پیشرفت آپلود: {profileUploadProgress}% )} {/* پیام موفقیت */} {!profileUploading && props.values.profilePhotoId && !profileUploadError && ( عکس با موفقیت بارگذاری شد. )} {/* پیام خطا */} {profileUploadError && ( {profileUploadError} )}
); }