import * as EgovNet from "../../api/egovFetch";
import React, {useEffect, useState} from "react";
import SbItem from "./SbItem";
import {Col, Row} from "react-bootstrap";
import {VwDiv, VwPtag} from "./Vw.style";

/*최상위 컴포넌트*/
export function Maincontent({docCode}) {
    const [doccode, setdoccode] = useState('');
    const [docname, setdocname] = useState('');
//TODO 맨처음 목차코드 및 목차제목 안나오는 문제 수정 
    function setdoccodandname(doccode, docname) {
        setdoccode(doccode);
        setdocname(docname);
    }


    return (
        <div>
            <Col>{doccode+' '+docname}</Col>
            <Row>
            <CodeTree docCode={docCode} setdoccodandname={setdoccodandname}/>
            <CodeCotentData docCode={docCode}/>
            </Row>
        </div>)
}

/*글 트리 컴포넌트*/
export function CodeTree({docCode, setdoccodandname}) {
    const [codeTree, setcodeTree] = useState([]);
    const [doccode, setdoccode] = useState(docCode);
    let data = [];
    const getCodeTree = () => {
        EgovNet.requestFetch(
            '/standardCode/getCodeTree.do',
            {
                method: "POST",
                headers: {
                    'Content-type': 'application/json'
                },
                body: JSON.stringify({})
            }, (item) => {
                data = item.result.codeTree;
                const nest = (menuData, parent_seq = null, link = 'parent_seq') =>
                    menuData.filter(item => item[link] === parent_seq)
                        .map(item => ({...item, childrens: nest(menuData, item.seq)}));
                setcodeTree(nest(data));
            }, () => {
            })
    }
    useEffect(() => {
        getCodeTree()
    }, [])

    return (<Col>
        {codeTree.map(resp => {
                return (
                    <SbItem item={resp} openDocCode={doccode} updateDocCode={setdoccodandname}/>
                )
            }
        )}
    </Col>)
}


/*글 내용+목차 분리 컴포넌트*/
//TODO 추가 분리 작업 필요
export function CodeCotentData({docCode}) {
    const [codeChapter, setcodeChapter] = useState([]);
    const [codeContent, setcodeContetn] = useState([]);
    let result =[];
    const getCodeDetail = (docCode) => {
        EgovNet.requestFetch(
            '/standardCode/getCodeDetailInfo.do',
            {
                method: "POST",
                headers: {
                    'Content-type': 'application/json'
                },
                body: JSON.stringify({
                    docCode: docCode
                })
            }, (item) => {
                result = item.result.document;
            }, () => {
            })
    }
    useEffect(() => {
        getCodeDetail(docCode)
        setcodeChapter(result.map(item =>{
            const isTitle = item.full_content.includes(item.group_title);
            return(
            <VwDiv depth={item.cont_level} isTitle={isTitle}>
                <VwPtag href="#" isTitle={isTitle} onClick={() => {
                    document.location.hash="#"+item.cont_type_cd;
                }} dangerouslySetInnerHTML={ {__html: item.group_title} }>
                </VwPtag>
            </VwDiv>
            )
        }))
        setcodeContetn(result.map(item =>{
            const isTitle = item.full_content.includes(item.group_title);
            const docLinkReg = /([A-Z]{3,5}(\s[0-9]{2}){3,4})/g
            const docPartReg = /\((?:표|그림|부록)?\s*([A-Z]\.)?(?!\d\))\d+(\.\d+)*(\s?\(\d\))?(-\d+)?(?:\s*[A-Z])?\)/g
            if(docLinkReg.test(item.full_content)){
                const docCodeAry = item.full_content.match(docLinkReg);
                const docCodeMap = new Map();
                for(let i=0; i<docCodeAry.length; i++) {
                    const docCode = docCodeAry[i];
                    docCodeMap.set(docCode, '<a class="docLink" href="/standardCode/viewer/' + docCode + '" target="_blank">' + docCode + '</a>')
                }
                docCodeMap.forEach((docCodeLink, docCode)=>{
                    item.full_content = item.full_content.replaceAll(docCode, docCodeLink);
                })
                if(docPartReg.test(item.full_content)){

                    const docPartAry = item.full_content.match(docPartReg);
                    const docPartMap = new Map();
                    for(let i=0; i<docPartAry.length; i++) {
                        const docPart = docPartAry[i];
                        const docCodeMatch = item.full_content.substring(item.full_content.indexOf(docPart)-30).match(docLinkReg);
                        let docCode = null;
                        if (docCodeMatch){
                            docCode = docCodeMatch[0];
                        }
                        //const docCode = item.full_content.substring(item.full_content.indexOf(docPart)-30).match(docLinkReg)[0];
                        docPartMap.set(docPart, docPart +
                            '<key class="bookmark" data-doccode="'+docCode+'" data-docpart="'+docPart.replace('(', '').replace(')', '')+'">'+
                            '<svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 16 16" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path d="M2 4a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L7 13.101l-4.223 2.815A.5.5 0 0 1 2 15.5V4z"></path><path d="M4.268 1A2 2 0 0 1 6 0h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L13 13.768V2a1 1 0 0 0-1-1H4.268z"></path></svg>'+
                            '</key>');
                    }
                    docPartMap.forEach((docPartLink, docPart)=>{
                        item.full_content = item.full_content.replaceAll(docPart, docPartLink);
                    })
                }
                if(item.full_content.includes("<table")){
                    item.full_content = item.full_content.replace('<table ', '<table class="table table-bordered "')
                }
                if(item.error_cd !== null){
                    item.full_content = "<div class='errorText'>"+item.error_cd+"</div>"+item.full_content;
                }
                item.full_content = item.full_content+"<hr>"
                return(
                    <VwDiv depth={item.cont_level} isTitle={isTitle} id={item.cont_type_cd} dangerouslySetInnerHTML={ {__html: item.full_content} }></VwDiv>
                )
            }
        }))
    }, [docCode])

    return (<>
        <CodeChapter codeChapter={codeChapter}/>
        <CodeContent codeContent={codeContent}/>
    </>)
}








/*글 목차 컴포넌트*/
export function CodeChapter({codeChapter}) {
    return (<>{codeChapter}</>)
}

/*글 내용 컴포넌트*/
export function CodeContent({codeContent}) {
    return (<>{codeContent}</>)
}