import React, {useState, useEffect, useRef} from 'react';
import {Link, useNavigate, useLocation, useParams} from 'react-router-dom';
import Modal from "react-bootstrap/Modal";

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 EgovRadioButtonGroup from 'components/EgovRadioButtonGroup';


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

    const navigate = useNavigate();
    const location = useLocation();
    const checkRef = useRef([]);

    console.log("EgovAdminBoardEdit [location] : ", location);

    const replyPosblAtRadioGroup = [{value: "Y", label: "가능"}, {value: "N", label: "불가능"}];
    const fileAtchPosblAtRadioGroup = [{value: "Y", label: "가능"}, {value: "N", label: "불가능"}];
    const bbsTyCodeOptions = [{value: "", label: "선택"}, {value: "BBST01", label: "일반게시판"}, {value: "BBST03", label: "공지게시판"}];
    const bbsAttrbCodeOptions = [{value: "", label: "선택"}, {value: "BBSA02", label: "갤러리"}, {value: "BBSA03", label: "일반게시판"}];
    const posblAtchFileNumberOptions = [{value: 0, label: "선택하세요"}, {value: 1, label: "1개"}, {value: 2, label: "2개"}, {value: 3, label: "3개"}];

    let item = null;
    item = props.props;
    console.log("@@@ item : " + JSON.stringify(item));



    const [modeInfo, setModeInfo] = useState(item != null ? {mode: props.props.mode} : {mode: CODE.MODE_CREATE});
    const [boardDetail, setBoardDetail] = useState({});
    console.log("@@@ mode : " + modeInfo.mode);

    const initMode = () => {
        retrieveDetail();
    }

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


        const retrieveDetailURL = '/admin/boards/board';

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

            }
        }

        EgovNet.requestFetch(retrieveDetailURL,
            requestOptions,
            function (resp) {
                // 수정모드일 경우 조회값 세팅
                if (modeInfo.mode === CODE.MODE_MODIFY) {
                    setBoardDetail(item);
                }
            }
        );
    }

    const formValidator = (formData) => {
        if (formData.get('bbsTitle') === null || formData.get('bbsTitle') === "") {
            alert("게시판명은 필수 값입니다.");
            return false;
        }
        if (formData.get('bbsDesc') === null || formData.get('bbsDesc') === "") {
            alert("게시판 소개는 필수 값입니다.");
            return false;
        }
        if (formData.get('bbsTyCode') === null || formData.get('bbsTyCode') === "") {
            alert("게시판 유형은 필수 값입니다.");
            return false;
        }
        if (formData.get('bbsAttrbCode') === null || formData.get('bbsAttrbCode') === "") {
            alert("게시판 속성은 필수 값입니다.");
            return false;
        }
        if (formData.get('posblAtchFileNumber') === null || formData.get('posblAtchFileNumber') === "") {
            alert("첨부파일 가능 숫자는 필수 값입니다.");
            return false;
        }
        return true;
    };

    const formObjValidator = (checkRef) => {
        if (checkRef.current[0].value === "") {
            alert("게시판명은 필수 값입니다.");
            return false;
        }
        if (checkRef.current[1].value === "") {
            alert("게시판 소개는 필수 값입니다.");
            return false;
        }
        if (checkRef.current[2].value === "0") {
            alert("첨부파일 가능 숫자는 필수 값입니다.");
            return false;
        }
        return true;
    };

    const updateBoard = () => {

        let modeStr = modeInfo.mode === CODE.MODE_CREATE ? "POST" : "PUT";

        let requestOptions = {};

        if (modeStr === "POST") {

            const formData = new FormData();

            for (let key in boardDetail) {
                formData.append(key, boardDetail[key]);
                //console.log("boardDetail [%s] ", key, boardDetail[key]);
            }

            if (formValidator(formData)) {

                requestOptions = {
                    method: modeStr,
                    headers: {},
                    body: formData
                }

                EgovNet.requestFetch(modeInfo.editURL,
                    requestOptions,
                    (resp) => {
                        if (Number(resp.resultCode) === Number(CODE.RCV_SUCCESS)) {
                            navigate({pathname: URL.ADMIN_BOARD});
                        } else {
                            navigate({pathname: URL.ERROR}, {state: {msg: resp.resultMessage}});
                        }
                    }
                );
            }
            ;

        } else {
            if (formObjValidator(checkRef)) {

                requestOptions = {
                    method: modeStr,
                    headers: {
                        'Content-type': 'application/json',

                    },
                    body: JSON.stringify({...boardDetail})
                }

                EgovNet.requestFetch(modeInfo.editURL,
                    requestOptions,
                    (resp) => {
                        if (Number(resp.resultCode) === Number(CODE.RCV_SUCCESS)) {
                            navigate({pathname: URL.ADMIN_BOARD});
                        } else {
                            navigate({pathname: URL.ERROR}, {state: {msg: resp.resultMessage}});
                        }
                    }
                );
            }
        }
    };

    const deleteBoardArticle = (bbsId) => {
        const deleteBoardURL = `/cop/bbs/deleteBBSMasterInfAPI/${bbsId}.do`;

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

            },
            body: JSON.stringify({
                bbsId: bbsId
            })
        }

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

    const getSelectedLabel = (objArray, findLabel = "") => {
        let foundValueLabelObj = objArray.find(o => o['value'] === findLabel);
        return foundValueLabelObj['label'];
    }

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

    console.log("------------------------------EgovAdminBoardEdit [End]");
    console.groupEnd("EgovAdminBoardEdit");

    return (
        <>
            {/* <!-- 본문 --> */}
            <Modal.Header>
                <Modal.Title>
                    {modeInfo.mode === CODE.MODE_CREATE && '게시판 생성'}
                    {modeInfo.mode === CODE.MODE_MODIFY && '게시판 수정'}
                </Modal.Title>
            </Modal.Header>

            <Modal.Body>
                <div className="board_view2">
                    <dl>
                        <dt><label htmlFor="bbsId">게시판ID</label><span className="req">필수</span></dt>
                        <dd>
                            <input className="f_input2 w_full" type="text" name="bbsId" title="" id="bbsId" placeholder=""
                                   defaultValue={boardDetail?.bbsId}
                                   onChange={e => setBoardDetail({...boardDetail, bbsId: e.target.value})}
                                   ref={el => (checkRef.current[0] = el)}
                            />
                        </dd>
                    </dl>
                    <dl>
                        <dt><label htmlFor="bbsTitle">게시판명</label><span className="req">필수</span></dt>
                        <dd>
                            <input className="f_input2 w_full" type="text" name="bbsTitle" title="" id="bbsTitle" placeholder=""
                                   defaultValue={boardDetail?.bbsTitle}
                                   onChange={e => setBoardDetail({...boardDetail, bbsTitle: e.target.value})}
                                   ref={el => (checkRef.current[0] = el)}
                            />
                        </dd>
                    </dl>
                    <dl>
                        <dt><label htmlFor="bbsDesc">게시판 소개</label><span className="req">필수</span></dt>
                        <dd>
                                    <textarea className="f_txtar w_full h_100" name="bbsDesc" id="bbsDesc" cols="30" rows="10" placeholder=""
                                              defaultValue={boardDetail?.bbsDesc}
                                              onChange={e => setBoardDetail({...boardDetail, bbsDesc: e.target.value})}
                                              ref={el => (checkRef.current[1] = el)}
                                    ></textarea>
                        </dd>
                    </dl>

                    {/* <!-- 버튼영역 --> */}
                    <div className="board_btn_area">
                        <div className="left_col btn1">
                            <button className="btn btn_skyblue_h46 w_100"
                                    onClick={() => updateBoard()}>저장
                            </button>
                            {modeInfo.mode === CODE.MODE_MODIFY &&
                            <button className="btn btn_skyblue_h46 w_100" onClick={() => {
                                deleteBoardArticle(boardDetail?.bbsId);
                            }}>삭제</button>
                            }
                        </div>

                        <div className="right_col btn1">
                            <Link to={URL.ADMIN_BOARD} className="btn btn_blue_h46 w_100">목록</Link>
                        </div>
                    </div>
                    {/* <!--// 버튼영역 --> */}
                </div>
            </Modal.Body>
        </>

    );
}

export default EgovAdminBoardEdit;