import React, { useState, useEffect, useRef, useReducer } from 'react'; import Button from '@mui/material/Button'; import Dialog from '@mui/material/Dialog'; import DialogActions from '@mui/material/DialogActions'; import DialogContent from '@mui/material/DialogContent'; import DialogContentText from '@mui/material/DialogContentText'; import DialogTitle from '@mui/material/DialogTitle'; import PropTypes from 'prop-types'; import Box from '@mui/material/Box'; import SelectField from "../../Report/SelectField"; import DatePicker from '../../Report/DatePicker' import TimerPickerSelect from '../TimerPickerSelect' import TextareaAutosize from '@mui/material/TextareaAutosize'; // import { subHours } from "date-fns"; import { IconButton, Paper, Table, TableBody, TableCell, TableHead, TableRow, } from "@material-ui/core"; import { DeleteOutline } from "@material-ui/icons"; import { toast } from "react-toastify"; import api from "../../../services/api"; import toastError from "../../../errors/toastError"; import ConfirmationModal from "../../ConfirmationModal"; const reducer = (state, action) => { if (action.type === "LOAD_SCHEDULES") { const schedulesContact = action.payload; const newSchedules= []; schedulesContact.forEach((schedule) => { const scheduleIndex = state.findIndex((s) => s.id === schedule.id); if (scheduleIndex !== -1) { state[scheduleIndex] = schedule; } else { newSchedules.push(schedule); } }); return [...state, ...newSchedules]; } if (action.type === "DELETE_SCHEDULE") { const scheduleId = action.payload; const scheduleIndex = state.findIndex((q) => q.id === scheduleId); if (scheduleIndex !== -1) { state.splice(scheduleIndex, 1); } return [...state]; } if (action.type === "RESET") { return []; } }; const Item = (props) => { const { sx, ...other } = props; return ( (theme.palette.mode === 'dark' ? '#101010' : '#fff'), color: (theme) => (theme.palette.mode === 'dark' ? 'grey.300' : 'grey.800'), border: '1px solid', borderColor: (theme) => theme.palette.mode === 'dark' ? 'grey.800' : 'grey.300', p: 1, m: 1, borderRadius: 2, fontSize: '0.875rem', fontWeight: '700', ...sx, }} {...other} /> ); } Item.propTypes = { sx: PropTypes.oneOfType([ PropTypes.arrayOf( PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool]), ), PropTypes.func, PropTypes.object, ]), }; const Modal = (props) => { // const [clientSchedules, dispatch] = useReducer(reducer, []); const [selectedSchedule, setSelectedSchedule] = useState(null); const [confirmModalOpen, setConfirmModalOpen] = useState(false); const [open, setOpen] = useState(true); const [scroll, /*setScroll*/] = useState('body'); const [scheduleId, setScheduling] = useState(null) const [startDate, setDatePicker] = useState(new Date()) const [timerPicker, setTimerPicker] = useState(new Date()) const [textArea1, setTextArea1] = useState() const [data] = useState(props.schedules) const [schedulesContact, dispatch] = useReducer(reducer, []); const handleCancel = (event, reason) => { if (reason && reason === "backdropClick") return; setOpen(false); }; useEffect(() => { (async () => { try { const { data } = await api.get("/tickets/" + props.ticketId); dispatch({ type: "LOAD_SCHEDULES", payload: data.schedulesContact }); } catch (err) { toastError(err); } })(); }, [props]); function formatedTimeHour(timer){ return `${timer.getHours().toString().padStart(2, '0')}:${timer.getMinutes().toString().padStart(2, '0')}` } function formatedFullCurrentDate(){ let dateCurrent = new Date() let day = dateCurrent.getDate().toString().padStart(2, '0'); let month = (dateCurrent.getMonth()+1).toString().padStart(2, '0'); let year = dateCurrent.getFullYear(); return `${year}-${month}-${day}`; } const handleCloseConfirmationModal = () => { setConfirmModalOpen(false); setSelectedSchedule(null); }; const handleDeleteSchedule = async (scheduleId) => { try { await api.delete(`/schedule/${scheduleId}`); toast.success(("Lembrete deletado com sucesso!")); dispatch({ type: "DELETE_SCHEDULE", payload: scheduleId }); } catch (err) { toastError(err); } setSelectedSchedule(null); }; // Get from child 2 const datePickerValue = (data) => { console.log('datePickerValue: ',(data)); setDatePicker(data) } // Get from child 3 const timerPickerValue = (data) => { console.log('timerPickerValue: ',(data)); setTimerPicker(data) } const handleChatEnd = (event, reason) => { let dataSendServer = {'scheduleId': scheduleId} if (reason && reason === "backdropClick") return; if (scheduleId === '2'){ console.log('Entrou! textArea1: ', textArea1) if(textArea1 && textArea1.trim().length<5){ alert('Mensagem muito curta!') return } else if(!textArea1){ alert('Defina uma mensagem para enviar para o cliente!') return } else if(formatedFullCurrentDate()===startDate){ if((new Date(timerPicker).getHours() < new Date().getHours() && new Date(timerPicker).getMinutes() <= new Date().getMinutes()) || (new Date(timerPicker).getHours() === new Date().getHours() && new Date(timerPicker).getMinutes() <= new Date().getMinutes()) || (new Date(timerPicker).getHours() < new Date().getHours() && new Date(timerPicker).getMinutes() >= new Date().getMinutes()) || (new Date(timerPicker).getHours() < new Date().getHours)){ alert('Horário menor ou igual horário atual!') return } } else if((new Date(timerPicker).getHours() > 20 && new Date(timerPicker).getMinutes() > 0) || (new Date(timerPicker).getHours() < 6)){ alert('Horário comercial inválido!\n Selecione um horário de lembrete válido entre às 06:00 e 20:00') return } dataSendServer = { 'scheduleId': scheduleId, 'schedulingDate': startDate+' '+formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}:00`)), 'schedulingTime': startDate+' '+formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}:00`)), 'message': textArea1 } } props.func(dataSendServer) setOpen(false); }; const descriptionElementRef = useRef(null); useEffect(() => { if (open) { const { current: descriptionElement } = descriptionElementRef; if (descriptionElement !== null) { descriptionElement.focus(); } } }, [open]); // Get from child 1 const textFieldSelect = (data) => { console.log('textFieldSelect: ',data); setScheduling(data) } const handleChange = (event) => { setTextArea1(event.target.value); }; return ( {props.modal_header} Selecione uma opção para encerrar o Atendimento { return {'value': obj.id, 'label': obj.name} })}/> {scheduleId==='2' && Lembrete } {schedulesContact.length>0 && handleDeleteSchedule(selectedSchedule.id)} > Deseja realmente deletar esse Lembrete? Lembrete Data Hora Mensagem Deletar <> {schedulesContact.map((scheduleData, index) => ( {scheduleData.schedulingDate.split(' ')[0]} {scheduleData.schedulingTime.split(' ')[1]} {scheduleData.message} { setSelectedSchedule(scheduleData); setConfirmModalOpen(true); }} > ))}
}
); } export default Modal