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

import EgovAttachFile from 'components/EgovAttachFile';
import RichTextEditor from "../../../../components/editor/RichTextEditor";
import AlertDialogSlide from "../../../../components/alert/AlertDialogSlide";
import CODE from 'constants/code';


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

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

import styled from "styled-components";

const StyledDiv = styled.div`

    .board_view2 {
        margin-bottom: 30px;
    }

    .label-text-editor {
        font-size: 19px;
        font-weight: 600;
        color: #212529;
        margin-bottom: 10px;
        .req {
            display: inline-block;
            width: 7px;
            height: 7px;
            margin-left: 2px;
            font-size: 0;
            background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMTM4IDc5LjE1OTgyNCwgMjAxNi8wOS8xNC0wMTowOTowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTcgKFdpbmRvd3MpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjdCNDNBMURDRjVFRDExRUJBMkM3OUEyMERCMzg3NTBGIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjdCNDNBMURERjVFRDExRUJBMkM3OUEyMERCMzg3NTBGIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6N0I0M0ExREFGNUVEMTFFQkEyQzc5QTIwREIzODc1MEYiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6N0I0M0ExREJGNUVEMTFFQkEyQzc5QTIwREIzODc1MEYiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz5vOlo3AAAAbElEQVR42mL4//8/Awy/zij/D8ShMD7Tm8wKQQYsACTOCFS5Csh2AeKzUPoeVP49E5BIB+JOIFaCCoJMWg3Erkwi0zveAxmzoIL3oPRZkDgTVHUHVMIEqrAcJMgClQQZywA1JR3omFAQHyDAAEctLdb1Cc0kAAAAAElFTkSuQmCC) no-repeat;
            vertical-align: 17px;
        }
    }

`;

function StandardResearchEditor(props) {
    
    const navigate = useNavigate();
    const location = useLocation();

    const [modeInfo, setModeInfo] = useState({ mode: props.mode });
    const [purpose, setPurpose] = useState("");
    const [purposeOriginal, setPurposeOriginal] = useState("");
    const [content, setContent] = useState("");
    const [contentOriginal, setContentOriginal] = useState("");
    const [effectContent, setEffectContent] = useState("");
    const [effectContentOriginal, setEffectContentOriginal] = useState("");



    const [standardResearchDetail, setStandardResearchDetail] = useState({ researchStartDate: new Date(), researchEndDate: new Date() });
    const [confirm, setConfirm] = React.useState();

    

    useEffect(function () {
        initMode();
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);
   
    const formValidator = (formData) => {
        if (formData.get('title') === null || formData.get('title') === "") {
            alert("연구명은 필수 값입니다.");
            return false;
        }
        
        if (formData.get('schdulBgnde') > formData.get('schdulEndde')) {
            alert("종료일시는 시작일시보다 앞 설 수 없습니다.");
            return false;
        }
        
        if (formData.get('director') === null || formData.get('director') === "") {
            alert("연구책임자는 필수 값입니다.");
            return false;
        }

        if (formData.get('purpose') === null || formData.get('purpose') === "") {
            alert("연구목적은 필수 값입니다.");
            return false;
        }

        if (formData.get('content') === null || formData.get('content') === "") {
            alert("연구내용은 필수 값입니다.");
            return false;
        }

        if (formData.get('effectContent') === null || formData.get('effectContent') === "") {
            alert("기대효과는 필수 값입니다.");
            return false;
        }
        return true;
    }

    const initMode = () => {

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

    const retrieveDetail = () => {  

        if (modeInfo.mode === CODE.MODE_CREATE) {// 조회/등록이면 조회 안함
            return;
        }

        const retrieveDetailURL = `/contents/standard-research/${location.state?.rsId}`;
        const requestOptions = {
            method: "GET",
            headers: {
                'Content-type': 'application/json'
            }
        }
        EgovNet.requestFetch(retrieveDetailURL,
            requestOptions,
            function (resp) {
                let rawDetail = resp.result;
                //기본값 설정
                setStandardResearchDetail({
                    ...standardResearchDetail,
                    ...rawDetail,
                    researchStartDate: convertDate(rawDetail.researchStartDate),
                    researchEndDate: convertDate(rawDetail.researchEndDate),
                });
                setPurpose(rawDetail.purpose);
                setPurposeOriginal(rawDetail.purpose);
                setContent(rawDetail.content);
                setContentOriginal(rawDetail.content);
                setEffectContent(rawDetail.effectContent);
                setEffectContentOriginal(rawDetail.effectContent);
            }
        );        
    }



    const createItem = () => {
        const formData = new FormData();
        
        for (let key in standardResearchDetail) {
            if ( key === 'researchStartDate' ) {
                formData.append(key, getDateFourteenDigit( standardResearchDetail[key] ));
            } else if( key === 'researchEndDate' ) {
                formData.append(key, getDateFourteenDigit( standardResearchDetail[key] ));
            } else {
                formData.append(key, standardResearchDetail[key]);
            }
        }
        
        //연구 목적
        formData.delete("purpose");
        formData.append("purpose", purpose); 
        
        //연구 내용
        formData.delete("content");
        formData.append("content", content); 

        //기대 효과
        formData.delete("effectContent");
        formData.append("effectContent", effectContent); 


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

            const requestTask = (callbackParams) => {
                EgovNet.requestFetch(callbackParams.requestUrl,
                    requestOptions,
                    (resp) => {
                        if (Number(resp.resultCode) === Number(CODE.RCV_SUCCESS)) {
                            if (modeInfo.mode === CODE.MODE_MODIFY) {
                                alert("게시글이 수정 되었습니다.");
                            }
                            navigate({ pathname: URL.ADMIN__CONTENTS__STANDARDS_RESEARCH });
                        } else {
                            navigate({pathname: URL.ERROR}, {state: {msg : resp.resultMessage}});
                        }
                    }
                );
            };

            
            if (modeInfo.mode === CODE.MODE_CREATE) {
                setConfirm({...confirm, open: true, body: "추가하시겠습니까?", yesCallback: requestTask, yesCallbackParams: {requestUrl:modeInfo.editURL}});
            } else if (modeInfo.mode === CODE.MODE_MODIFY) {
                setConfirm({...confirm, open: true, body: "수정하시겠습니까?", yesCallback: requestTask, yesCallbackParams: {requestUrl:`${modeInfo.editURL}/${location.state?.rsId}`}});
            }
            
        }

    }

    const onClickDelete = (rsId) => {
        const deleteBoardURL = `/contents/standard-research/${rsId}`;

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

        const requestTask = () => {
            EgovNet.requestFetch(deleteBoardURL,
                requestOptions,
                (resp) => {
                    if (Number(resp.resultCode) === Number(CODE.RCV_SUCCESS)) {
                        alert("삭제 되었습니다.");
                        navigate(URL.ADMIN__CONTENTS__STANDARDS_RESEARCH ,{ replace: true });
                    } else {
                        navigate({pathname: URL.ERROR}, {state: {msg : resp.resultMessage}});
                    }    
                }
            );
        };        

        setConfirm({...confirm, open: true, body: "삭제하시겠습니까?", yesCallback: requestTask});
    }

    const onClickList = (e) => {

        const requestTask = () => {       
            navigate(URL.ADMIN__CONTENTS__STANDARDS_RESEARCH ,{ replace: true });
        };

        if( purpose !== purposeOriginal ) {
            setConfirm({...confirm, open: true, body: "작업 내용을 취소하시겠습니까?", yesCallback: requestTask});
        } else if( content !== contentOriginal ) {
            setConfirm({...confirm, open: true, body: "작업 내용을 취소하시겠습니까?", yesCallback: requestTask});
        } else if( effectContent !== effectContentOriginal ) {
            setConfirm({...confirm, open: true, body: "작업 내용을 취소하시겠습니까?", yesCallback: requestTask});
        } else {
            requestTask();
        }
        
    }
    

    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 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 Location = React.memo(function Location() {
        return (
            <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>
        )
    });

    return (
        <div className="container">
            <div className="c_wrap">
                {/* <!-- Location --> */}
                <Location />
                {/* <!--// Location --> */}

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

                    <div className="contents " id="contents">
                        {/* <!-- 본문 --> */}
                        <StyledDiv>
                            <div className="top_tit">
                                <h1 className="tit_1">건설기준연구 추가</h1>
                            </div>                          
                            {/* <!-- 상단 입력 form --> */}
                            <div className='board_view2'>
                                <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={standardResearchDetail.title}
                                            onChange={(e) => setStandardResearchDetail({ ...standardResearchDetail, title: e.target.value })}
                                        />
                                    </dd>
                                </dl>
                                <dl>
                                    <dt>연구 기간<span className="req">필수</span></dt>
                                    <dd className="datetime">
                                        <span className="line_break">
                                            <DatePicker
                                                selected={standardResearchDetail.researchStartDate}
                                                name="researchStartDate"
                                                className="f_input"
                                                dateFormat="yyyy-MM-dd"
                                                onChange={(date) => {
                                                    console.log("setStartDate : ", date);
                                                    setStandardResearchDetail({ ...standardResearchDetail, schdulBgnde: getDateFourteenDigit(date), schdulBgndeYYYMMDD: getYYYYMMDD(date), researchStartDate: date });
                                                }} />
                                            <span className="f_inn_txt">~</span>
                                        </span>
                                        <span className="line_break">
                                            <DatePicker
                                                selected={standardResearchDetail.researchEndDate}
                                                name="researchEndDate"
                                                className="f_input"
                                                dateFormat="yyyy-MM-dd"
                                                minDate={standardResearchDetail.researchStartDate}
                                                onChange={(date) => {
                                                    console.log("setEndDate: ", date);
                                                    setStandardResearchDetail({ ...standardResearchDetail, schdulEndde: getDateFourteenDigit(date), schdulEnddeYYYMMDD: getYYYYMMDD(date), researchEndDate: date });
                                                }
                                                } />
                                        </span>
                                    </dd>
                                </dl>
                                <dl>
                                    <dt><label htmlFor="director">연구 책임자</label><span className="req">필수</span></dt>
                                    <dd>
                                        <input className="f_input2 w_full" type="text" name="director" title="연구 책임자" id="director" placeholder="연구 책임자를 입력하세요."
                                            value={standardResearchDetail.director}
                                            onChange={(e) => setStandardResearchDetail({ ...standardResearchDetail, director: e.target.value })}
                                        />
                                    </dd>
                                </dl>
                            </div>
                            {/* <!--// 상단 입력 form --> */}

                            {/* <!-- 게시판 --> */}
                            <label className="label-text-editor">연구 목적<span className="req">필수</span></label>
                            <RichTextEditor item={purpose} setText={setPurpose}/>

                            <label className="label-text-editor">연구 내용<span className="req">필수</span></label>
                            <RichTextEditor item={content} setText={setContent}/>

                            <label className="label-text-editor">기대 효과<span className="req">필수</span></label>
                            <RichTextEditor item={effectContent} setText={setEffectContent}/>
                            {/* <!--// 게시판 --> */}

                            {/* <!-- 버튼영역 --> */}
                            <div className="board_btn_area">
                                <div className="left_col btn1">
                                    <button className="btn btn_skyblue_h46 w_100"
                                        onClick={() => createItem()}
                                    > 저장</button>
                                    {modeInfo.mode === CODE.MODE_MODIFY &&
                                        <button className="btn btn_skyblue_h46 w_100"
                                        onClick={(e) => {
                                            onClickDelete(location.state?.rsId);
                                        }}>삭제</button> 
                                    }                                    
                                </div>
                                <div className="right_col btn1">
                                    <button className="btn btn_blue_h46 w_100"
                                        onClick={onClickList}>목록</button> 
                                </div>
                            </div>
                            {/* <!--// 버튼영역 --> */}

                            <AlertDialogSlide confirm={confirm} setConfirm={setConfirm} />
                        </StyledDiv>                        
                        {/* <!--// 본문 --> */}
                    </div>
                </div>
            </div>
        </div>
    );
}


export default StandardResearchEditor;