shahrbin-citizen/components/Settings/profile/Profile.tsx

440 lines
16 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"use client";
import React, { useEffect, useState } from "react";
import { zodResolver } from "@hookform/resolvers/zod";
import { Controller, 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 { Input } from "@/components/ui/input";
import Link from "next/link";
import { useMutation, useQuery } from "@tanstack/react-query";
import { getAuthenticate, putAuthenticate } from "@/utils/authenticateApi";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Oval } from "react-loader-spinner";
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { educations, genders } from "@/constants";
import DatePicker, { DateObject } from "react-multi-date-picker";
import gregorian from "react-date-object/calendars/gregorian";
import gregorian_en from "react-date-object/locales/gregorian_en";
import persian from "react-date-object/calendars/persian";
import persian_fa from "react-date-object/locales/persian_fa";
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";
import jalaliday from "jalaliday";
// import 'react-modern-calendar-datepicker/lib/DatePicker.css';
// import DatePicker from 'react-modern-calendar-datepicker';
dayjs.extend(jalaliday);
dayjs.extend(utc);
const FormSchema = z.object({
firstName: z.string().min(1, {
message: "لطفا نام خود را وارد نمایید.",
}),
lastName: z.string().min(1, {
message: "لطفا نام خانوادگی خود را وارد نمایید.",
}),
nationalId: z
.string()
.length(10, { message: "کد ملی معتبر نمی باشد." })
.transform((value) => {
const parsedNumber = Number(value);
if (Number.isNaN(parsedNumber)) {
throw new Error("کد ملی معتبر نمی باشد.");
} else if (
Number(parsedNumber) > 100000000 &&
Number(parsedNumber) < 999999999
) {
throw new Error("کد ملی معتبر نمی باشد.");
}
return parsedNumber;
}),
phoneNumber: z
.string()
.length(11, { message: "شماره موبایل معتبر نمی باشد." })
.transform((value) => {
const parsedNumber = Number(value);
if (Number.isNaN(parsedNumber)) {
throw new Error("شماره موبایل معتبر نمی باشد.");
} else if (
Number(parsedNumber) > 10000000000 &&
Number(parsedNumber) < 99999999999
) {
throw new Error("شماره موبایل معتبر نمی باشد.");
}
return parsedNumber;
}),
gender: z.string({
required_error: "لطفا جنسیت خود را انتخاب نمایید.",
}),
education: z.string({
required_error: "لطفا تحصیلات خود را انتخاب نمایید.",
}),
birthday: z.nullable(
z.any({
required_error: "لطفا تاریخ تولد خود را وارد کنید",
// invalid_type_error: "Age must be a number",
})
),
});
export default function Profile() {
const router = useRouter();
const [value, setValue] = useState(new Date());
const [date, setDate] = useState<any>();
// const [selectedDay, setSelectedDay] = useState<any | null>(null);
// const [profileData, setProfileData] = useState<any | null>(null);
const {
data: profileData,
isLoading,
refetch,
} = useQuery({
queryKey: ["Profile"],
queryFn: () => getAuthenticate(),
refetchOnWindowFocus: false,
});
const editProfileMutation = useMutation({
mutationKey: ["editProfile"],
mutationFn: putAuthenticate,
onSuccess: (res) => {
refetch();
// toast("پروفایل شما با موفقیت ویرایش شد.", {
toast(res.message, {
className: "!bg-green !text-black flex justify-end",
});
// router.push("/");
},
onError: (err: any | string) => {
toast(<>{err.response.data.detail}</>, {
className: "!bg-red-500 !text-white",
});
},
});
const form = useForm<z.infer<typeof FormSchema>>({
resolver: zodResolver(FormSchema),
defaultValues:{
gender:'',
education:''
}
});
useEffect(() => {
if (profileData) {
// setProfileData(data?.data);
console.log(profileData);
form.setValue("firstName", profileData.data?.firstName);
form.setValue("lastName", profileData.data?.lastName);
form.setValue("nationalId", profileData.data?.nationalId);
form.setValue("phoneNumber", profileData.data?.phoneNumber);
form.setValue("gender", String(profileData.data?.gender));
form.setValue("education", profileData.data?.education);
console.log(String(profileData.data?.gender));
const birthDate = new DateObject(profileData.data?.birthDate).convert(
gregorian,
gregorian_en
);
form.setValue(
"birthday",
birthDate.format("YYYY-MM-DDTHH:mm:ss.SSSSSSS")
);
const date2 = new DateObject(profileData.data?.birthDate).convert(
persian,
persian_fa
);
setDate(date2);
}
}, [profileData, setValue]);
function onSubmit(data: z.infer<typeof FormSchema>) {
const strNationalId = String(data.nationalId);
const strPhoneNumber = String(data.phoneNumber);
const NumGender = Number(data.gender);
const NumEducation = Number(data.education);
const payload = {
...data,
nationalId: strNationalId,
phoneNumber: strPhoneNumber,
gender: NumGender,
education: NumEducation,
};
console.log(payload);
editProfileMutation.mutate(payload);
}
return (
<div className="w-full sm:w-2/3 mx-auto bg-transparent border-2 p-2 sm:p-5 rounded-md">
<div className="flex flex-col justify-center space-y-2 md:space-y-4">
<h2 className=" w-full font-bold">پروفایل کاربری</h2>
{profileData && (
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="flex flex-col w-full mt-6 "
>
<div className="flex flex-row flex-wrap justify-between p-4 rounded-md gap-4 md:gap-2 lg:gap-4">
<FormField
control={form.control}
name="firstName"
render={({ field }) => (
<FormItem className="w-full md:w-[48%]">
<FormLabel className="text-gray-800 text-sm font-medium">
نام
</FormLabel>
<FormControl>
<Input
className="text-opacity-100"
placeholder="نام خود را وارد نمایید"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="lastName"
render={({ field }) => (
<FormItem className="w-full md:w-[48%] ">
<FormLabel className="text-gray-800 text-sm font-medium">
نام خانوادگی
</FormLabel>
<FormControl>
<Input
className="text-opacity-100"
placeholder="نام خانوادگی خود را وارد نمایید"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Controller
control={form.control}
name="gender"
render={({ field }) => (
<FormItem className=" w-full md:w-[48%]">
<FormLabel className="text-gray-800 text-sm font-medium">
جنسیت
</FormLabel>{" "}
<Select
onValueChange={field.onChange}
// defaultValue={field.value}
value={field.value}
dir="rtl"
>
<FormControl>
<SelectTrigger
className=" !text-[#7C838A]"
dir="rtl"
>
<SelectValue
className=""
placeholder="جنسیت خود را انتخاب نمایید."
/>
</SelectTrigger>
</FormControl>
<SelectContent dir="rtl">
<SelectGroup>
{genders?.map((item: any) => {
return (
<SelectItem key={item.id} value={item.id}>
{item.title}
</SelectItem>
);
})}
</SelectGroup>
</SelectContent>
</Select>
<FormMessage className="mt-2 " />
</FormItem>
)}
/>
<FormField
control={form.control}
name="education"
render={({ field }) => (
<FormItem className=" w-full md:w-[48%]">
<FormLabel className="text-gray-800 text-sm font-medium">
تحصیلات
</FormLabel>
<Select
onValueChange={field.onChange}
// defaultValue={field.value}
value={field.value}
dir="rtl"
>
<FormControl>
<SelectTrigger
className=" !text-[#7C838A]"
dir="rtl"
>
<SelectValue
className=""
placeholder="تحصیلات خود را انتخاب نمایید."
/>
</SelectTrigger>
</FormControl>
<SelectContent dir="rtl">
<SelectGroup>
{educations?.map((item: any) => {
return (
<SelectItem key={item.id} value={item.id}>
{item.title}
</SelectItem>
);
})}
</SelectGroup>
</SelectContent>
</Select>
<FormMessage className="mt-2 " />
</FormItem>
)}
/>
<FormField
control={form.control}
name="nationalId"
render={({ field }) => (
<FormItem className="w-full md:w-[48%]">
<FormLabel className="text-gray-800 text-sm font-medium">
کد ملی
</FormLabel>
<FormControl>
<Input
className="text-opacity-100"
type="text"
placeholder="کد ملی خود را وارد نمایید "
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="phoneNumber"
render={({ field }) => (
<FormItem className="w-full md:w-[48%]">
<FormLabel className="text-gray-800 text-sm font-medium">
شماره موبایل
</FormLabel>
<FormControl>
<Input
className="text-opacity-100"
type="text"
placeholder="شماره موبایل خود را وارد نمایید "
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="birthday"
render={({ field }) => (
<FormItem className="w-full md:w-[48%] flex flex-col ">
<FormLabel className="text-gray-800 text-sm font-medium">
تاریخ تولد
</FormLabel>
<FormControl>
{/* <Input
type="text"
placeholder="شماره موبایل خود را وارد نمایید "
{...field}
/> */}
{/* <DatePicker value={value} onChange={setValue} /> */}
<DatePicker
inputClass="h-10 w-full rounded border border-input text-gray text-sm"
calendar={persian}
locale={persian_fa}
calendarPosition="bottom-right"
value={date || ""}
onChange={(ab: any) => {
const date = new DateObject(ab).convert(
gregorian,
gregorian_en
);
form.setValue(
"birthday",
date.format("YYYY-MM-DDTHH:mm:ss.SSSSSSS")
);
console.log(
date.format("YYYY-MM-DDTHH:mm:ss.SSSSSSS")
);
}}
placeholder="تاریخ تولد خود را انتخاب نمایید"
onOpenPickNewDate={false}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="flex justify-end w-full gap-2">
<Button
className="w-full sm:w-1/4 text-black bg-yellow rounded-md hover:bg-yellow/80 mt-3 sm:ml-3"
disabled={editProfileMutation.isPending}
type="submit"
>
{editProfileMutation.isPending ? (
<div className="flex items-center justify-center gap-2">
<Oval
visible={true}
height="20"
width="20"
color="#fff"
ariaLabel="oval-loading"
wrapperStyle={{}}
wrapperClass=""
/>
</div>
) : (
"ذخیره"
)}
{/* ورود */}
</Button>
</div>
</form>
</Form>
)}
</div>
</div>
);
}