import React, {useEffect, useState} from "react";
import {SbContainer} from "./Sb.style";
import SbItem from "./SbItem";
import * as EgovNet from "api/egovFetch";


function ViewerTree({docCode, updateDocCode, setTreeLoading}){
    const [tree, setTree] = useState([]);
    function getCodeTree(){
        EgovNet.requestFetch(
            '/standardCode/code-tree',
            {
                method: "GET",
                headers: {
                    'Content-type': 'application/json'
                }
            },
            (resp) => {
                const menuData = resp.result.codeTree;
                // 코드 목록 트리 구성
                // https://garve32.tistory.com/52 참고
                const nest = (menuData, parent_seq = null, link = 'parent_seq') =>
                    menuData.filter(item => item[link] === parent_seq)
                        .map(item => ({ ...item, childrens: nest(menuData, item.seq) }));
                setTree(nest(menuData));
                setTreeLoading(false);
            },
            function (resp) {
                console.log("err response : ", resp);
            }
        );
    }

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

    return (
        <SbContainer>
            {tree.map((subItem) =>
                <SbItem item={subItem} openDocCode={docCode} updateDocCode={updateDocCode} />
            )}
        </SbContainer>
    );
}

export default ViewerTree;