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

import * as EgovNet from 'api/egovFetch';
import URL from 'constants/url';

import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import Button from 'react-bootstrap/Button';
import {format} from "date-fns";
import EgovPaging from "../../components/EgovPaging";

function List(){
    const navigate = useNavigate();

    const goToCreate = () => {
        navigate('/support/create/KCSC-QA');
    };
    const location = useLocation();

    const {BbsCode} = useParams();
    const [searchCondition, setSearchCondition] = useState(location.state?.searchCondition || { pageIndex: 1, searchCnd: '0', searchKeyword: '', bbsId:BbsCode });// 기존 조회에서 접근 했을 시 || 신규로 접근 했을 시
    const [paginationInfo, setPaginationInfo] = useState({});
    const [listTag, setListTag] = useState([]);
    const [categoryList, setCategoryList] = useState([]);

    const [show, setShow] = useState(false);
    const [modalBody, setModalBody] = useState();
    const handleClose = () => setShow(false);
    const handleShow = () => setShow(true);

    console.log("@@@ BbsCode : " + BbsCode);

    const retrieveList = useCallback((searchCondition) => {
        handleClose();
        const params = EgovNet.convParams(searchCondition);

        console.groupCollapsed("EgovAdminPostList.retrieveList()");

        const retrieveListURL = '/admin/boards/posts/post-list' + params;

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

            }
        }

        EgovNet.requestFetch(retrieveListURL,
            requestOptions,
            (resp) => {
                setPaginationInfo(resp.result.paginationInfo);
                setCategoryList(resp.result.categoryList);
                console.log("@@@ resultCnt : " + resp.result.resultCnt);

                let mutListTag = [];
                setListTag([]);
                resp.result.fixedList.forEach(function (item) {
                    const finalModifiedDate = item?.lastChgDt ? item?.lastChgDt : item?.frstCrtDt;
                    const formattedDate = finalModifiedDate ? format(finalModifiedDate, "yyyy-MM-dd") : "";
                    mutListTag.push(
                        <div className="list_item">
                            <div>공지</div>
                            <div className="al">{item?.bbsContTitle}</div>
                            <div>{item?.frstCrtId}</div>
                            <div>{item?.bbsReadCnt}</div>
                            <div>{formattedDate}</div>
                            <div>{item?.fileGrpId && <img src="/assets/images/file.png" />}</div>
                        </div>
                    );
                });

                resp.result.postList.forEach(function (item, index) {
                    const finalModifiedDate = item?.lastChgDt ? item?.lastChgDt : item?.frstCrtDt;
                    const formattedDate = finalModifiedDate ? format(finalModifiedDate, "yyyy-MM-dd") : "";
                    mutListTag.push(
                        <div className="list_item">
                            <div>{resp.result.resultCnt - (resp.result.paginationInfo.pageIndex -1) * resp.result.paginationInfo.rowCnt - index}</div>
                            <div className="al">{item?.bbsContTitle}</div>
                            <div>{item?.frstCrtId}</div>
                            <div>{item?.bbsReadCnt}</div>
                            <div>{formattedDate}</div>
                            <div>{item?.fileGrpId && <img src="/assets/images/file.png" />}</div>
                        </div>
                    );
                });
                if(!mutListTag.length) mutListTag.push(<p className="no_data" key="0">검색된 결과가 없습니다.</p>); // 게시판 목록 초기값
                setListTag(mutListTag);
            },
            function (resp) {
                console.log("err response : ", resp);
            }
        );
        console.groupEnd("EgovAdminPostList.retrieveList()");
    },[listTag]);

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


    return (
        <div className="container">
            <div className="c_wrap">
                {/* <!-- Location --> */}
                <div className="location">
                    <ul>
                        <li><Link to={URL.MAIN} className="home" >Home</Link></li>
                        <li><Link to={URL.SUPPORT_LIST_NOCODE+'/KCSC-NTC'}>정보제공</Link></li>
                        <li>게시판명</li>
                    </ul>
                </div>
                {/* <!--// Location --> */}

                <div className="layout">
                    <div className="contents QNA_LIST" id="contents">
                        {/* <!-- 본문 --> */}
                        <h1 className="tit_3">게시판명</h1>

                        {/* <!-- 검색조건 --> */}
                        <div className="condition1">
                            <ul>
                                <li className="">
                                    <label className="" htmlFor="search_select">
                                        <select defaultValue={"0"} name="search_select" id="search_select" className="form-select shadow-none" >
                                            <option value="0">전체</option>
                                            <option value="1">제목</option>
                                            <option value="2">제목/내용</option>
                                            <option value="3">작성자</option>
                                        </select>
                                    </label>
                                </li>
                                <li className="">
                                    <input type="text" name="" placeholder="" className="form-control shadow-none rounded-2" />
                                </li>
                                <li className="">
                                    <button type="button" className="btn btn-outline-secondary px-4">검색</button>
                                </li>
                            </ul>
                        </div>
                        {/* <!--// 검색조건 --> */}

                        {/* <!-- 게시판목록 --> */}
                        <div className="board_list BRD013">
                            <div className="head">
                                <span>번호</span>
                                <span>제목</span>
                                <span>작성자</span>
                                <span>조회수</span>
                                <span>등록일</span>
                                <span>파일</span>
                            </div>
                            <div className="result">
                                {/* <!-- case : 데이터 없을때 --> */}
                                {/* <p className="no_data" key="0">검색된 결과가 없습니다.</p> */}

                                {/* <!-- case : 데이터 있을때 --> */}
                                {listTag}
                                {/*<Link to={URL.SUPPORT_DETAIL_NOCODE+'/KCSC-NTC'} className="list_item">
                                    <div>3</div>
                                    <div className="al">[공지] 공통컴포넌트 중 모니터링 관련 서비스 실행시 오류가 발생합니다 [15] <img src="/assets/images/lock.png" className="pt-1" /> <img src="/assets/images/new.png" className="pt-1" /></div>
                                    <div>관리자</div>
                                    <div>3</div>
                                    <div>2021-7-24</div>
                                    <div><img src="/assets/images/file.png" /></div>
                                </Link>
                                <Link to={URL.SUPPORT_DETAIL_NOCODE+'/KCSC-NTC'} className="list_item">
                                    <div>2</div>
                                    <div className="al"><img src="/assets/images/re.png" className="pt-1" /> validation 처리 시.패스워드에 대한 메소드를 찾지 못합니다.</div>
                                    <div>홍길동</div>
                                    <div>3</div>
                                    <div>2021-7-24</div>
                                    <div></div>
                                </Link>
                                <Link to={URL.SUPPORT_DETAIL_NOCODE+'/KCSC-NTC'} className="list_item">
                                    <div>1</div>
                                    <div className="al d-flex align-items-center">
                                        미답변시 아이콘
                                        <img src="/assets/images/icon_answer0.png" className="pt-1 h_30 pb-1" /> &nbsp;
                                        답변완료시 아이콘
                                        <img src="/assets/images/icon_answer.png" className="pt-1 h_30 pb-1" /> &nbsp;
                                        공통컴포넌트 중 모니터링 관련 서비스 실행시 오류가 발생합니다.</div>
                                    <div>홍길동</div>
                                    <div>3</div>
                                    <div>2021-7-24</div>
                                    <div></div>
                                </Link>*/}
                            </div>
                        </div>
                        {/* <!--// 게시판목록 --> */}

                        <Row className="board_bot justify-content-between">
                            <Col xs={3} className=""></Col>
                            {/* <!-- Paging --> */}
                            <EgovPaging pagination={paginationInfo} moveToPage={passedPage => {
                                retrieveList({ ...searchCondition, pageIndex: passedPage}) //, searchCnd: cndRef.current.value, searchKeyword: wrdRef.current.value
                            }} />
                            <Col xs={6} className="paging">
                                <ul>
                                    <li className="btn"><button to="" className="first">처음</button></li>
                                    <li className="btn"><button to="" className="prev">이전</button></li>
                                    <li><button to="" className="cur">1</button></li>
                                    <li><button to="">2</button></li>
                                    <li><button to="">3</button></li>
                                    <li><button to="">4</button></li>
                                    <li><button to="">5</button></li>
                                    <li><button to="">6</button></li>
                                    <li><button to="">7</button></li>
                                    <li><button to="">8</button></li>
                                    <li><button to="">9</button></li>
                                    <li><button to="">10</button></li>
                                    <li className="btn"><button to="" className="next">다음</button></li>
                                    <li className="btn"><button to="" className="last">마지막</button></li>
                                </ul>
                            </Col>
                            {/* <!--/ Paging --> */}

                            {/* 수요조사는 버튼명 "의견 접수"  수요조사와 QNA만 작성가능하게 관리자 세팅되어야 함/관리자 쓰기권한만 작성가능 */}
                            <Col xs={3} className="text-end"><button type={"button"} className={"btn btn-outline-secondary px-4"} onClick={goToCreate}>질의 작성</button></Col>
                        </Row>

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

export default List;