import { useRouter } from "next/navigation" import { FC, useEffect, useState } from "react" import { Checkbox, Form, Input, Radio } from "antd" import useAxiosAuth from "@/lib/axios/useAxiosAuth" import { Button } from "@/components/ui/button" import { DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog" import { Label } from "@/components/ui/label" import { Icons } from "@/components/Icons" import { IMenuAction } from "@/app/admin/menu/component/type" import { DUMMY_MENU_LIST, LIST_ACTION_DATA } from "@/lib/data" import { cn } from "@/lib/utils" import { type IRole } from "./type" import { toast } from "sonner" type Props = { isUpdate?: boolean data?: IRole onCancel?: () => any } function createMenuTree(data: IMenuAction[], parentId: Number | null | undefined = null) { const result = []; // Filter items with the specified parentId const filteredItems = data.filter(item => item.menu_parent_id === parentId); // Iterate over the filtered items for (const item of filteredItems) { // Recursively call createMenuTree to build the children for the current item const children = createMenuTree(data, item.id); // Add the children array to the current item if there are children if (children.length > 0) { item.children = children; } // Add the current item to the result array result.push(item); } return result; } function assignMenuLevel(menuList: IMenuAction[], existMenu: IMenuAction[], level: number = 1) { for (const menu of menuList) { if (menu.children && menu.children.length > 0) { existMenu.push({ ...menu, menu_level: level, action: [] }) assignMenuLevel(menu.children, existMenu, level + 1); } else { existMenu.push({ ...menu, menu_level: level, action: [] }) } } return existMenu; } export default function ComponentForm({ data, isUpdate, onCancel }: Props) { const [isLoading, setIsLoading] = useState(false) const [allowAdmin, setAllowAdmin] = useState(false) const [privilegeMenus, setPrivilegeMenus] = useState([]) const [form] = Form.useForm(); const router = useRouter() const axios = useAxiosAuth() // const { data: menuList } = useFetch('/menu') useEffect(() => { if (DUMMY_MENU_LIST && DUMMY_MENU_LIST.length > 0) { // CREATE MENU TREE const nestedMenuData = createMenuTree(DUMMY_MENU_LIST as IMenuAction[]); // console.log(nestedMenuData) // DESTRUCTURING MENU TREE INTO ONE LIST const result: IMenuAction[] = [] const resultData = assignMenuLevel(nestedMenuData, result); // REMOVE "children object" const arrayMenu = resultData.map(({ children, ...rest }) => rest); if (data && data.privilege) { const existData = [...arrayMenu].map((item) => { // FIND ACTION FROM EXISTING DATA AND SET IT const findIdxAction = data.privilege.findIndex((menu: any) => menu.menu_id === item.id) if (findIdxAction > -1) { item.action = data.privilege[findIdxAction].action } return item }) setPrivilegeMenus(existData) } else { setPrivilegeMenus(arrayMenu) } } }, [DUMMY_MENU_LIST, data]) useEffect(() => { if (data) { if (data.allow_admin) setAllowAdmin(data.allow_admin) form.setFieldsValue(data) } else { form.resetFields() } }, [data, form]) const handleSubmit = (value: any) => { !isUpdate ? handleCreate(value) : handleUpdate(value) } const handleCreate = async (payload: IRole) => { try { setIsLoading(true) // await axios.post('/dayoff', payload) if (allowAdmin) { // ONLY SUBMIT MENU THAT HAVE ACTION const submitedPrivilegeMenus = privilegeMenus.filter(item => item.action?.length! > 0) // REMOVE CHILD MENU DOES"NT HAVE A PARENT const filterChildNotHaveParent = [...submitedPrivilegeMenus].filter((item) => { if (item.menu_level > 1) { const findParent = [...submitedPrivilegeMenus].find(menu => menu.id === item.menu_parent_id) if (findParent) { return true } return false } else { return true } }).map(item => { return { menu_id: item.id, menu_name: item.name, action: item.action } }) payload['privilege'] = filterChildNotHaveParent } else { payload['privilege'] = [] } localStorage.setItem('role_test', JSON.stringify(payload)) handleSuccess('Data successfully created.') } catch (error: any) { handleError(`Data failed to create, (${error.response.data.code || error.response.status || '-'}) ${error.response.data.message || error.response.statusText || error.message}`) } } const handleUpdate = async (payload: IRole) => { try { setIsLoading(true) // await axios.put('/dayoff/' + data?.id, payload) if (allowAdmin) { // ONLY SUBMIT MENU THAT HAVE ACTION const submitedPrivilegeMenus = privilegeMenus.filter(item => item.action?.length! > 0) // REMOVE CHILD MENU DOES"NT HAVE A PARENT const filterChildNotHaveParent = [...submitedPrivilegeMenus].filter((item) => { if (item.menu_level > 1) { const findParent = [...submitedPrivilegeMenus].find(menu => menu.id === item.menu_parent_id) if (findParent) { return true } return false } else { return true } }).map(item => { return { menu_id: item.id, menu_name: item.name, action: item.action } }) payload['privilege'] = filterChildNotHaveParent } else { payload['privilege'] = [] } localStorage.setItem('role_test', JSON.stringify(payload)) handleSuccess('Data successfully updated.') } catch (error: any) { handleError(`Data failed to update, (${error.response.data.code || error.response.status || '-'}) ${error.response.data.message || error.response.statusText || error.message}`) } } const handleSuccess = (message: string) => { toast.success(message) setIsLoading(false) onCancel!() router.refresh() form.resetFields() } const handleError = (message: string) => { toast.error(message) setIsLoading(false) } const handleCheckAllAction = (action: typeof LIST_ACTION_DATA[0], isChecked: boolean) => { console.log({ action, isChecked }) const existData = [...privilegeMenus] if (isChecked) { existData.map((item) => { item.action?.push(action.id) return item }) } else { existData.map((item) => { const index = item.action?.indexOf(action.id); if (index! > -1) { item.action?.splice(index!, 1); } return item }) } setPrivilegeMenus(existData) } const handleCheckMenu = (menu: IMenuAction, isChecked: boolean) => { console.log({ menu, isChecked }) const existData = [...privilegeMenus] const findIndex = existData.findIndex(item => item.id === menu.id) if (isChecked) { existData[findIndex].action = LIST_ACTION_DATA.map(item => item.id) } else { existData[findIndex].action = [] // FIND CHILD AND ALSO REMOVE ACTION IN NESTED CHILD IF EXIST const filterChild = existData.filter(item => item.menu_parent_id === menu.id) if (filterChild.length > 0) { for (const item of filterChild) { handleCheckMenu(item, isChecked) } } } setPrivilegeMenus(existData) } const handleCheckAction = (menu: IMenuAction, action: number[]) => { console.log({ menu, action }) const existData = [...privilegeMenus] const findIndex = existData.findIndex(item => item.id === menu.id) existData[findIndex].action = action as number[] setPrivilegeMenus(existData) } const disableCheckAction = (menu: IMenuAction) => { if (menu.menu_level > 1) { const { menu_parent_id } = menu const findParent = privilegeMenus.find(item => item.id === menu_parent_id) if (findParent?.action?.length! <= 0) { return true } } return false } return (
{isUpdate ? 'Update role' : 'Create new role'} Add or update a role and adjust the privilege
setAllowAdmin(e.target.value)}> Dissallow Allow
{allowAdmin &&
{/* HEADER */}
Menu Name {LIST_ACTION_DATA.map((action) =>
handleCheckAllAction(action, e.target.checked)}> {action.name}
)}
{/* BODY */} {privilegeMenus.length > 0 && privilegeMenus.map((menu: IMenuAction, key: number) => //
0} onChange={(e) => handleCheckMenu(menu, e.target.checked)} disabled={disableCheckAction(menu)} > {menu.name}
handleCheckAction(menu, val)} disabled={disableCheckAction(menu)} > {LIST_ACTION_DATA?.length > 0 && LIST_ACTION_DATA.map((item: any, key: number) =>
)}
)}
}
) } type ChildrenProps = { menu: IMenuAction className?: string onMenuChecked: (menu: IMenuAction, isChecked: boolean) => any onActionChecked: (menu: IMenuAction, action: typeof LIST_ACTION_DATA[0], isChecked: boolean) => any } const ChildrenItem: FC = ({ menu, className, onMenuChecked, onActionChecked }) => { return ( <>
onMenuChecked(menu, e.target.checked)}> {menu.name}
console.log(e)}> {LIST_ACTION_DATA?.length > 0 && LIST_ACTION_DATA.map((item: any, key: number) =>
onActionChecked(menu, item, e.target.checked)}>
)}
{menu.children && menu.children.length > 0 && menu.children.map((item) => )} ) }