"use client"; import React, { useEffect, useState } from "react"; import { zodResolver } from "@hookform/resolvers/zod"; import { useForm } from "react-hook-form"; import * as z from "zod"; import { Button } from "@/components/ui/button"; import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form"; import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Input } from "@/components/ui/input"; import { Textarea } from "@/components/ui/textarea"; import { Label } from "@/components/ui/label"; import Link from "next/link"; import RequestResult from "./RequestResult"; import Image from "next/image"; import Img1 from "../public/img/logo.png"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { postAuthorizedComplaintSubmit, postComplaintSubmit, } from "@/utils/citizenApi"; import { useRouter } from "next/navigation"; import { getCaptcha, getCategory, getOptions, getOrganizations, } from "@/utils/commonApi"; import { Oval, ThreeDots } from "react-loader-spinner"; import useToken from "@/store/useToken"; import { toast } from "sonner"; import { Eye, RefreshCcw, Upload } from "lucide-react"; import { getCookie } from "cookies-next"; import { formatBytes } from "@/lib/utils"; import AttachmentsDialog from "./AttachmentsDialog"; import { DialogTrigger } from "./ui/dialog"; interface Organization { title: string; description: string; isDeleted: string; id: string; } export default function RequestStep2() { const router = useRouter(); const [file, setFile] = useState([]); const [charCount, setCharCount] = useState(0); // Queries const { data: optionsData, isLoading: isLoadingData } = useQuery({ queryKey: ["Options"], queryFn: () => getOptions(), refetchOnWindowFocus: false, }); const FormSchema = z.object({ title: z.string().min(1, { message: "لطفا موضوع شکایت را وارد نمایید.", }), OrganizationId: z.string({ required_error: "لطفا دستگاه مربوطه را انتخاب نمایید.", }), person: z.string().optional(), description: z .string() .min(1, { message: "لطفا توضیحات خود را بنویسید.", }) .max(optionsData?.maxTextLength, { message: "تعداد کاراکترها بیشتر از حد مجاز میباشد.", }), uploadFile: z .custom() // .refine((files) => files.length > 0, `Required`) .refine( (files) => files.length <= optionsData?.maxFileCount, `تعداد فایل های پیوست شده می بایست حداکثر ${optionsData?.maxFileCount} عدد باشد.` ) .refine( (files) => files.every((item) => item.size < optionsData?.maxFileSize), `حجم هر فایل حداکثر می بایست ${formatBytes( optionsData?.maxFileSize )} باشد.` ) .nullish(), categoryId: z.string({ required_error: "لطفا دسته بندی را انتخاب نمایید.", }), captchaValue: z.string().min(1, { message: "لطفا کد امنیتی را وارد نمایید.", }), }); const complaintSubmitMutation = useMutation({ mutationKey: ["complaintSubmit"], mutationFn: postComplaintSubmit, onSuccess: (res) => { localStorage.setItem("trackingNumber", res.trackingNumber); localStorage.setItem("password", res.password); localStorage.removeItem("unknown"); router.push("/RequestResult"); }, onError: (err: any | string) => { refetch(); toast(<>{err.response.data.detail}, { className: "!bg-red-500 !text-white", }); }, }); const authorizedComplaintSubmitMutation = useMutation({ mutationKey: ["authorizedComplaintSubmit"], mutationFn: postAuthorizedComplaintSubmit, onSuccess: (res) => { const currentDate = new Date(); const formattedDate = currentDate.toISOString(); localStorage.setItem("trackingNumber", res.trackingNumber); localStorage.setItem("password", res.password); // localStorage.setItem("registeredAt", res.registeredAt); localStorage.setItem("registeredAt", formattedDate); localStorage.removeItem("authorized"); localStorage.removeItem("unknown"); router.push("/RequestResult"); }, onError: (err: any | string) => { refetch(); toast(<>{err.response.data.detail}, { className: "!bg-red-500 !text-white", }); }, }); // All Category const { data: categoryData } = useQuery({ queryKey: ["Category"], queryFn: () => getCategory(), }); const { data: organizationsData } = useQuery({ queryKey: ["organizations"], queryFn: () => getOrganizations(), }); // Captcha const { data: CaptchaData, isLoading, refetch, } = useQuery({ queryKey: ["Captcha"], queryFn: () => getCaptcha(), }); const srcForImage = CaptchaData ? URL.createObjectURL(CaptchaData.data) : null; const form = useForm>({ resolver: zodResolver(FormSchema), defaultValues: { title: "", person: "", description: "", captchaValue: "", // uploadFile: null, }, }); function handleDescriptionChange( event: React.ChangeEvent ) { const newCharCount = event.target.value.length; // Update charCount only when the user types or removes characters if (newCharCount <= optionsData?.maxTextLength) { setCharCount(newCharCount); } } // Add the useEffect hook to monitor changes in the description field useEffect(() => { setCharCount(form.watch("description").length); }, [form.watch("description")]); function onSubmit(data: z.infer) { console.log(data); const formData = new FormData(); formData.append("Title", data.title); formData.append("Text", data.description); formData.append("CategoryId", data.categoryId); if (data?.uploadFile && data?.uploadFile?.length > 0) { for (let i = 0; i < data.uploadFile.length; i++) { formData.append("Medias", data.uploadFile[i]); } } formData.append("Captcha.Value", data.captchaValue); formData.append("Captcha.Key", CaptchaData?.headers["captcha-key"]); formData.append("Complaining", data.person ? data.person : "-"); formData.append("OrganizationId", data.OrganizationId); const unknown = localStorage.getItem("unknown"); const isAuth = getCookie("Sootzani_Token"); if (isAuth && !unknown) { authorizedComplaintSubmitMutation.mutate({ Data: formData, }); } else { complaintSubmitMutation.mutate({ Data: formData, }); } resetField("Title"); resetField("Text"); resetField("Medias"); resetField("CategoryId"); resetField("Captcha.Value"); } const { resetField } = useForm(); const deleteFileFromAttachments = (File: any) => { const filtered = file?.filter((item) => item.name !== File); setFile(filtered); form.setValue("uploadFile", filtered); }; const deleteAllAttachmentsFiles = () => { setFile([]); form.setValue("uploadFile", []); }; const allowedExtensions = optionsData?.allowedExtensions; const split = allowedExtensions?.split(","); const withDot = split?.map((item: string) => "." + item); const newAllowedExtensions = withDot?.join(","); const formatSize = (size: number) => { const string = formatBytes(size); return ( {string} ); }; return (
ارسال گزارش

لطفا جهت ارسال درخواست فرم زیر را تکمیل نمایید.

( *موضوع گزارش )} />
( *واحد مورد گزارش )} /> ( فرد مربوطه )} />
( توضیحات ({charCount}/{optionsData?.maxTextLength})