import { useState, useEffect } from "react";
import { Redirect, useParams } from "react-router-dom";
import BtnGroup from "../Buttons/BtnGroup.js";
import scheduleApi from "../../apis/schedule.api";
import { useAuth } from "../../utils/context.js";
import catchErrors from "../../utils/catchErrors.js";
import styles from "./form.module.scss";
const ScheduleForm = () => {
const { user } = useAuth()
const [schedule, setSchedule] = useState({
title: "",
startDate: "",
endDate: "",
startTime: "",
endTime: "",
allDay: user.role === "admin" ? "on" : "",
location: "",
memo: ""
})
const [disabled, setDisabled] = useState(true)
const [success, setSuccess] = useState(false)
const [error, setError] = useState("")
const { scheduleId } = useParams()
useEffect(() => {
if (scheduleId) getOne(scheduleId)
}, [])
useEffect(() => {
let isMounted = true;
const checkInfo = { title: schedule.title, startDate: schedule.startDate, endDate: schedule.endDate }
if (schedule.allDay !== "on") {
checkInfo.startTime = schedule.startTime
checkInfo.endTime = schedule.endTime
} else {
delete checkInfo.startTime
delete checkInfo.endTime
}
if (isMounted) {
const isSchedule = Object.values(checkInfo).every((el) => Boolean(el));
isSchedule ? setDisabled(false) : setDisabled(true);
}
return () => {
isMounted = false;
};
}, [schedule])
async function getOne(id) {
try {
setError("")
const resSchedule = await scheduleApi.getOne(id, user.id)
setSchedule({ ...schedule, ...resSchedule })
} catch (error) {
catchErrors(error, setError)
}
}
function handleChange(e) {
const { name, value } = e.target
if (name === "allDay") {
schedule.allDay !== "on" ? setSchedule({ ...schedule, [name]: value }) : setSchedule({ ...schedule, [name]: "off" })
} else if (name === "startDate") {
setSchedule({ ...schedule, [name]: value, endDate: value })
} else if (name === "startTime") {
setSchedule({ ...schedule, [name]: value, endTime: value })
} else setSchedule({ ...schedule, [name]: value })
}
async function handleSubmit(e) {
e.preventDefault()
try {
setError("")
if (scheduleId) {
await scheduleApi.edit(scheduleId, schedule, user.id)
alert('해당 일정이 성공적으로 수정되었습니다.')
}
else {
await scheduleApi.submit(schedule, user.id)
alert('해당 일정이 성공적으로 등록되었습니다.')
}
setSuccess(true)
} catch (error) {
catchErrors(error, setError)
}
}
if (success) {
if (user.role === "admin") return