import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import Box from '@mui/material/Box';

import * as EgovNet from 'api/egovFetch';

import CommitteeCodeRegistrationPopup from './CommitteeCodeMgt/CommitteeCodeRegistrationPopup';
import ListCreateUpdateDelete from '../../../components/list/ListCreateUpdateDelete'
import ListLabelInputs from '../../../components/list/ListLabelInputs'

import AlertDialogSlide from "../../../components/alert/AlertDialogSlide";

import URL from 'constants/url';

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


function CommitteeCodeMgt(props) {

    const [searchCondition, setSearchCondition] = useState({ paramCodeGroup: null, paramCodeLevel: 'LV_01' });
    const [createOrModifyCondition, setCreateOrModifyCondition] = useState();

    const [depth01List, setDepth01List] = useState({});
    const [depth02List, setDepth02List] = useState({});
    const [depth03List, setDepth03List] = useState({});
    const [depth04List, setDepth04List] = useState({});

    const [summaryArray, setSummaryArray] = useState({});
    const [depthSelectedIndex, setDepthSelectedIndex] = useState([]);

    const [confirm, setConfirm] = React.useState();

    

    
    // 위원회 코드 등록 팝업을 보이거나 닫는다.
    const [isCommitteeCodeRegistrationPopupOpen, setIsCommitteeCodeRegistrationPopupOpen] = React.useState(false);


    // '중앙건설기술심의'에서 특정 item선택 시, 하위 '총괄위원회'목록을 불러온다.
    useEffect(function () {
        if( typeof depthSelectedIndex[0] !== "undefined" && depth01List[depthSelectedIndex[0]] && depth01List[depthSelectedIndex[0]].orgId !== undefined) {
            setSearchCondition({ paramCodeGroup: depth01List[depthSelectedIndex[0]].orgId, paramCodeLevel: 'LV_02' });
            setDepth02List({});
            setDepth03List({});
            setDepth04List({});
            depthSelectedIndex[1] = undefined;
            depthSelectedIndex[2] = undefined;
            depthSelectedIndex[3] = undefined;            
            let forChangeObject = [...depthSelectedIndex];
            setDepthSelectedIndex(forChangeObject);
        }
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [depthSelectedIndex[0]]);


    // '총괄위원회'에서 특정 item선택 시, 하위 '건설기준위원회'목록을 불러온다.
    useEffect(function () {
        if( typeof depthSelectedIndex[1] !== 'undefined' ) {
            setSearchCondition({ paramCodeGroup: depth02List[depthSelectedIndex[1]].orgId, paramCodeLevel: 'LV_03' });
            setDepth03List({});
            setDepth04List({});
            depthSelectedIndex[2] = undefined;
            depthSelectedIndex[3] = undefined;
            let forChangeObject = [...depthSelectedIndex];
            setDepthSelectedIndex(forChangeObject);
        } 
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [depthSelectedIndex[1]]);

    // '건설기준위원회'에서 특정 item선택 시, 하위 '실무위원회'목록을 불러온다.
    useEffect(function () {
        if( typeof depthSelectedIndex[2] !== 'undefined' ) {
            setSearchCondition({ paramCodeGroup: depth03List[depthSelectedIndex[2]].orgId, paramCodeLevel: 'LV_04' });
            setDepth04List({});
            depthSelectedIndex[3] = undefined;
            let forChangeObject = [...depthSelectedIndex];
            setDepthSelectedIndex(forChangeObject);
        }
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [depthSelectedIndex[2]]);


    // 검색 조건이 변경되면 데이터를 불러온다.
    useEffect(function () {
        if( typeof searchCondition !== 'undefined' ) {
            getList(searchCondition);
        }
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [searchCondition]);
    
   

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

    const arrayToJson = (myArray, key) => {
        let tempObj = {};

        // eslint-disable-next-line array-callback-return
        myArray.map((value, index) => {
            tempObj = {...tempObj, [value[key]] : value};
        });

        return tempObj;
    };

    const getList = (searchCondition) => {  
        
        EgovNet.requestFetch(`/admin/config/committee-code-management?paramCodeGroup=${searchCondition.paramCodeGroup}&paramCodeLevel=${searchCondition.paramCodeLevel}`,
            requestOptions,
            function (resp) {
                if( searchCondition.paramCodeLevel === 'LV_01' ) {
                    setDepth01List(arrayToJson(resp.result.list, "orgId"));
                } else if( searchCondition.paramCodeLevel === 'LV_02' ) {
                    setDepth02List(arrayToJson(resp.result.list, "orgId"));
                } else if( searchCondition.paramCodeLevel === 'LV_03' ) {
                    setDepth03List(arrayToJson(resp.result.list, "orgId"));
                } else if( searchCondition.paramCodeLevel === 'LV_04' ) {   
                    setDepth04List(arrayToJson(resp.result.list, "orgId"));
                }
            }
        );        
    }


    useEffect(function () {
        setSummaryArray(
            {
                "중앙건설기술심의" : depth01List[depthSelectedIndex[0]] && depth01List[depthSelectedIndex[0]].orgNm ? depth01List[depthSelectedIndex[0]].orgNm : "", 
                "총괄위원회" : depth02List[depthSelectedIndex[1]] && depth02List[depthSelectedIndex[1]].orgNm ? depth02List[depthSelectedIndex[1]].orgNm : "", 
                "건설기준위원회" : depth03List[depthSelectedIndex[2]] && depth03List[depthSelectedIndex[2]].orgNm ? depth03List[depthSelectedIndex[2]].orgNm : "", 
                "실무위원회" : depth04List[depthSelectedIndex[3]] && depth04List[depthSelectedIndex[3]].orgNm ? depth04List[depthSelectedIndex[3]].orgNm : "", 
            }
        );        
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [
        depth01List, 
        depth02List,
        depth03List, 
        depth04List, 
        depthSelectedIndex
    ]);


    const onClickDeleteItem = (e, paramCodeGroup, paramCodeLevel, depthSelectedArrayIndex, deleteItem) => {  
        
        if( deleteItem.orgId === undefined ) {
            alert('삭제 대상이 존재하지 않습니다.');
            return false;
        }

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

        const requestTask = () => {       
            EgovNet.requestFetch(`/admin/config/committee-code-management/${deleteItem.orgId}`,
                requestOptions,
                function (resp) {
                    let forChangeObject = {...searchCondition, paramCodeGroup, paramCodeLevel};
                    setSearchCondition(forChangeObject);

                    //현재 선택된 아이템을 삭제한 경우 그 하위 목록을 모두 비운다.
                    if( Number(depthSelectedIndex[depthSelectedArrayIndex]) === Number(deleteItem.orgId) ) {                 

                        for( let i = depthSelectedArrayIndex + 1; i<4; i++ ) {
                            //setSearchCondition({...searchCondition, paramCodeLevel : createOrModifyCondition.paramCodeLevel});
                            depthSelectedIndex[i] = undefined;
                        }
                        let forChangeObject = [...depthSelectedIndex];
                        setDepthSelectedIndex(forChangeObject);
                        
                        // eslint-disable-next-line default-case
                        switch(depthSelectedArrayIndex) {
                            case 0:
                                setDepth02List({});                            
                            // eslint-disable-next-line no-fallthrough
                            case 1:
                                setDepth03List({});
                            // eslint-disable-next-line no-fallthrough
                            case 2:
                                setDepth04List({});
                        }
                    }

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

    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">
                        {/* <!-- 본문 --> */}

                        <div className="top_tit">
                            <h1 className="tit_1">위원회 코드 관리</h1>
                        </div>

                        <Box
                            sx={{
                                display: 'flex',
                                flexWrap: 'wrap',
                                justifyContent: 'space-between',
                                '& > :not(style)': {
                                mt: 0,
                                width: 245,
                                },
                            }}
                        >

                            <ListCreateUpdateDelete
                                title="중앙건설기술심의"
                                items={depth01List}
                                itemIndex={depthSelectedIndex}
                                setItemIndex={setDepthSelectedIndex}
                                depthSelectedArrayIndex={0}
                                createOrModifyCondition={createOrModifyCondition}
                                setCreateOrModifyCondition={setCreateOrModifyCondition}
                                paramCodeLevel="LV_01"
                                upParamOrgId="00"
                                nameKey="orgNm"
                                idKey="orgId"
                                isPopupOpen = {isCommitteeCodeRegistrationPopupOpen}
                                setIsPopupOpen = {setIsCommitteeCodeRegistrationPopupOpen}
                                onClickDeleteItem={onClickDeleteItem}
                            />
                            <ListCreateUpdateDelete
                                title="총괄위원회"
                                items={depth02List}
                                itemIndex={depthSelectedIndex}
                                setItemIndex={setDepthSelectedIndex}
                                depthSelectedArrayIndex={1}
                                createOrModifyCondition={createOrModifyCondition}
                                setCreateOrModifyCondition={setCreateOrModifyCondition}
                                searchCondition={searchCondition}
                                setSearchCondition={setSearchCondition}
                                paramCodeLevel="LV_02"
                                nameKey="orgNm"
                                idKey="orgId"
                                isPopupOpen = {isCommitteeCodeRegistrationPopupOpen}
                                setIsPopupOpen = {setIsCommitteeCodeRegistrationPopupOpen}
                                onClickDeleteItem={onClickDeleteItem}
                            />
                            <ListCreateUpdateDelete
                                title="건설기준위원회"
                                items={depth03List}
                                itemIndex={depthSelectedIndex}
                                setItemIndex={setDepthSelectedIndex}
                                depthSelectedArrayIndex={2}
                                createOrModifyCondition={createOrModifyCondition}
                                setCreateOrModifyCondition={setCreateOrModifyCondition}
                                searchCondition={searchCondition}
                                setSearchCondition={setSearchCondition}
                                paramCodeLevel="LV_03"
                                nameKey="orgNm"
                                idKey="orgId"
                                isPopupOpen = {isCommitteeCodeRegistrationPopupOpen}
                                setIsPopupOpen = {setIsCommitteeCodeRegistrationPopupOpen}
                                onClickDeleteItem={onClickDeleteItem}
                            />
                            <ListCreateUpdateDelete
                                title="실무위원회"
                                items={depth04List}
                                itemIndex={depthSelectedIndex}
                                setItemIndex={setDepthSelectedIndex}
                                depthSelectedArrayIndex={3}
                                createOrModifyCondition={createOrModifyCondition}
                                setCreateOrModifyCondition={setCreateOrModifyCondition}
                                searchCondition={searchCondition}
                                setSearchCondition={setSearchCondition}
                                paramCodeLevel="LV_04"
                                nameKey="orgNm"
                                idKey="orgId"
                                isPopupOpen = {isCommitteeCodeRegistrationPopupOpen}
                                setIsPopupOpen = {setIsCommitteeCodeRegistrationPopupOpen}
                                onClickDeleteItem={onClickDeleteItem}
                            />
                            
                        </Box>
                        { false &&
                            <Box
                                sx={{
                                    display: 'flex',
                                    flexWrap: 'wrap',
                                    '& > :not(style)': {
                                        mt: 4,
                                        width: 245,
                                    },
                                }}
                            >
                                <ListLabelInputs title="위원회 코드정보" items={summaryArray} />
                            </Box>
                        }
                      
                        <CommitteeCodeRegistrationPopup
                            open={isCommitteeCodeRegistrationPopupOpen}
                            setOpen={setIsCommitteeCodeRegistrationPopupOpen}
                            createOrModifyCondition={createOrModifyCondition}
                            searchCondition={searchCondition}
                            setSearchCondition={setSearchCondition}
                        />

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

export default CommitteeCodeMgt;