import React, {useCallback, useEffect, useState} from 'react';
import { default as EgovLeftNav } from 'components/leftmenu/EgovLeftNavAdmin';
import {Link} from "react-router-dom";
import URL from "constants/url";
import * as EgovNet from "api/egovFetch";
import Form from "react-bootstrap/Form";
import CODE from "../../../constants/code";


function MenuAuthMgt(props) {
    const [listTag, setListTag] = useState([]);
    const [roleHeader, setRoleHeader] = useState([]);

    const retrieveList = useCallback(() => {
        EgovNet.requestFetch(
            '/admin/config/menu-auth-mgt',
            {
                method: "GET"
            },
            (resp) => {
                const menuList = resp.result.menuList;
                const roleList = resp.result.roleList

                let mutListTag = [];
                let headerTag = [];

                setListTag([]);
                setRoleHeader([]);
                // 리스트 항목 구성
                menuList.forEach(function (item, index) {
                    const checkboxs = [];
                    roleList.forEach(function (role) {
                        checkboxs.push(
                            <div className={"checkboxDiv"}>
                                <Form.Check className={role.itemCd} value={role.itemCd}
                                            onClick={(e)=>{
                                                const checked = e.target.checked;
                                                if(checked) {
                                                    item.menuAuth += ","+role.itemCd
                                                }else{
                                                    item.menuAuth = item.menuAuth.replace(","+role.itemCd, '');
                                                }
                                            }}
                                            defaultChecked={item.menuAuth.includes(role.itemCd)}/>
                            </div>
                        )
                    });
                    mutListTag.push(
                        <div className={"list_item"} key={"userListDiv_"+index}>
                            <div>{item.menuId}</div>
                            <div>{item.menuTitle}</div>
                            <div>{item.menuGroup}</div>
                            {checkboxs}
                            <div className={"saveBtnDiv"}>
                                <button className={"btn btn_blue_h31 px-1"} onClick={()=>{editMenu(item)}}>저장</button>
                            </div>
                        </div>
                    );
                });
                if(!mutListTag.length) mutListTag.push(<p className="no_data" key="0">검색된 결과가 없습니다.</p>); // 게시판 목록 초기값

                roleList.forEach(function (item, index) {
                    headerTag.push(<span className={"checkboxDiv"}>{item.itemNm}</span>)
                });

                setListTag(mutListTag);
                setRoleHeader(headerTag)
            },
            function (resp) {
                console.log("err response : ", resp);
            }
        );
    },[]);

    function editMenu(menu){
        if(window.confirm("수정하시겠습니까?")) {
            EgovNet.requestFetch(
                '/admin/config/menu-auth-mgt',
                {
                    method: "PUT",
                    headers: {
                        'Content-type': 'application/json'
                    },
                    body: JSON.stringify(menu)
                },
                (resp) => {
                    if (Number(resp.resultCode) === Number(CODE.RCV_SUCCESS)) {
                        alert("수정되었습니다.")
                    } else if (Number(resp.resultCode) === Number(CODE.RCV_ERROR_AUTH)) {
                        console.log("토큰 갱신중.")
                    } else {
                        alert(resp.result.resultMessage)
                    }
                }
            )
        }
    }

    useEffect(()=>{
        retrieveList();
    }, [])

    return (
        <div className="container">
            <div className="c_wrap">
                <div className="location">
                    <ul>
                        <li><Link to={URL.MAIN} className="home">Home</Link></li>
                        <li>사이트관리</li>
                        <li>환경설정</li>
                        <li><Link to={URL.ADMIN_MENU_AUTH}>메뉴 권한 관리</Link></li>
                    </ul>
                </div>
                <div className="layout">
                    {/* <!-- Navigation --> */}
                    <EgovLeftNav/>
                    <div className="contents NOTICE_LIST" id="contents">
                        {/* <!-- 본문 --> */}

                        <div className="top_tit">
                            <h1 className="tit_1">메뉴 권한 관리</h1>
                        </div>
                        <h2 className="tit_2"></h2>

                        <div className="board_list roleList">
                            <div className="head">
                                <span>메뉴 코드</span>
                                <span>메뉴 이름</span>
                                <span>부모 메뉴</span>
                                {roleHeader}
                                <span className={"saveBtnDiv"}></span>
                            </div>
                            <div className="result">
                                {listTag}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}

export default MenuAuthMgt;