477 lines
16 KiB
TypeScript
477 lines
16 KiB
TypeScript
"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 { toast } from "@/components/ui/use-toast";
|
||
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, getOrganizations } from "@/utils/commonApi";
|
||
import { ThreeDots } from "react-loader-spinner";
|
||
import useToken from "@/store/useToken";
|
||
|
||
const MAX_IMAGE_SIZE = 5242880; // 5 MB
|
||
const ALLOWED_IMAGE_TYPES = [
|
||
"image/jpeg",
|
||
"image/png",
|
||
"image/webp",
|
||
"image/jpg",
|
||
];
|
||
|
||
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(300, {
|
||
message: "تعداد کاراکترها بیشتر از حد مجاز میباشد.",
|
||
}),
|
||
uploadFile: z
|
||
.custom<FileList>((val) => val instanceof FileList, "Required")
|
||
// .refine((files) => files.length > 0, `Required`)
|
||
.refine((files) => files.length <= 5, `Maximum of 5 File are allowed.`)
|
||
.refine(
|
||
(files) => Array.from(files).every((file) => file.size <= MAX_IMAGE_SIZE),
|
||
`Each file size should be less than 5 MB.`
|
||
)
|
||
.nullish(),
|
||
// .refine(
|
||
// (files) =>
|
||
// Array.from(files).every((file) =>
|
||
// ALLOWED_IMAGE_TYPES.includes(file.type)
|
||
// ),
|
||
// "Only these types are allowed .jpg, .jpeg, .png and .webp"
|
||
// ),
|
||
categoryId: z.string({
|
||
required_error: "لطفا دسته بندی را انتخاب نمایید.",
|
||
}),
|
||
captchaValue: z.string().min(1, {
|
||
message: "لطفا کد امنیتی را وارد نمایید.ئ",
|
||
}),
|
||
});
|
||
|
||
interface Organization {
|
||
title: string;
|
||
description: string;
|
||
isDeleted: string;
|
||
id: string;
|
||
}
|
||
|
||
// Form Hook
|
||
export default function RequestStep2() {
|
||
// const [trackingComplaint, setTrackingComplaint] = useState({});
|
||
const isAuth = useToken((state) => state.token);
|
||
const router = useRouter();
|
||
useEffect(() => {
|
||
useToken.persist.rehydrate();
|
||
}, []);
|
||
const complaintSubmitMutation = useMutation({
|
||
mutationKey: ["complaintSubmit"],
|
||
mutationFn: postComplaintSubmit,
|
||
onSuccess: (res) => {
|
||
localStorage.setItem("trackingNumber", res.trackingNumber);
|
||
localStorage.setItem("password", res.password);
|
||
router.push("/RequestResult");
|
||
},
|
||
onError: (error) => {},
|
||
});
|
||
|
||
const authorizedComplaintSubmitMutation = useMutation({
|
||
mutationKey: ["authorizedComplaintSubmit"],
|
||
mutationFn: postAuthorizedComplaintSubmit,
|
||
onSuccess: (res) => {
|
||
localStorage.setItem("trackingNumber", res.trackingNumber);
|
||
localStorage.setItem("password", res.password);
|
||
localStorage.removeItem("authorized");
|
||
router.push("/RequestResult");
|
||
},
|
||
onError: (error) => {},
|
||
});
|
||
|
||
// 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(),
|
||
});
|
||
// console.log(captchaData);
|
||
|
||
const srcForImage = CaptchaData
|
||
? URL.createObjectURL(CaptchaData.data)
|
||
: null;
|
||
|
||
const form = useForm<z.infer<typeof FormSchema>>({
|
||
resolver: zodResolver(FormSchema),
|
||
defaultValues: {
|
||
title: "",
|
||
person: "",
|
||
description: "",
|
||
captchaValue: "",
|
||
// uploadFile: null,
|
||
},
|
||
});
|
||
|
||
function onSubmit(data: z.infer<typeof FormSchema>) {
|
||
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);
|
||
if (isAuth) {
|
||
authorizedComplaintSubmitMutation.mutate({
|
||
Data: formData,
|
||
});
|
||
} else {
|
||
complaintSubmitMutation.mutate({
|
||
Data: formData,
|
||
});
|
||
}
|
||
refetch();
|
||
resetField("Title");
|
||
resetField("Text");
|
||
resetField("Medias");
|
||
resetField("CategoryId");
|
||
resetField("Captcha.Value");
|
||
}
|
||
|
||
const { resetField } = useForm();
|
||
|
||
return (
|
||
<div className="w-full h-full sm:w-2/3 md:w-2/4 max-sm:p-8 pt-12">
|
||
<div className="space-y-3 md:space-y-4 h-full flex flex-col justify-center">
|
||
<p className="text-sm md:text-base font-bold leading-tight tracking-tight text-blue dark:text-white">
|
||
لطفا جهت ارسال درخواست فرم زیر را تکمیل نمایید.
|
||
</p>
|
||
|
||
<Form {...form}>
|
||
<form
|
||
onSubmit={form.handleSubmit(onSubmit)}
|
||
className="w-full flex flex-col mt-6"
|
||
>
|
||
<FormField
|
||
control={form.control}
|
||
name="title"
|
||
render={({ field }) => (
|
||
<FormItem>
|
||
<FormLabel className="text-[#7C838A] text-sm font-medium mt-7">
|
||
*موضوع شکایت
|
||
</FormLabel>
|
||
<FormControl>
|
||
<Input
|
||
placeholder="موضوع شکایت خود را بنویسید"
|
||
{...field}
|
||
/>
|
||
</FormControl>
|
||
<FormMessage />
|
||
</FormItem>
|
||
)}
|
||
/>
|
||
<div className="flex flex-row flex-wrap justify-between">
|
||
<FormField
|
||
control={form.control}
|
||
name="OrganizationId"
|
||
render={({ field }) => (
|
||
<FormItem className=" w-full sm:w-[48%]">
|
||
<FormLabel className="text-[#7C838A] text-sm font-medium mt-7">
|
||
*دستگاه مربوطه
|
||
</FormLabel>
|
||
<Select
|
||
onValueChange={field.onChange}
|
||
defaultValue={field.value}
|
||
dir="rtl"
|
||
>
|
||
<FormControl>
|
||
<SelectTrigger
|
||
className=" bg-slate-200 !text-[#7C838A]"
|
||
dir="rtl"
|
||
>
|
||
<SelectValue
|
||
className=""
|
||
placeholder="دستگاه مربوطه را انتخاب نمایید."
|
||
/>
|
||
</SelectTrigger>
|
||
</FormControl>
|
||
<SelectContent dir="rtl">
|
||
<SelectGroup>
|
||
{organizationsData?.map((item: any) => {
|
||
return (
|
||
<SelectItem value={item.id}>
|
||
{item.title}
|
||
</SelectItem>
|
||
);
|
||
})}
|
||
</SelectGroup>
|
||
</SelectContent>
|
||
</Select>
|
||
<FormMessage className=" mt-2" />
|
||
</FormItem>
|
||
)}
|
||
/>
|
||
|
||
<FormField
|
||
control={form.control}
|
||
name="person"
|
||
render={({ field }) => (
|
||
<FormItem className=" w-full sm:w-[48%]">
|
||
<FormLabel className="text-[#7C838A] text-sm font-medium mt-7">
|
||
فرد مربوطه
|
||
</FormLabel>
|
||
<FormControl>
|
||
<Input
|
||
placeholder="نام فرد مورد نظر خود را بنویسید"
|
||
{...field}
|
||
/>
|
||
</FormControl>
|
||
<FormMessage />
|
||
</FormItem>
|
||
)}
|
||
/>
|
||
</div>
|
||
|
||
<FormField
|
||
control={form.control}
|
||
name="description"
|
||
render={({ field }) => (
|
||
<FormItem>
|
||
<FormLabel className="text-[#7C838A] text-sm font-medium mt-7">
|
||
توضیحات
|
||
</FormLabel>
|
||
<FormControl>
|
||
<Textarea
|
||
placeholder="متن توضیحات خود را بنویسید"
|
||
className="resize-none mb-3"
|
||
{...field}
|
||
/>
|
||
</FormControl>
|
||
<FormMessage />
|
||
</FormItem>
|
||
)}
|
||
/>
|
||
|
||
<div className="flex flex-row flex-wrap justify-between">
|
||
{/* Select Option */}
|
||
<FormField
|
||
control={form.control}
|
||
name="categoryId"
|
||
render={({ field }) => (
|
||
<FormItem className="w-full sm:w-[48%] flex-row-reverse">
|
||
<FormLabel className="text-[#7C838A] text-sm font-medium mt-7">
|
||
انتخاب دسته بندی
|
||
</FormLabel>
|
||
<Select
|
||
onValueChange={field.onChange}
|
||
defaultValue={field.value}
|
||
dir="rtl"
|
||
>
|
||
<FormControl>
|
||
<SelectTrigger className="bg-slate-200">
|
||
<SelectValue placeholder=" دسته بندی ها" />
|
||
</SelectTrigger>
|
||
</FormControl>
|
||
<SelectContent>
|
||
{categoryData?.map((catItems: any, index: any) => (
|
||
<SelectItem key={index} value={catItems.id}>
|
||
{catItems.title}
|
||
</SelectItem>
|
||
))}
|
||
</SelectContent>
|
||
</Select>
|
||
<FormMessage className=" mt-2" />
|
||
</FormItem>
|
||
)}
|
||
/>
|
||
|
||
{/* uploadFile */}
|
||
<FormField
|
||
control={form.control}
|
||
name="uploadFile"
|
||
render={({ field: { onChange }, ...field }) => {
|
||
// Get current uploadFile value (always watched updated)
|
||
const uploadFile = form.watch("uploadFile");
|
||
{
|
||
console.log(uploadFile);
|
||
}
|
||
var filenames: string[] | undefined = undefined;
|
||
if (uploadFile) {
|
||
// 1. covert to File[] using Array.from
|
||
const files: File[] = Array.from(uploadFile);
|
||
// 2. now you can use array methods on files;
|
||
filenames = files.map((file) => file?.name);
|
||
{
|
||
console.log(filenames);
|
||
}
|
||
}
|
||
|
||
return (
|
||
<FormItem className="w-full sm:w-[48%]">
|
||
<FormLabel className="text-[#7C838A] text-sm font-medium mt-7">
|
||
پیوست
|
||
</FormLabel>
|
||
{/* File Upload */}
|
||
<FormControl>
|
||
<Input
|
||
type="file"
|
||
className="mb-3"
|
||
accept="image/* , .pdf"
|
||
multiple={true}
|
||
disabled={form.formState.isSubmitting}
|
||
{...field}
|
||
onChange={(event) => {
|
||
// Triggered when user uploaded a new file
|
||
// FileList is immutable, so we need to create a new one
|
||
const dataTransfer = new DataTransfer();
|
||
|
||
// Add old images
|
||
// if (images) {
|
||
// Array.from(images).forEach((image) =>
|
||
// dataTransfer.items.add(image)
|
||
// );
|
||
// }
|
||
|
||
// Add newly uploaded images
|
||
Array.from(event.target.files!).forEach((image) =>
|
||
dataTransfer.items.add(image)
|
||
);
|
||
|
||
// Validate and update uploaded file
|
||
const newFiles = dataTransfer.files;
|
||
onChange(newFiles);
|
||
}}
|
||
/>
|
||
</FormControl>
|
||
{/* Show File Name */}
|
||
{/* <FormDescription>{`${filenames}`}</FormDescription> */}
|
||
<FormMessage />
|
||
</FormItem>
|
||
);
|
||
}}
|
||
/>
|
||
</div>
|
||
{/* Captcha */}
|
||
<div className="flex flex-row justify-between items-center w-full lg:w-[48%] gap-2">
|
||
<FormField
|
||
control={form.control}
|
||
name="captchaValue"
|
||
render={({ field }) => (
|
||
<FormItem className="w-full ">
|
||
<FormLabel className="text-[#7C838A] text-sm font-medium mt-7">
|
||
*کد امنیتی
|
||
</FormLabel>
|
||
<FormControl>
|
||
<Input
|
||
placeholder="کد تصویر روبرو را وارد کنید "
|
||
{...field}
|
||
/>
|
||
</FormControl>
|
||
<FormMessage />
|
||
</FormItem>
|
||
)}
|
||
/>
|
||
|
||
{isLoading ? (
|
||
<div className=" w-2/3 max-w[11rem] flex justify-center text-center">
|
||
<ThreeDots
|
||
visible={true}
|
||
height="50"
|
||
width="50"
|
||
color="#003778"
|
||
radius="9"
|
||
ariaLabel="three-dots-loading"
|
||
wrapperStyle={{}}
|
||
wrapperClass=""
|
||
/>
|
||
</div>
|
||
) : (
|
||
<div className=" w-2/3 max-w[11rem] flex justify-end text-center">
|
||
<Image
|
||
alt="icon"
|
||
src={srcForImage as string}
|
||
className=" h-12 rounded-md shadow-md w-36"
|
||
width={150}
|
||
height={20}
|
||
quality={100}
|
||
/>
|
||
</div>
|
||
)}
|
||
</div>
|
||
|
||
<div className="flex justify-center sm:justify-end gap-2 w-full mt-4">
|
||
<Button
|
||
type="submit"
|
||
className="w-1/2 sm:w-1/3 lg:w-1/4 bg-blue text-white p-2 rounded-xl text-center mb-4"
|
||
>
|
||
ارسال درخواست
|
||
</Button>
|
||
</div>
|
||
</form>
|
||
</Form>
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|