"use client"; import React, { useEffect, useRef, useState } from "react"; import { useForm, Controller } from "react-hook-form"; import { Input } from "@/components/ui/input"; import { Button } from "@/components/ui/button"; import { Label } from "@/components/ui/label"; import { Card } from "@/components/ui/card"; import { zodResolver } from "@hookform/resolvers/zod"; import * as z from "zod"; import Swal from "sweetalert2"; import withReactContent from "sweetalert2-react-content"; import { useParams, useRouter } from "next/navigation"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Checkbox } from "@/components/ui/checkbox"; import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"; import JoditEditor from "jodit-react"; import { createAssignmentResponse, createTask, getAssignmentResponseList, getTask, getUserLevelForAssignments, } from "@/service/task"; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog"; import { ChevronDown, ChevronUp } from "lucide-react"; import dynamic from "next/dynamic"; import { Link } from "@/components/navigation"; import { Textarea } from "@/components/ui/textarea"; import { loading } from "@/lib/swal"; import { getCookiesDecrypt } from "@/lib/utils"; const taskSchema = z.object({ uniqueCode: z.string().min(1, { message: "Judul diperlukan" }), title: z.string().min(1, { message: "Judul diperlukan" }), naration: z.string().min(2, { message: "Narasi Penugasan harus lebih dari 2 karakter.", }), }); export type taskDetail = { id: number; uniqueCode: string; title: string; fileTypeOutput: string; assignedToRole: string; assignedToTopLevel: string; assignmentType: { id: number; name: string; }; assignmentMainType: { id: number; name: string; }; taskType: string; broadcastType: string; narration: string; is_active: string; isDone: any; }; interface ListData { id: number; name: string; content: string; timestamp: string; } const ViewEditor = dynamic( () => { return import("@/components/editor/view-editor"); }, { ssr: false } ); export default function FormTaskDetail() { const MySwal = withReactContent(Swal); const router = useRouter(); const editor = useRef(null); type TaskSchema = z.infer; const { id } = useParams() as { id: string }; console.log(id); const userLevelNumber = getCookiesDecrypt("ulne"); const userId = getCookiesDecrypt("uie"); // State for various form fields const [taskOutput, setTaskOutput] = useState({ all: false, video: false, audio: false, image: false, text: false, }); // const [assignmentType, setAssignmentType] = useState("mediahub"); // const [assignmentCategory, setAssignmentCategory] = useState("publication"); const [mainType, setMainType] = useState("1"); const [taskType, setTaskType] = useState("atensi-khusus"); const [broadcastType, setBroadcastType] = useState(""); // untuk Tipe Penugasan const [type, setType] = useState("1"); const [selectedTarget, setSelectedTarget] = useState("all"); const [detail, setDetail] = useState(); const [refresh] = useState(false); const [listDest, setListDest] = useState([]); // Data Polda dan Polres const [checkedLevels, setCheckedLevels] = useState(new Set()); const [expandedPolda, setExpandedPolda] = useState([{}]); const [isLoading, setIsLoading] = useState(false); const [responses, setResponses] = useState([]); const [response, setResponse] = useState(""); const [showInput, setShowInput] = useState(false); const [listData, setListData] = useState([]); const [message, setMessage] = useState(""); const [platformTypeVisible, setPlatformTypeVisible] = useState(false); const [unitSelection, setUnitSelection] = useState({ allUnit: false, mabes: false, polda: false, polres: false, }); const { control, handleSubmit, formState: { errors }, } = useForm({ resolver: zodResolver(taskSchema), }); // const handleRadioChange = (event: React.ChangeEvent) => { // const selectedValue = Number(event.target.value); // setMainType(selectedValue); // setPlatformTypeVisible(selectedValue === 2); // }; useEffect(() => { async function fetchPoldaPolres() { setIsLoading(true); try { const response = await getUserLevelForAssignments(); setListDest(response?.data?.data.list); const initialExpandedState = response?.data?.data.list.reduce( (acc: any, polda: any) => { acc[polda.id] = false; return acc; }, {} ); setExpandedPolda(initialExpandedState); console.log("polres", initialExpandedState); } catch (error) { console.error("Error fetching Polda/Polres data:", error); } finally { setIsLoading(false); } } fetchPoldaPolres(); }, []); useEffect(() => { async function initState() { if (id) { const response = await getTask(id); const details = response?.data?.data; setDetail(details); if (details?.assignedToLevel) { const levels = new Set( details.assignedToLevel.split(",").map(Number) ); setCheckedLevels(levels); } } } initState(); }, [id, refresh]); useEffect(() => { if (detail?.broadcastType) { setBroadcastType(detail.broadcastType); // Mengatur nilai broadcastType dari API } }, [detail?.broadcastType]); useEffect(() => { if (detail?.fileTypeOutput) { const outputSet = new Set(detail.fileTypeOutput.split(",").map(Number)); // Membagi string ke dalam array dan mengonversi ke nomor setTaskOutput({ all: outputSet.has(0), video: outputSet.has(2), audio: outputSet.has(4), image: outputSet.has(1), text: outputSet.has(3), }); } }, [detail?.fileTypeOutput]); useEffect(() => { if (detail?.assignedToTopLevel) { const outputSet = new Set( detail.assignedToTopLevel.split(",").map(Number) ); setUnitSelection({ allUnit: outputSet.has(0), mabes: outputSet.has(1), polda: outputSet.has(2), polres: outputSet.has(3), }); } }, [detail?.fileTypeOutput]); const save = async (data: TaskSchema) => { const fileTypeMapping = { all: "1", video: "2", audio: "3", image: "4", text: "5", }; const selectedOutputs = Object.keys(taskOutput) .filter((key) => taskOutput[key as keyof typeof taskOutput]) // Ambil hanya yang `true` .map((key) => fileTypeMapping[key as keyof typeof fileTypeMapping]) // Konversi ke nilai string .join(","); const requestData = { ...data, // assignmentType, // assignmentCategory, target: selectedTarget, unitSelection, assignedToRole: "3", taskType: taskType, broadcastType: broadcastType, assignmentMainTypeId: mainType, assignmentPurpose: "1", assignmentTypeId: type, fileTypeOutput: selectedOutputs, id: null, narration: data.naration, platformType: "", title: data.title, }; const response = await createTask(requestData); console.log("Form Data Submitted:", requestData); console.log("response", response); MySwal.fire({ title: "Sukses", text: "Data berhasil disimpan.", icon: "success", confirmButtonColor: "#3085d6", confirmButtonText: "OK", }).then(() => { router.push("/en/contributor/task"); }); }; const onSubmit = (data: TaskSchema) => { MySwal.fire({ title: "Simpan Data", text: "Apakah Anda yakin ingin menyimpan data ini?", icon: "warning", showCancelButton: true, cancelButtonColor: "#d33", confirmButtonColor: "#3085d6", confirmButtonText: "Simpan", }).then((result) => { if (result.isConfirmed) { save(data); } }); }; const handleCheckboxChange = (levelId: any) => { setCheckedLevels((prev: any) => { const updatedLevels = new Set(prev); if (updatedLevels.has(levelId)) { updatedLevels.delete(levelId); } else { updatedLevels.add(levelId); } return updatedLevels; }); }; const toggleExpand = (poldaId: any) => { setExpandedPolda((prev: any) => ({ ...prev, [poldaId]: !prev[poldaId], })); }; // const handleToggleInput = () => { // setShowInput((prev: any) => !prev); // Toggle visibility of input field // }; useEffect(() => { async function initState() { // loading(); const response = await getAssignmentResponseList(id); console.log("data", response?.data?.data); console.log("userLvl", userLevelNumber); setListData(response?.data?.data); close(); } initState(); }, []); // const handleSubmitResponse = () => { // console.log("Response Submitted:", response); // setShowInput(false); // Optionally hide the input after submission // }; const handleToggleInput = (): void => { setShowInput(!showInput); }; const handleInputChange = (e: React.ChangeEvent) => { setMessage(e.target.value); }; // const handleSubmitResponse = (): void => { // if (response.trim()) { // const newResponse: Response = { // id: Date.now(), // Unique ID for each response // name: "Mabes Polri - Approver", // content: response, // timestamp: new Date().toLocaleString("id-ID"), // Format timestamp for Indonesia locale // }; // setResponses([newResponse, ...responses]); // Add new response to the top // setResponse(""); // Reset textarea // setShowInput(false); // Hide input // } // }; const postData = () => { sendSuggestionParent(); }; async function sendSuggestionParent() { if (message?.length > 1) { loading(); const data = { assignmentId: id, message, // Gunakan response di sini parentId: null, }; const response = await createAssignmentResponse(data); console.log(response); setMessage(""); const responseGet = await getAssignmentResponseList(id); console.log(responseGet?.data?.data); setListData(responseGet?.data?.data); close(); } } return (

Form Penugasan

{detail !== undefined ? (
( )} />
( )} /> {errors.title?.message && (

{errors.title.message}

)}
{Object.keys(unitSelection).map((key) => (
setUnitSelection({ ...unitSelection, [key]: value }) } />
))}
Daftar Wilayah Polda dan Polres
{listDest.map((polda: any) => (
{expandedPolda[polda.id] && (
{polda?.subDestination?.map((polres: any) => ( ))}
)}
))}
setMainType(value)} // value={String(mainType)} // onValueChange={(value) => setMainType(Number(value))} className="flex flex-wrap gap-3" >
setTaskType(String(value))} className="flex flex-wrap gap-3" >
{/* RadioGroup Assignment Category */}
setType(value)} // Mengubah nilai state ketika pilihan berubah className="flex flex-wrap gap-3" >
{Object.keys(taskOutput).map((key) => (
setTaskOutput({ ...taskOutput, [key]: value }) } />
))}
{/*
setBroadcastType(value)} className="flex flex-wrap gap-3" >
*/}
( )} /> {errors.naration?.message && (

{errors.naration.message}

)}
{showInput && (