import * as Yup from 'yup'; import { useSnackbar } from 'notistack'; import { useNavigate } from 'react-router-dom'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import MenuItem from '@mui/material/MenuItem'; import Select, { SelectChangeEvent } from '@mui/material/Select'; import * as React from 'react'; // form import {useFieldArray, useForm } from 'react-hook-form'; import { yupResolver } from '@hookform/resolvers/yup'; // @mui import { styled } from '@mui/material/styles'; import { LoadingButton } from '@mui/lab'; import { Box, Autocomplete, Avatar, Button, ButtonGroup, Card, FormHelperText, Grid, Stack, Typography, TextField, Chip, Badge, Divider, } from '@mui/material'; import CancelIcon from '@mui/icons-material/Cancel'; // components import { FormProvider, RHFTextField, RHFRadioGroup, RHFUploadAvatar, RHFSwitch, RHFEditor, RHFDatepicker, RHFMultiCheckbox, RHFCheckbox, RHFCustomMultiCheckbox, } from '../../../components/hook-form'; import axios from '../../../utils/axios'; import { fCurrency } from '../../../utils/formatNumber'; import { Appointment } from '../../../@types/doctor'; import RHFTextFieldMoney from "@/components/hook-form/v2/RHFTextFieldMoney"; import { Label, Rowing, Spa } from '@mui/icons-material'; import { border, padding } from '@mui/system'; import { IconButton } from '@mui/material'; import AddIcon from '@mui/icons-material/Add'; import RemoveIcon from '@mui/icons-material/Remove'; const LabelStyle = styled(Typography)(({ theme }) => ({ ...theme.typography.subtitle2, color: theme.palette.text.secondary, marginBottom: theme.spacing(1), })); const HeaderStyle = styled('header')(({ theme }) => ({ paddingBottom: theme.spacing(5), display: 'flex', alignItems: 'center', justifyContent: 'space-between', })); const Title = styled(Typography)(({ theme }) => ({ ...theme.typography.h4, boxShadow: 'none', // paddingBottom: theme.spacing(3), fontWeight: 700, color: '#005B7F', })); interface FormValuesProps extends Partial { taxes: boolean; inStock: boolean; } type Props = { isEdit: boolean; id: number; currentAppointment?: Appointment; }; const Span = styled(Typography)(({ theme }) => ({ boxShadow: 'none', paddingBottom: theme.spacing(1), })); const Text = styled(Typography)(({ theme }) => ({ boxShadow: 'none', paddingBottom: theme.spacing(3), })); export default function AppointmentForm({ isEdit, id, currentAppointment }: Props) { const navigate = useNavigate(); // const [ errors, setErrors ] = useState<{ [key: string]: string }>({}); const { enqueueSnackbar } = useSnackbar(); const NewCorporateSchema = Yup.object().shape({ // name: Yup.string().required('Name is required'), // file: Yup.boolean().required('Corporate Status is required'), }); const defaultValues = useMemo( () => ({ id: currentAppointment?.id, name: currentAppointment?.name || '', address: currentAppointment?.address || '', birth_date: currentAppointment?.birth_date || '', gender: currentAppointment?.gender || '', description: currentAppointment?.description || '', birth_place: currentAppointment?.birth_place || '', active: currentAppointment?.active === 1 ? true : false, avatar_url: currentAppointment?.avatar_url || '', doctor_id: currentAppointment?.doctor_id || '', organizations: currentAppointment?.organizations || [], specialities: currentAppointment?.specialities || [], diagnosis: currentAppointment?.diagnosis || '', hospital: currentAppointment?.hospital || null, medicine : currentAppointment?.medicine || [ { drug_id: 0, qty: 0, signa: '', unit_id: 0, note: '', // input to database } ], }), // eslint-disable-next-line react-hooks/exhaustive-deps [currentAppointment] ); console.log() const methods = useForm({ // resolver: yupResolver(NewCorporateSchema), defaultValues, }); const {fields, append, remove} = useFieldArray({name: 'medicine',control: methods.control}) // Autocomplite ICD const [icdOptions, setIcdOptions] = useState([]); useEffect(() => { // Ambil data dari API dan atur opsi ICD axios.get('diagnosis') .then((response) => { setIcdOptions(response.data.data); }) .catch((error) => { console.error('Error fetching ICD options:', error); }); }, []); // useEffect dijalankan hanya sekali saat komponen dimount // Menggunakan selectedIcdOptions sebagai state untuk nilai default const [selectedIcdOptions, setSelectedIcdOptions] = useState([]); const codes = defaultValues.diagnosis.split(','); useEffect(() => { // Pastikan bahwa icdOptions sudah terisi sebelum memfilter if (icdOptions.length > 0) { const selectedCodes = icdOptions.filter((icd) => { return codes.includes(icd.value); }); setSelectedIcdOptions(selectedCodes); // setValue('diagnosis', selectedCodes); // Ini bisa Anda hilangkan jika tidak diperlukan } }, [icdOptions, defaultValues.diagnosis]); // Autocomplite Rumah Sakit const [hospitalOptions, setHospitalOptions] = useState([]); const [selectedHospitalOption, setSelectedHospitalOption] = useState(null); // Ambil data dari API dan atur opsi rumah sakit useEffect(() => { axios.get('hospitals') .then((response) => { setHospitalOptions(response.data.data); }) .catch((error) => { console.error('Error fetching hospital options:', error); }); }, []); // useEffect dijalankan hanya sekali saat komponen dimount // Set default value saat hospitalOptions berubah useEffect(() => { const selectedId = hospitalOptions.find((hospital) => { return hospital.value == defaultValues.hospital }); setSelectedHospitalOption(selectedId); setValue('hospital', defaultValues.hospital) }, [hospitalOptions, defaultValues]); // Autocomplite drugs const [drugOptions, setDrugsOptions] = useState([]); const [selectedDrugsOptions, setSelectedDrugsOptions] = useState({}); const handleAutocompleteChange = (newValue, index) => { setSelectedDrugsOptions((prevState) => ({ ...prevState, [index]: newValue })); setValue(`medicine.${index}.drug_id`, newValue ? newValue.value : ''); }; // Ambil data dari API dan atur opsi rumah sakit useEffect(() => { axios.get('drugs') .then((response) => { setDrugsOptions(response.data.data); }) .catch((error) => { console.error('Error fetching drug options:', error); }); }, []); // useEffect dijalankan hanya sekali saat komponen dimount // Autocomplite unit const [unitOptions, setUnitsOptions] = useState([]); const [selectedUnitsOptions, setSelectedUnitsOptions] = useState({}); const handleAutocompleteChangeUnit = (newValue, index) => { setSelectedUnitsOptions((prevState) => ({ ...prevState, [index]: newValue })); setValue(`medicine.${index}.unit_id`, newValue ? newValue.value : ''); }; // Ambil data dari API dan atur opsi rumah sakit useEffect(() => { axios.get('units') .then((response) => { setUnitsOptions(response.data.data); }) .catch((error) => { console.error('Error fetching unit options:', error); }); }, []); // useEffect dijalankan hanya sekali saat komponen dimount useEffect(() => { if (defaultValues.medicine.length > 0) { defaultValues.medicine.map((med, index) => { const selectedDrugId = drugOptions.find((drug) => { return drug.value == med.drug_id }); handleAutocompleteChange(selectedDrugId,index) const selectedUnitId = unitOptions.find((unit) => { return unit.value == med.unit_id }); handleAutocompleteChangeUnit(selectedUnitId,index) // Contoh: Lakukan tindakan lainnya sesuai kebutuhan Anda }); } else { console.log('Medicine is empty'); } }, [defaultValues.medicine]); const { reset, watch, control, setValue, getValues, setError, handleSubmit, formState: { isSubmitting }, } = methods; const values = watch(); useEffect(() => { if (isEdit && currentAppointment) { reset(defaultValues); } if (!isEdit) { reset(defaultValues); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [isEdit, currentAppointment]); const onSubmit = async (data: FormValuesProps) => { try { const formData = new FormData(); formData.append('id', data.id); formData.append('diagnosis', data.diagnosis); formData.append('hospital', data.hospital); // Iterasi melalui setiap objek dalam array medicine dan menambahkannya ke FormData data.medicine.forEach((medicineObj, index) => { // Anda dapat menambahkan setiap properti dari objek medicine ke FormData formData.append(`medicine[${index}][drug_id]`, medicineObj.drug_id); formData.append(`medicine[${index}][qty]`, medicineObj.qty); formData.append(`medicine[${index}][unit_id]`, medicineObj.unit_id); formData.append(`medicine[${index}][signa]`, medicineObj.signa); formData.append(`medicine[${index}][note]`, medicineObj.note); }); const response = await axios.post('/prescription', formData); reset(); enqueueSnackbar('Berhasil menambahkan resep', { variant: 'success', }); navigate('/e-prescription/live-chat'); } catch (error: any) { console.log(error, 'submit') enqueueSnackbar(error.message ?? 'Failed Processing Request', { variant: 'error' }); } const ascent = document?.querySelector('ascent'); if (ascent != null) { ascent.innerHTML = ''; } }; const handleDownloadEPrescription = (id: number) => { axios .get(`prescription-download/${id}`, { responseType: 'blob', }) .then((response) => { window.open(URL.createObjectURL(response.data)); }) .catch((response) => { enqueueSnackbar(response.message, { variant: 'error' }); }); } return ( {/* */} } spacing={2} > Data Live Chat Status Appointment : Status Chat : Tanggal Booking : {currentAppointment?.date_created ? currentAppointment?.date_created : '-'} Tanggal Appointment : {currentAppointment?.date_appointment ? currentAppointment?.date_appointment : '-'} Nama Dokter {currentAppointment?.doctor_name ? currentAppointment?.doctor_name : '-'} Faskes {currentAppointment?.health_care ? currentAppointment?.health_care : '-'} Durasi {currentAppointment?.duration ? currentAppointment?.duration : '-'} Spesialis {currentAppointment?.speciality ? currentAppointment?.speciality : '-'} Appointment Via Web/App {currentAppointment?.appointment_media ? currentAppointment?.appointment_media : '-'} Data Pembayaran {currentAppointment?.payment_detail !== null ? ( Metode Pembayaran {currentAppointment?.payment_method ? currentAppointment?.payment_method : '-'} Harga {currentAppointment?.payment_detail?.gross_amount ? currentAppointment?.payment_detail?.gross_amount : '-'} Mata Uang {currentAppointment?.payment_detail?.currency ? currentAppointment?.payment_detail?.currency : '-'} Tipe Pembayaran {currentAppointment?.payment_detail?.payment_type ? currentAppointment?.payment_detail?.payment_type : '-'} Waktu Transaksi {currentAppointment?.payment_detail?.transaction_time ? currentAppointment?.payment_detail?.transaction_time : '-'} Status {currentAppointment?.payment_detail?.status_message ? currentAppointment?.payment_detail?.status_message : '-'} ) : ( Belum ada pembayaran )} E-Prescription Diagnosa option.label} fullWidth value={selectedIcdOptions} onChange={(e, newValues) => { const selectedCodes = newValues.map((value) => value.value); setValue('diagnosis', selectedCodes); setSelectedIcdOptions(newValues); }} renderInput={(params) => ( )} /> {/* Rumah Sakit option.label} fullWidth value={selectedHospitalOption} onChange={(e, newValue) => { setSelectedHospitalOption(newValue); setValue('hospital', newValue ? newValue.value : ''); // Simpan nilai rumah sakit }} renderInput={(params) => ( )} /> */} Obat {fields.map((field, index) => ( option.label} fullWidth value={selectedDrugsOptions[index] || null} onChange={(e, newValue) => handleAutocompleteChange(newValue, index)} renderInput={(params) => ( )} /> option.label} fullWidth value={selectedUnitsOptions[index] || null} onChange={(e, newValue) => handleAutocompleteChangeUnit(newValue, index)} renderInput={(params) => ( )} /> { index === 0 ? ( append({medicine_name: '', medicine_price: 0, request_log_id: 1 })}> ) : ( index == (fields.length-1) ? ( remove(index)}> ) : ( append({medicine_name: '', medicine_price: 0, request_log_id: 1 })}> ) ) } ))} {!isEdit ? 'Save' : 'Update'} ); }