import React, { useState, useEffect, useCallback, useRef } from 'react';
import {Link, useLocation, useParams} from 'react-router-dom';

import * as EgovNet from 'api/egovFetch';
import URL from 'constants/url';
import { NOTICE_BBS_ID } from 'config';


import EgovPaging from 'components/EgovPaging';
import { itemIdxByPage } from 'utils/calc';

import {StandardCodeListModal, StandardCodeListModalTable} from './StandardCodeListModal'

function StandardCodeList(props) {
    const {listCode} = useParams();
    const [show, setshow] = useState(false);
    const [groupseq,setgroupseq] = useState();
    function showhandling(e){
        const param = e.currentTarget.dataset;
        const groupseq = param.groupseq;
        console.log(groupseq);
        EgovNet.requestFetch(
            '/standardCode/testCodeList.do',
        {
            method: "POST",
            headers: {
                'Content-type': 'application/json'
            },
            body: JSON.stringify(
                groupseq
            )
        },(resp) =>{
                console.log(resp+"------------------------resp")
                const body =[];
                const head =[];
                if(resp.length>0){

                    resp.forEach(function (item,index){
                        const formattedDate = item.aplcnBgngYmd.match(/\d{4}-\d{2}-\d{2}/)[0];
                        const url = "https://www.kcsc.re.kr/file/DownloadGrp/"+item.docFileGrpId;
                        body.push(
                            <tr>
                            <td>{formattedDate}</td>
                            <td><a href={url}>{item.docFileGrpId}</a></td>
                            <td></td>
                        </tr>)
                    })
                    head.push(
                        <tr>
                            <td>년도</td>
                            <td>기준코드</td>
                            <td>신구건설기준비교</td>
                        </tr>
                    )
                }

                 setgroupseq(<StandardCodeListModalTable head={head} content={body}/>);
            }
        )
        setshow(true);

    }
    function close () {
        setshow(false);
    }
    console.group("StandardCodeList");
    console.log("[Start] StandardCodeList ------------------------------");
    console.log("StandardCodeList [props] : ", props);
    console.log("listcode----------------------------"+listCode);

    const location = useLocation();
    console.log("StandardCodeList [location] : ", location);

    const cndRef = useRef();
    const wrdRef = useRef();

    const bbsId = location.state?.bbsId || NOTICE_BBS_ID;

    // eslint-disable-next-line no-unused-vars
    const [searchCondition, setSearchCondition] = useState(location.state?.searchCondition || { listCode: listCode, pageIndex: 1, searchCnd: '0', searchWrd: '' });// 기존 조회에서 접근 했을 시 || 신규로 접근 했을 시
    const [masterBoard, setMasterBoard] = useState({});
    const [paginationInfo, setPaginationInfo] = useState({});

    const [listTag, setListTag] = useState([]);

    const retrieveList = useCallback((searchCondition) => {
        console.groupCollapsed("StandardCodeList.retrieveList()");

        const retrieveListURL = '/standardCode/selectStandardCodeList.do';
        const requestOptions = {
            method: "POST",
            headers: {
                'Content-type': 'application/json',
            },
            body: JSON.stringify(searchCondition)
        }

        EgovNet.requestFetch(retrieveListURL,
            requestOptions,
            (resp) => {
                setMasterBoard(resp.result.tnDocumentInfo);
                setPaginationInfo(resp.result.paginationInfo);

                let mutListTag = [];
                mutListTag.push(<p className="no_data" key="0">검색된 결과가 없습니다.</p>); // 게시판 목록 초기값

                const resultCnt = parseInt(resp.result.resultCnt);
                const currentPageNo = resp.result.paginationInfo.currentPageNo;
                const pageSize = resp.result.paginationInfo.pageSize;
                console.log(resp)
                // 리스트 항목 구성
                resp.result.resultList.forEach(function (item, index) {
                    if (index === 0) mutListTag = []; // 목록 초기화
                    const listIdx = itemIdxByPage(resultCnt , currentPageNo, pageSize, index);

                    mutListTag.push(
                        <Link
                            key={listIdx}
                            className="list_item List_Codes" >
                            <div>{item.mainCategory}</div>
                            <div>{item.middleCategory}</div>
                            <div>{item.kcscCd}</div>
                            {(item.replyLc * 1 ? true : false) &&
                            <div className="al reply">
                                {item.groupNm}
                            </div>}
                            {(item.replyLc * 1 ? false : true) &&
                            <div className="al">
                                {item.groupNm}
                            </div>}
                            <div><button onClick={showhandling}  data-groupseq = {item.groupSeq}>개정이력</button></div>
                            <div>{item.contentcount>0?<a href = {"/standardCode/viewer/"+item.kcscCd}>{item.kcscCd}</a>:null}</div>
                            <div>{item.docFileGrpId}</div>
                            <div></div>

                        </Link>
                    );
                });
                setListTag(mutListTag);
            },
            function (resp) {
                console.log("err response : ", resp);
            }
        );
        console.groupEnd("StandardCodeList.retrieveList()");
    },[]);

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

    console.log("------------------------------StandardCodeList [End]");
    console.groupEnd("StandardCodeList");
    return (
        <div className="StandardCodeList container">
            <div className="c_wrap">
                {/* <!-- Location --> */}
                <div className="location">
                    <ul>
                        <li><Link to={URL.MAIN} className="home">Home</Link></li>
                        <li><Link to='#'>건설기준코드</Link></li>
                        <li>{masterBoard && masterBoard.bbsNm}</li>
                    </ul>
                </div>
                {/* <!--// Location --> */}

                <div className="layout">
                    {/* <!-- Navigation --> */}

                    {/* <!--// Navigation --> */}

                    <div className="contents NOTICE_LIST" id="contents">
                        {/* <!-- 본문 --> */}

                        <div className="top_tit">
                            <h2 className="tit_1">건설기준코드</h2>
                        </div>

                        <h2 className="tit_2">설계기준, 표준시방서 내용을 열람할 수 있습니다.</h2>

                        {/* <!-- 검색조건 --> */}
                        <div className="condition">
                            <ul>
                                <li className="third_1 L">
                                    <label className="f_select" htmlFor="sel1">
                                        <select id="sel1" title="조건" defaultValue={searchCondition.searchCnd} ref={cndRef}
                                                onChange={e => {
                                                    cndRef.current.value = e.target.value;
                                                }}
                                        >
                                            <option value="0">제목</option>
                                            <option value="1">내용</option>
                                            <option value="2">작성자</option>
                                        </select>
                                    </label>
                                </li>
                                <li className="third_2 R">
                                    <span className="f_search w_500">
                                        <input type="text" name="" defaultValue={searchCondition.searchWrd} placeholder="" ref={wrdRef}
                                               onChange={e => {
                                                   wrdRef.current.value = e.target.value;
                                               }}
                                        />
                                        <button type="button"
                                                onClick={() => {
                                                    retrieveList({ ...searchCondition, pageIndex: 1, searchCnd: cndRef.current.value, searchWrd: wrdRef.current.value });
                                                }}>조회</button>
                                    </span>
                                </li>
                                <li>
                                    <Link to={URL.INFORM_NOTICE_CREATE} state={{bbsId: bbsId}} className="btn btn_blue_h46 pd35">등록</Link>
                                </li>
                            </ul>
                        </div>
                        {/* <!--// 검색조건 --> */}

                        {/* <!-- 게시판목록 --> */}
                        <div className="board_list BRD002">
                            <div className="head">
                                <span>대분류</span>
                                <span>중분류</span>
                                <span>코드번호</span>
                                <span>코드명</span>
                                <span>개정이력</span>
                                <span>보기</span>
                                <span>다운로드</span>
                                <span>즐겨찾기</span>
                            </div>
                            <div className="result">
                                {listTag}
                            </div>
                        </div>
                        {/* <!--// 게시판목록 --> */}

                        <div className="board_bot">
                            {/* <!-- Paging --> */}
                            <EgovPaging pagination={paginationInfo} moveToPage={passedPage => {
                                retrieveList({ ...searchCondition, pageIndex: passedPage, searchCnd: cndRef.current.value, searchWrd: wrdRef.current.value })
                            }} />
                            {/* <!--/ Paging --> */}
                            <StandardCodeListModal size={"lg"} show ={show} content ={groupseq} onClose = {close} title={"개정이력"}/>
                            
                        </div>

                        {/* <!--// 본문 --> */}
                    </div>
                </div>
            </div>
        </div>
    );
}


export default StandardCodeList;

