import React, { useState, useEffect } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import DatePicker from "react-datepicker";



import * as EgovNet from 'api/egovFetch';
import URL from 'constants/url';
import CODE from 'constants/code';

import { default as EgovLeftNav } from 'components/leftmenu/EgovLeftNavAdmin';

import 'react-datepicker/dist/react-datepicker.css';

import styled from "styled-components";
import { makeStyles } from "@mui/styles";

const useStyles = makeStyles(() => ({
    shake: {
      animation: "$description 15s",
      animationIterationCount: "1"
    },
    "@keyframes description": {
      "0%": { opacity: 0, transform: "translateY(0)" },
      "15%": { transform: "translateY(-4px, 0)" },
      "30%": { transform: "translateY(6px, 0)" },
      "45%": { transform: "translateY(-4px, 0)" },
      "60%": { transform: "translateY(6px, 0)" },
      "100%": { opacity: 1, transform: "translateY(0)" }
    }
  }));

const StyledDiv = styled.div`
    .org-under-id {
        margin-left: 20px;
        @media only screen and (max-width: 768px) {
            display: block;
            margin-left: 0px;
            margin-top: 20px;
        }
    }

    .f_select.w_250 {
        @media only screen and (max-width: 768px) {
            width: 100%;
        }
    }

    .f_input {
        @media only screen and (max-width: 768px) {
            width: 100%;
        }
    }
`;

function SchedulesEdit(props) {
    console.group("EgovAdminScheduleEdit");
    console.log("[Start] EgovAdminScheduleEdit ------------------------------");
    console.log("EgovAdminScheduleEdit [props] : ", props);

    const classes = useStyles();
    const [isShake, setShake] = useState(false);

    //${location.state?.schdulId
    
    const getDateFourteenDigit = (date) => {
        return `${getYYYYMMDD(date).toString()}${makeTwoDigit(date.getHours())}${makeTwoDigit(date.getMinutes())}${makeTwoDigit(date.getSeconds())}`;
    }
    const getYYYYMMDD = (date) => {
        return date.getFullYear().toString() + makeTwoDigit(Number(date.getMonth() + 1)) + makeTwoDigit(date.getDate());
    }
    const makeTwoDigit = (number) => {
        return number < 10 ? "0" + number : number.toString();
    }


    const navigate = useNavigate();
    const location = useLocation();
    console.log("EgovAdminScheduleEdit [location] : ", location);

    const [modeInfo, setModeInfo] = useState({ mode: props.mode });
    const [scheduleDetail, setScheduleDetail] = useState
        (
            {
                startDate: new Date(),
                endDate: new Date(),            
                eventId : 0,
            }
        );

    const [schdulBgndeHH, setSchdulBgndeHH] = useState();
    const [schdulBgndeMM, setSchdulBgndeMM] = useState();
    const [schdulEnddeHH, setSchdulEnddeHH] = useState();
    const [schdulEnddeMM, setSchdulEnddeMM] = useState();

    const [scheduleInit, setScheduleInit] = useState({});
    const [scheduleApiOrgApiDepthList, setScheduleApiOrgApiDepthList] = useState({ });


    const initMode = () => {

        // props.mode 값이 없으면 에러가 발생한다.
        switch (props.mode) {
            case CODE.MODE_CREATE:
                setModeInfo({
                    ...modeInfo,
                    modeTitle: "등록",
                    method : "POST",
                    editURL: '/schedule'
                });
                break;
            case CODE.MODE_MODIFY:
                setModeInfo({
                    ...modeInfo,
                    modeTitle: "수정",
                    method : "PUT",
                    editURL: '/schedule'
                });
                break;
			default:
                navigate({pathname: URL.ERROR}, {state: {msg : ""}});
        }
        retrieveDetail();
    }

    const convertDate = (str) => {
        let year = str.substring(0, 4);
        let month = str.substring(4, 6);
        let date = str.substring(6, 8);
        let hour = str.substring(8, 10);
        let minute = str.substring(10, 12);
        return new Date(year, month - 1, date, hour, minute)
    }

    const requestOptions = {
        method: "GET",
        headers: {
            'Content-type': 'application/json'
        }
    }

    const retrieveDetail = () => {  

        EgovNet.requestFetch("/schedule/init",
            requestOptions,
            function (resp) {
                setScheduleInit(
                    resp
                );

                if (modeInfo.mode === CODE.MODE_CREATE) {// 조회/등록이면 조회 안함
                    setScheduleDetail({
                        ...scheduleDetail,
                        schdulBgnde:  location.state.iUseDate,
                        schdulEndde: location.state.iUseDate,
                        startDate: convertDate(location.state.iUseDate),
                        endDate: convertDate(location.state.iUseDate),
                    });
                    return;
                }
        
                const retrieveDetailURL = `/schedule/${location.state?.schdulId}`;
                const requestOptions = {
                    method: "GET",
                    headers: {
                        'Content-type': 'application/json'
                    }
                }
                EgovNet.requestFetch(retrieveDetailURL,
                    requestOptions,
                    function (resp) {

                        let rawScheduleDetail = resp.result;
                        //기본값 설정
                        setScheduleDetail({
                            ...scheduleDetail,
                            ...rawScheduleDetail,
                            startDate: convertDate(rawScheduleDetail.schdulBgnde),
                            endDate: convertDate(rawScheduleDetail.schdulEndde),
                        });
                    }
                );
            }
        );
        
    }

    const updateSchedule = () => {
        const formData = new FormData();
        
        for (let key in scheduleDetail) {
            if ( key === 'startDate' ) {
                formData.append(key, getDateFourteenDigit( scheduleDetail[key] ));
            } else if( key === 'endDate' ) {
                formData.append(key, getDateFourteenDigit( scheduleDetail[key] ));
            } else {
                formData.append(key, scheduleDetail[key]);
            }
            
            console.log("scheduleDetail [%s] ", key, scheduleDetail[key]);
        }

        if ( formValidator(formData) ) {
            const requestOptions = {
                method: modeInfo.method,
                body: formData
            }

            if (modeInfo.mode === CODE.MODE_MODIFY) {
                modeInfo.editURL = `${modeInfo.editURL}/${location.state?.schdulId}`;
            }
            EgovNet.requestFetch(modeInfo.editURL,
                requestOptions,
                (resp) => {
                    if (Number(resp.resultCode) === Number(CODE.RCV_SUCCESS)) {                        
                        alert('일정이 등록되었습니다.');
                        navigate({ pathname: URL.ADMIN__COMMITTEE__SCHEDULES__DETAIL }, {state: {schdulId : resp.result?.schdulId}});
                    } else {
                        navigate({pathname: URL.ERROR}, {state: {msg : resp.resultMessage}});
                    }
                }
            );
        }

    }

    const formValidator = (formData) => {
        
        if (formData.get('divMeet') === null || formData.get('divMeet') === "") {
            alert("구분을 선택해 주세요.");
            return false;
        }
        if (formData.get('upCommittee') === null || formData.get('upCommittee') === "") {
            alert("심의위원회 첫 번째 값을 선택해 주세요.");
            return false;
        }
        if (formData.get('committee') === null || formData.get('committee') === "") {
            alert("심의위원회 두 번째 값을 선택해 주세요.");
            return false;
        }
        if (formData.get('title') === null || formData.get('title') === "") {
            alert("제목을 입력해 주세요.");
            return false;
        }
        if (formData.get('location') === null ||formData.get('location') === "") {
            alert("장소를 입력해 주세요.");
            return false;
        }
        if (formData.get('contents') === null ||formData.get('contents') === "") {
            alert("내용을 입력해 주세요.");
            return false;
        }        
        if (formData.get('schdulBgnde') > formData.get('schdulEndde')) {
            alert("종료일시는 시작일시보다 앞 설 수 없습니다.");
            //return false;
        }
        return true;
    }

    useEffect(function () {
        initMode();
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    useEffect(function () {
        console.log("------------------------------EgovAdminScheduleEdit [%o]", scheduleDetail);
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [scheduleDetail]);

    useEffect(function () {        

        EgovNet.requestFetch(`/schedule/api/org-api/depth/list?paramCodeGroup=${scheduleDetail.upCommittee}`,
            requestOptions,
            function (resp) {
                setScheduleApiOrgApiDepthList(
                    resp
                );                
            }
        );
        console.log("------------------------------EgovAdminScheduleEdit [%o]", scheduleDetail);
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [scheduleDetail && scheduleDetail.upCommittee]);
    

    const onClickDeleteSchedule = (schdulId) => {
        const deleteBoardURL = `/schedule/${schdulId}`;

        const requestOptions = {
            method: "DELETE",
            headers: {
                'Content-type': 'application/json',
            }
        }

        EgovNet.requestFetch(deleteBoardURL,
            requestOptions,
            (resp) => {
                console.log("====>>> Schdule delete= ", resp);
                if (Number(resp.resultCode) === Number(CODE.RCV_SUCCESS)) {
                    alert("게시글이 삭제되었습니다.")
                    navigate(URL.ADMIN__COMMITTEE__SCHEDULES ,{ replace: true });
                } else {
                    navigate({pathname: URL.ERROR}, {state: {msg : resp.resultMessage}});
                }

            }
        );
    }

    console.log("------------------------------EgovAdminScheduleEdit [End]");
    console.groupEnd("EgovAdminScheduleEdit");
    return (
        <div className="container">
            <div className="c_wrap">
                {/* <!-- Location --> */}
                <div className="location">
                    <ul>
                        <li><Link to={URL.MAIN} className="home">Home</Link></li>
                        <li><Link to={URL.ADMIN}>사이트 관리</Link></li>
                        <li>위원회 관리</li>
                        <li>위원회 일정 관리</li>
                    </ul>
                </div>
                {/* <!--// Location --> */}

                <div className="layout">
                    {/* <!-- Navigation --> */}
                    <EgovLeftNav></EgovLeftNav>
                    {/* <!--// Navigation --> */}

                    <div className="contents SITE_SCHDULE_REG" id="contents">
                        {/* <!-- 본문 --> */}

                        <div className="top_tit">
                            <h1 className="tit_1">위원회 일정 관리</h1>
                        </div>

                        {/* <!-- <h2 className="tit_2">위원회 일정 추가</h2> --> */}

                        {/* <!-- 게시판 상세보기 --> */}
                        <StyledDiv className="board_view2">
                            <dl>
                                <dt>구분<span className="req">필수</span></dt>
                                <dd>
                                    <label className="f_select w_150" htmlFor="div-meet">
                                        <select id="div-meet" name="div-meet" title="일정구분"
                                            value={scheduleDetail.divMeet}
                                            onChange={(e) => setScheduleDetail({ ...scheduleDetail, divMeet: e.target.value })}>
                                            <option key={"none"} value="">선택</option>
                                            {scheduleInit && scheduleInit.result && scheduleInit.result.listCodes
                                            && scheduleInit.result.listCodes.map((item) => (
                                                <option key={item.id} value={item.id}>{item.name}</option>
                                            ))}
                                        </select>
                                    </label>
                                </dd>
                            </dl>
                            <dl>
                                <dt>심의위원회<span className="req">필수</span></dt>
                                <dd>
                                    <label className="f_select w_250 up-committe" htmlFor="up-committee">
                                        <select id="up-committe" name="up-committe" title="심의위원회-상위"
                                            value={scheduleDetail.upCommittee}
                                            onChange={(e) => setScheduleDetail({ ...scheduleDetail, upCommittee: e.target.value })}>
                                            <option value="">선택</option>
                                            {scheduleInit && scheduleInit.result && scheduleInit.result.listTopOrg
                                            && scheduleInit.result.listTopOrg.map((item) => (
                                                <option key={item.id} value={item.id}>{item.name}</option>
                                            ))}
                                        </select>
                                    </label>
                                    <label className="f_select w_250 org-under-id" htmlFor="committee">
                                        <select id="committee" name="committee" title="심의위원회-하위"
                                            value={scheduleDetail.committee}
                                            onChange={(e) => setScheduleDetail({ ...scheduleDetail, committee: e.target.value })}>
                                            <option value="">선택</option>
                                            {scheduleApiOrgApiDepthList && scheduleApiOrgApiDepthList.result && scheduleApiOrgApiDepthList.result.list
                                            && scheduleApiOrgApiDepthList.result.list.map((item) => (
                                                <option key={item.id} value={item.id}>{item.name}</option>
                                            ))}
                                        </select>
                                    </label>
                                </dd>
                            </dl>
                            <dl>
                                <dt><label htmlFor="title">제목</label><span className="req">필수</span></dt>
                                <dd>
                                    <input className="f_input2 w_full" type="text" name="title" title="제목" id="title" placeholder="제목을 입력하세요."
                                        value={scheduleDetail.title}
                                        onChange={(e) => setScheduleDetail({ ...scheduleDetail, title: e.target.value })}
                                    />
                                </dd>
                            </dl>
                            <dl>
                                <dt><label htmlFor="location">장소</label><span className="req">필수</span></dt>
                                <dd>
                                    <input className="f_input2 w_full" type="text" name="location" title="장소" id="location" placeholder="장소를 입력하세요."
                                        defaultValue={scheduleDetail.location}
                                        onChange={(e) => setScheduleDetail({ ...scheduleDetail, location: e.target.value })} />
                                </dd>
                            </dl>
                            <dl>
                                <dt>날짜/시간<span className="req">필수</span></dt>
                                <dd className="datetime">
                                    <span className="line_break">
                                        <DatePicker
                                            selected={scheduleDetail.startDate}
                                            name="schdulBgnde"
                                            className="f_input"
                                            dateFormat="yyyy-MM-dd HH:mm"
                                            showTimeInput
                                            onChange={(date) => {
                                                console.log("setStartDate : ", date);
                                                setScheduleDetail({ ...scheduleDetail, schdulBgnde: getDateFourteenDigit(date), schdulBgndeYYYMMDD: getYYYYMMDD(date), schdulBgndeHH: date.getHours(), schdulBgndeMM: date.getMinutes(), startDate: date });
                                                setSchdulBgndeHH(date.getHours());
                                                setSchdulBgndeMM(date.getMinutes());
                                            }} />
                                        <input type="hidden" name="schdulBgndeHH" defaultValue={schdulBgndeHH} readOnly />
                                        <input type="hidden" name="schdulBgndeMM" defaultValue={schdulBgndeMM} readOnly />
                                        <span className="f_inn_txt">~</span>
                                    </span>
                                    <span className="line_break">
                                        <DatePicker
                                            selected={scheduleDetail.endDate}
                                            name="schdulEndde"
                                            className="f_input"
                                            dateFormat="yyyy-MM-dd HH:mm"
                                            showTimeInput
                                            minDate={scheduleDetail.startDate}
                                            onChange={(date) => {
                                                console.log("setEndDate: ", date);
                                                setScheduleDetail({ ...scheduleDetail, schdulEndde: getDateFourteenDigit(date), schdulEnddeYYYMMDD: getYYYYMMDD(date), schdulEnddeHH: date.getHours(), schdulEnddeMM: date.getMinutes(), endDate: date });
                                                setSchdulEnddeHH(date.getHours());
                                                setSchdulEnddeMM(date.getMinutes());
                                            }
                                            } />
                                        <input type="hidden" name="schdulEnddeHH" defaultValue={schdulEnddeHH} readOnly />
                                        <input type="hidden" name="schdulEnddeMM" defaultValue={schdulEnddeMM} readOnly />
                                    </span>
                                </dd>
                            </dl>
                            <dl>
                                <dt><label htmlFor="contents">내용</label><span className="req">필수</span></dt>
                                <dd>
                                    <textarea className="f_txtar w_full h_100" name="contents" id="contents" cols="30" rows="10" placeholder="일정 내용을 입력하세요."
                                        defaultValue={scheduleDetail.contents}
                                        onChange={(e) => setScheduleDetail({ ...scheduleDetail, contents: e.target.value })}
                                    ></textarea>
                                </dd>
                            </dl>

                            {/* <!-- 버튼영역 --> */}
                            <div className="board_btn_area">
                                <div className="left_col btn1">
                                    <button className="btn btn_skyblue_h46 w_100"
                                        onClick={() => updateSchedule()}
                                    > 저장</button>
                                    {modeInfo.mode === CODE.MODE_MODIFY &&
                                        <button className="btn btn_skyblue_h46 w_100"
                                        onClick={(e) => {
                                            onClickDeleteSchedule(location.state?.schdulId);
                                        }}>삭제</button> 
                                    }
                                    
                                </div>

                                <div className="right_col btn1">
                                    <Link to={URL.ADMIN__COMMITTEE__SCHEDULES} className="btn btn_blue_h46 w_100">목록</Link>
                                </div>
                            </div>
                            {/* <!--// 버튼영역 --> */}
                        </StyledDiv>
                        {/* <!-- 게시판 상세보기 --> */}

                        {/* <!--// 본문 --> */}
                    </div>
                </div>
            </div>
        </div >
    );
}

export default SchedulesEdit;