import React, { useState, useEffect } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import DatePicker from "react-datepicker";
import AttachFile from "components/file/AttachFile";
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 ReferenceCodePopupInput from './ReferenceCodePopupInput';


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`
    .f_select.w_250 {
        @media only screen and (max-width: 768px) {
            width: 100%;
        }
    }

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

    .org-group-id-1 {
        margin: 0px 29px;
        @media only screen and (max-width: 768px) {    
            margin: 0px;
        }
    }
`;


function ProgressStatusEdit(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 [requestItems, setRequestItems] = useState
        (
            {
                orgGroupId: 1,
                startDate: new Date(),         
                eventId : 0,
            }
        );

    const [drftDatetimeHH, setDrftDatetimeHH] = useState();
    const [drftDatetimeMM, setDrftDatetimeMM] = useState();

    const [scheduleInit, setScheduleInit] = 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 : ""}});
        }
        
        getList(orgSearchCondition);
    }

    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 [orgSearchCondition, setOrgSearchCondition] = useState({ paramCodeGroup: null, paramCodeLevel: 'LV_01' });
    const [orgArray, setOrgArray] = useState([]);
    const [orgSelectedIndex, setOrgSelectedIndex] = useState([]);




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





    useEffect(function () {
        if ( typeof orgArray[0] === 'undefined' || typeof orgSelectedIndex[0] === 'undefined' ) {
            return;
        }

        if( orgSelectedIndex[0] === 0) {
            orgArray[1] = undefined;
            orgArray[2] = undefined;
            let forChangeObject = [...orgArray];
            setOrgArray(forChangeObject);
            setOrgSelectedIndex([orgSelectedIndex[0], undefined, undefined]);
            return;
        }

        if ( typeof orgArray[0][orgSelectedIndex[0]-1] === 'undefined' ) {
            return;
        }

        const paramCodeLevel = 'LV_02';
        const paramCodeGroup = orgArray[0][orgSelectedIndex[0]-1].orgId;
        setOrgSearchCondition({ paramCodeGroup, paramCodeLevel });
        orgArray[1] = undefined;
        orgArray[2] = undefined;
        let forChangeObject = [...orgArray];
        setOrgArray(forChangeObject);
        setOrgSelectedIndex([orgSelectedIndex[0], undefined, undefined]);
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [orgSelectedIndex[0]]);




    useEffect(function () {
        if ( typeof orgArray[1] === 'undefined' || typeof orgSelectedIndex[1] === 'undefined' ) {
            return;
        }

        if( orgSelectedIndex[1] === 0) {
            orgArray[2] = undefined;
            let forChangeObject = [...orgArray];
            setOrgArray(forChangeObject);
            setOrgSelectedIndex([orgSelectedIndex[0], orgSelectedIndex[1], undefined]);
            return;
        }

        if ( typeof orgArray[0][orgSelectedIndex[1]-1] === 'undefined' ) {
            return;
        }

        const paramCodeLevel = 'LV_03';
        const paramCodeGroup = orgArray[1][orgSelectedIndex[1]-1].orgId;
        setOrgSearchCondition({ paramCodeGroup, paramCodeLevel });

        orgArray[2] = undefined;   
        let forChangeObject = [...orgArray];
        setOrgArray(forChangeObject);
        setOrgSelectedIndex([orgSelectedIndex[0], orgSelectedIndex[1], undefined]);
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [orgSelectedIndex[1]]);




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

    

    const getList = (orgSearchCondition) => {  
        
        EgovNet.requestFetch(`/admin/config/committee-code-management?paramCodeGroup=${orgSearchCondition.paramCodeGroup}&paramCodeLevel=${orgSearchCondition.paramCodeLevel}`,
            requestOptions,
            function (resp) {
                const myIndex = Number(String(orgSearchCondition.paramCodeLevel).replace('LV_','')) - 1;
                const forCopy = [...orgArray];
                forCopy[myIndex] = resp.result.list;
                setOrgArray(forCopy);
            }
        );        
    }


    const updateSchedule = () => {
        const formData = new FormData();
        
        for (let key in requestItems) {
            if ( key === 'startDate' ) {
                formData.append(key, getDateFourteenDigit( requestItems[key] ));
            } else if( key === 'endDate' ) {
                formData.append(key, getDateFourteenDigit( requestItems[key] ));
            } else {
                formData.append(key, requestItems[key]);
            }
            
            console.log("requestItems [%s] ", key, requestItems[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]", requestItems);
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [requestItems]);
    
    const fileTypes = ["JPG", "PNG", "GIF", "PDF", "HWP", "HWPX", "ZIP", "JPEG", "MP4", "TXT"];
    //사전검토자료
    const [preDataFile, setPreDataFile] = useState(null);
    const [preDataFileName, setPreDataFileName] = useState(null);
    //사전검토양식
    const [preFormFile, setPreFormFile] = useState(null);
    const [preFormFileName, setPreFormFileName] = useState(null);
    //관계기관의견
    const [partnerFile, setPartnerFile] = useState(null);
    const [partnerFileName, setPartnerFileName] = useState(null);
    //조치계획서
    const [actionPlanFile, setActionPlanFile] = useState(null);
    const [actionPlanFileName, setActionPlanFileName] = useState(null);
    //조치결과서
    const [actionResultReportFile, setActionResultReportFile] = useState(null);
    const [actionResultReportFileName, setActionResultReportFileName] = useState(null);



    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>

                        {/* <!-- 게시판 상세보기 --> */}
                        <StyledDiv className="board_view2">
                            <dl>
                                <dt><label>안건</label><span className="req">필수</span></dt>
                                <dd>
                                    <input className="f_input2 w_full" type="text" name="title" title="안건" placeholder="안건을 입력하세요"
                                        value={requestItems.title}
                                        onChange={(e) => setRequestItems({ ...requestItems, title: e.target.value })}
                                    />
                                </dd>
                            </dl>
                            <dl>
                                <dt><label>기준코드</label><span className="req">필수</span></dt>
                                <dd>
                                    <ReferenceCodePopupInput
                                        requestItems={requestItems}
                                        setRequestItems={setRequestItems}
                                    />
                                </dd>
                            </dl>
                            <dl>
                                <dt><label>구분</label><span className="req">필수</span></dt>
                                <dd>
                                    <label className="f_select w_150" >
                                        <select name="div-meet" title="재정 개정 재개정 선택"
                                            value={requestItems.drftTypeCode}
                                            onChange={(e) => setRequestItems({ ...requestItems, drftTypeCode: 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><label>회의일자</label><span className="req">필수</span></dt>
                                <dd className="datetime">
                                    <span className="line_break">
                                        <DatePicker
                                            selected={requestItems.drftDatetime}
                                            name="drftDatetime"
                                            className="f_input"
                                            dateFormat="yyyy-MM-dd"
                                            onChange={(date) => {
                                                setRequestItems({ ...requestItems, schdulBgnde: getDateFourteenDigit(date), drftDatetimeYYYMMDD: getYYYYMMDD(date), drftDatetime: date });
                                                setDrftDatetimeHH(date.getHours());
                                                setDrftDatetimeMM(date.getMinutes());
                                            }} />
                                        <input type="hidden" name="drftDatetimeMM" defaultValue={drftDatetimeMM} readOnly />
                                    </span>
                                </dd>
                            </dl>
                            <dl>
                                <dt><label>위원회</label><span className="req">필수</span></dt>
                                <dd>
                                    {/** top org */}
                                    <label className="f_select w_250 org-group-id" htmlFor="org-group-id">
                                        <select id="org-group-id" name="orgGroupId" title="중앙건설기술심의 선택"
                                            value={requestItems.orgGroupId}
                                            onChange={(e) => {
                                                setRequestItems({ ...requestItems, orgGroupId: e.target.value });
                                                orgSelectedIndex[0] = e.target.options.selectedIndex;    
                                                let forChangeObject = [...orgSelectedIndex];
                                                setOrgSelectedIndex(forChangeObject);
                                            }}>
                                                <option value="">중앙건설기술심의 선택</option>
                                            {orgArray && orgArray[0] && orgArray[0].map && orgArray[0].map((item, index) => (
                                                <option key={item.orgId} value={item.orgId} data-index={index}>{item.orgNm}</option>
                                            ))}
                                        </select>
                                    </label>
                                    <label className="f_select w_250 org-group-id-1" htmlFor="org-group-id-1">
                                        <select id="org-group-id-1" name="orgGroupId1" title="총괄건설기준위원회 선택"
                                            value={requestItems.orgGroupId1}
                                            defaultValue='1'
                                            onChange={(e) => {
                                                setRequestItems({ ...requestItems, orgGroupId1: e.target.value });
                                                orgSelectedIndex[1] = e.target.options.selectedIndex;
                                                let forChangeObject = [...orgSelectedIndex];
                                                setOrgSelectedIndex(forChangeObject);
                                            }}>
                                            <option value="">총괄건설기준위원회 선택</option>
                                            {orgArray && orgArray[1] && orgArray[1].map((item, index) => (
                                                <option key={item.orgId} value={item.orgId} data-index={index}>{item.orgNm}</option>
                                            ))}
                                        </select>
                                    </label>
                                    <label className="f_select w_250 org-group-id-2" htmlFor="org-group-id-2">
                                        <select id="org-group-id-2" name="orgGroupId2" title="기준위원회 선택"
                                            value={requestItems.orgGroupId2}
                                            onChange={(e) => {
                                                setRequestItems({ ...requestItems, orgGroupId2: e.target.value });
                                                orgSelectedIndex[2] = e.target.options.selectedIndex;    
                                                let forChangeObject = [...orgSelectedIndex];
                                                setOrgSelectedIndex(forChangeObject);
                                            }}>
                                            <option value="">기준위원회 선택</option>
                                            {orgArray && orgArray[2] && orgArray[2].map((item, index) => (
                                                <option key={item.orgId} value={item.orgId} data-index={index}>{item.orgNm}</option>
                                            ))}
                                        </select>
                                    </label>
                                </dd>
                            </dl>
                            <dl>
                                <dt><label htmlFor="title">사전검토자료</label><span className="req">필수</span></dt>
                                <dd>
                                    <AttachFile name="preDataFile" file={preDataFile} setFile={setPreDataFile} fileName={preDataFileName} fileTypes={fileTypes}  />
                                </dd>     
                            </dl>
                            <dl>
                                <dt><label htmlFor="title">사전검토양식</label><span className="req">필수</span></dt>
                                <dd>
                                    <AttachFile name="preFormFile" file={preFormFile} setFile={setPreFormFile} fileName={preFormFileName} fileTypes={fileTypes}  />
                                </dd>
                            </dl>
                            <dl>
                                <dt><label htmlFor="title">관계기관의견</label><span className="req">필수</span></dt>
                                <dd>
                                    <AttachFile name="partnerFile" file={partnerFile} setFile={setPartnerFile} fileName={partnerFileName} fileTypes={fileTypes}  />
                                </dd>
                            </dl>
                            <dl>
                                <dt><label htmlFor="title">조치계획서</label><span className="req">필수</span></dt>
                                <dd>
                                    <AttachFile name="actionPlanFile" file={actionPlanFile} setFile={setActionPlanFile} fileName={actionPlanFileName} fileTypes={fileTypes}  />
                                </dd>
                            </dl>
                            <dl>
                                <dt><label>조치결과서</label><span className="req">필수</span></dt>
                                <dd>
                                    <AttachFile name="actionResultReportFile" file={actionResultReportFile} setFile={setActionResultReportFile} fileName={actionResultReportFileName} fileTypes={fileTypes}  />
                                </dd>
                            </dl>
                            <dl>
                                <dt><label>회의담당자</label><span className="req">필수</span></dt>
                                <dd>
                                    <input className="f_input2 w_full" type="text" name="drftConfeCharger" title="회의 담당자" placeholder="여기를 눌러 회의담당자를 선택하세요"
                                        value={requestItems.drftConfeCharger}
                                        onChange={(e) => setRequestItems({ ...requestItems, drftConfeCharger: e.target.value })}
                                    />
                                </dd>
                            </dl>
                            <dl>
                                <dt><label>회의실 비밀번호</label><span className="req">필수</span></dt>
                                <dd>
                                    <input className="f_input2 w_full" type="text" name="drftConfePw" title="제목" placeholder="회의실 비밀번호를 입력하세요"
                                        value={requestItems.drftConfePw}
                                        onChange={(e) => setRequestItems({ ...requestItems, drftConfePw: e.target.value })}
                                    />
                                </dd>
                            </dl>
                            <dl>
                                <dt><label>회의 안건</label><span className="req">필수</span></dt>
                                <dd>
                                    <textarea className="f_txtar w_full h_100" name="drftSummery" cols="30" rows="10" placeholder="회의 안건 내용을 입력하세요."
                                        defaultValue={requestItems.drftSummery}
                                        onChange={(e) => setRequestItems({ ...requestItems, drftSummery: 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>            
                                    
                                </div>

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

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

export default ProgressStatusEdit;