import React, { useEffect, useState } from 'react';
import { Head, Link, useForm, usePage } from '@inertiajs/react';
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import FormInput from '@/Components/FormInput';
import Button from '@/Components/Button';
import { isEmpty } from 'lodash';
import Checkbox from '@/Components/Checkbox';
import { router } from '@inertiajs/react';
export default function Role(props) {
const { props: { errors } } = usePage()
const { permissions, role } = props
const [processing, setProcessing] = useState(false)
const [name, setName] = useState('')
const [permins, setPermins] = useState(permissions.map(permin => { return {...permin, checked: false} }))
const handleCheckPermission = (e) => {
setPermins(permins.map(item => {
if(item.name === e.target.name) {
return {
...item,
checked: !item.checked
}
}
return item
}))
}
const handleCheckAll = (e) => {
setPermins(permins.map(item => {
return {
...item,
checked: e.target.checked,
}
}))
}
const handleSubmit = () => {
if(isEmpty(role) === false) {
router.put(route('roles.update', role), {
name: name,
permissions: permins.filter(item => item.checked)
}, {
onStart: () => setProcessing(true),
onFinish: (e) => {
setProcessing(false)
}
})
return
}
router.post(route('roles.store'), {
name: name,
permissions: permins.filter(item => item.checked)
}, {
onStart: () => setProcessing(true),
onFinish: (e) => {
setProcessing(false)
}
})
}
useEffect(() => {
if(!isEmpty(role)) {
setName(role.name)
setPermins(permins.map(item => {
const isExists = role.permissions.find(permit => permit.id === item.id)
if (isExists) {
return {
...item,
checked: true,
}
}
return item
}))
}
}, [role])
return (
{errors.permissions}
)}