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

import {LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer} from 'recharts';

import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';

import { CSVLink } from "react-csv";

import {format, sub} from "date-fns";
import { ko } from 'date-fns/locale';

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

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

import { itemIdxByPage } from 'utils/calc';

function FileConnections(props) {
    // console.group("EgovAdminPrivacyList");
    // console.log("[Start] EgovAdminPrivacyList ------------------------------");
    // console.log("EgovAdminPrivacyList [props] : ", props);
    const nowDate = new Date();
    const oneMonthAgoDate = sub(nowDate, { months: 1 });
    const [start_date, setStartDate] = useState(oneMonthAgoDate);
    const [end_date, setEndDate] = useState(nowDate);           // new Date()

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

    // eslint-disable-next-line no-unused-vars
    const [searchCondition, setSearchCondition] = useState(location.state?.searchCondition || {start_date: format(start_date, "yyyy-MM-dd"), end_date: format(end_date, "yyyy-MM-dd")});
    const [chartData, setChartData] = useState([]);
    const [excelData, setExcelData] = useState([]);

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

    const excelHeaders = [
        { label: "일자", key: "logdt" },
        { label: "설계기준",  key: "group10" },
        { label: "표준시방서", key: "group20" },
        { label: "서울특별시", key: "group40" },
        { label: "고속도로공사", key: "group50" },
        { label: "농업생산기반시설", key: "group60" },
        { label: "철도건설공사", key: "group70" },
        { label: "LH", key: "group80" },
        { label: "K-water", key: "group90" },
        { label: "(구)설계기준", key: "groupO2" },
        { label: "(구)표준시방서", key: "groupO3" },
        { label: "(구)전문시방서", key: "groupO4" },
        { label: "(구)훈령.예규.지침", key: "groupO567" }
    ];

    const retrieveList = useCallback((srchCnd) => {
        // console.groupCollapsed("EgovAdminUsageList.retrieveList()");
        const retrieveListURL = '/admin/logs/file';

        const requestOptions = {
            method: "POST",
            headers: {
                'Content-type': 'application/json',
            },
            body: JSON.stringify(srchCnd)
        }

        EgovNet.requestFetch(
            retrieveListURL,
            requestOptions,
            (resp) => {
                let mutListTag = [];

                const resultCnt = parseInt(resp.result.resultCnt);
                const currentPageNo = 1;            // resp.result.paginationInfo.currentPageNo;
                const pageSize = resultCnt;         // resp.result.paginationInfo.pageSize;

                // 리스트 항목 구성
                if (resultCnt === 0) {
                    mutListTag.push(<p className="no_data" key="0">데이터가 없습니다.</p>);
                } else {
                    resp.result.resultList.forEach(function (item, index) {
                        if (index === 0) mutListTag = []; // 목록 초기화
                        const listIdx = itemIdxByPage(resultCnt, currentPageNo, pageSize, index);

                        mutListTag.push(
                            <div key={listIdx} className="list_item">
                                <div>{item[0]}</div>
                                <div style={{textAlign: 'right', paddingRight: '10px'}}>{item[1].toLocaleString()}</div>
                                <div style={{textAlign: 'right', paddingRight: '10px'}}>{item[2].toLocaleString()}</div>
                                <div style={{textAlign: 'right', paddingRight: '10px'}}>{item[3].toLocaleString()}</div>
                                <div style={{textAlign: 'right', paddingRight: '10px'}}>{item[4].toLocaleString()}</div>
                                <div style={{textAlign: 'right', paddingRight: '10px'}}>{item[5].toLocaleString()}</div>
                                <div style={{textAlign: 'right', paddingRight: '10px'}}>{item[6].toLocaleString()}</div>
                                <div style={{textAlign: 'right', paddingRight: '10px'}}>{item[7].toLocaleString()}</div>
                                <div style={{textAlign: 'right', paddingRight: '10px'}}>{item[8].toLocaleString()}</div>
                                <div style={{textAlign: 'right', paddingRight: '10px'}}>{item[9].toLocaleString()}</div>
                                <div style={{textAlign: 'right', paddingRight: '10px'}}>{item[10].toLocaleString()}</div>
                                <div style={{textAlign: 'right', paddingRight: '10px'}}>{item[11].toLocaleString()}</div>
                                <div style={{textAlign: 'right', paddingRight: '10px'}}>{item[12].toLocaleString()}</div>
                            </div>
                        );
                    });
                }
                setListTag(mutListTag);

                // chart values
                let chartDataArray = resp.result.resultList.map((item, index) => ({
                    logdt: item[0],             // Assuming logdt is the x-axis data
                    "설계기준": item[1],        // Assuming menuTitle is the y-axis data
                    "표준시방서": item[2],
                    "서울특별시": item[3],
                    "고속도로공사": item[4],
                    "농업생산기반시설": item[5],
                    "철도건설공사": item[6],
                    "LH": item[7],
                    "K-water": item[8],
                    "(구)설계기준": item[9],
                    "(구)표준시방서": item[10],
                    "(구)전문시방서": item[11],
                    "(구)훈령.예규.지침": item[12],
                }));
                setChartData(chartDataArray);

                // excel value
                let filteredExcelData = resp.result.resultList.map((item) => ({
                    logdt: item[0],
                    group10: item[1],
                    group20: item[2],
                    group40: item[3],
                    group50: item[4],
                    group60: item[5],
                    group70: item[6],
                    group80: item[7],
                    group90: item[8],
                    groupO2: item[9],
                    groupO3: item[10],
                    groupO4: item[11],
                    groupO567: item[12]
                }));
                setExcelData(filteredExcelData);
            },
            function (resp) {
                console.log("err response : ", resp);
            }
        );
        // console.groupEnd("EgovAdminPrivacyList.retrieveList()");
    },[listTag]);

    const CustomTooltip = ({ active, payload, label }) => {
        if (active && payload && payload.length) {
            return (
                <div className="custom-tooltip">
                    <p className="intro">파일 다운 현황 [{`${label}`}]</p>
                    <p className="label">설계기준 : {`${payload[0].value}`}회</p>
                    <p className="label">표준시방서 : {`${payload[1].value}`}회</p>
                    <p className="label">서울특별시 : {`${payload[2].value}`}회</p>
                    <p className="label">고속도로공사 : {`${payload[3].value}`}회</p>
                    <p className="label">농업생산기반시설 : {`${payload[4].value}`}회</p>
                    <p className="label">철도건설공사 : {`${payload[5].value}`}회</p>
                    <p className="label">LH : {`${payload[6].value}`}회</p>
                    <p className="label">K-water : {`${payload[7].value}`}회</p>
                    <p className="label">(구)설계기준 : {`${payload[8].value}`}회</p>
                    <p className="label">(구)표준시방서 : {`${payload[9].value}`}회</p>
                    <p className="label">(구)전문시방서 : {`${payload[10].value}`}회</p>
                    <p className="label">(구)훈령.예규.지침 : {`${payload[11].value}`}회</p>
                </div>
            );
        }
        return null;
    };

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

    // console.log("------------------------------EgovAdminPrivacyList [End]");
    // console.groupEnd("EgovAdminPrivacyList");

    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.ADMIN} >사이트관리</Link></li>
                        <li>로그현황</li>
                        <li>파일 다운 현황</li>
                    </ul>
                </div>
                {/* <!--// Location --> */}

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

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

                        <div className="top_tit">
                            <h1 className="tit_1">파일 다운 현황</h1>
                        </div>

                        {/* <!-- 검색조건 --> */}
                        <div className="condition">
                            <ul>
                                <li className="half L">
                                    <DatePicker
                                        dateFormat='yyyy-MM-dd'                     // 날짜 형태
                                        shouldCloseOnSelect                         // 날짜를 선택하면 datepicker가 자동으로 닫힘
                                        minDate={new Date('2017-01-01')}        // minDate 이전 날짜 선택 불가
                                        maxDate={new Date()}                        // maxDate 이후 날짜 선택 불가
                                        selected={start_date}
                                        locale={ko}
                                        className="f_input1 al_c"
                                        selectsStart
                                        startDate={start_date}
                                        endDate={end_date}
                                        onChange={(date) => {
                                            setStartDate(date);
                                            setSearchCondition({
                                                start_date: format(date, "yyyy-MM-dd"),
                                                end_date: format(end_date, "yyyy-MM-dd")
                                            });
                                        }}
                                    /> -
                                </li>
                                <li className="half R">
                                    <DatePicker
                                        dateFormat='yyyy-MM-dd'                     // 날짜 형태
                                        shouldCloseOnSelect                         // 날짜를 선택하면 datepicker가 자동으로 닫힘
                                        minDate={new Date('2017-01-01')}        // minDate 이전 날짜 선택 불가
                                        maxDate={new Date()}                        // maxDate 이후 날짜 선택 불가
                                        selected={end_date}
                                        locale={ko}
                                        className="f_input1 al_c"
                                        selectsEnd
                                        startDate={start_date}
                                        endDate={end_date}
                                        onChange={(date) => {
                                            setEndDate(date);
                                            setSearchCondition({
                                                start_date: format(start_date, "yyyy-MM-dd"),
                                                end_date: format(date, "yyyy-MM-dd")
                                            });
                                        }}
                                    />
                                    {/*<button type="button" className="btn btn_blue_h32 ms-2" onClick={getExcelData}>엑셀 다운로드</button>          */}
                                    <CSVLink data={excelData}
                                             headers={excelHeaders}
                                             filename={"파일 다운 현황.csv"}
                                             target="_blank"
                                             className="btn btn_blue_h32 ms-2"
                                             separator={";"}
                                             >CSV ⬇</CSVLink>
                                </li>
                            </ul>
                        </div>
                        {/* <!--// 검색조건 --> */}

                        {/* <!-- 목록 --> */}
                        <div className="board_list BRD011">
                            <div className="head">
                                <span>일자</span>
                                <span>설계기준</span>
                                <span>표준시방서</span>
                                <span>서울특별시</span>
                                <span>고속도로공사</span>
                                <span>농업생산기반시설</span>
                                <span>철도건설공사</span>
                                <span>LH</span>
                                <span>K-water</span>
                                <span>(구)설계기준</span>
                                <span>(구)표준시방서</span>
                                <span>(구)전문시방서</span>
                                <span>(구)훈령.예규.지침</span>
                            </div>
                            <div className="result">
                                {listTag}
                            </div>
                        </div>
                        <div className="">
                            <ResponsiveContainer width="100%" height={477}>
                                <LineChart data={chartData}
                                          height={477}
                                          margin={{
                                              top: 5,
                                              right: 0,
                                              left: 0,
                                              bottom: 0,
                                          }}
                                >
                                    <CartesianGrid strokeDasharray="3 3" />
                                    <XAxis type="category" dataKey="logdt" tick={{ fontSize: 10, whiteSpace: 'nowrap' }} />
                                    <YAxis type="number" />
                                    <Tooltip content={<CustomTooltip/>} />
                                    <Legend />
                                    <Line type="monotone" dataKey="설계기준" stroke="#87CEFA" />
                                    <Line type="monotone" dataKey="표준시방서" stroke="#82ca9d" />
                                    <Line type="monotone" dataKey="서울특별시" stroke="#8884d8" />
                                    <Line type="monotone" dataKey="고속도로공사" stroke="#87B17A" />
                                    <Line type="monotone" dataKey="농업생산기반시설" stroke="#F2857A" />
                                    <Line type="monotone" dataKey="철도건설공사" stroke="#F6C86B" />
                                    <Line type="monotone" dataKey="LH" stroke="#EA3322" />
                                    <Line type="monotone" dataKey="K-water" stroke="#333" />
                                    <Line type="monotone" dataKey="(구)설계기준" stroke="#F5C2CB" />
                                    <Line type="monotone" dataKey="(구)표준시방서" stroke="#3B86F6" />
                                    <Line type="monotone" dataKey="(구)전문시방서" stroke="#9CDE54" />
                                    <Line type="monotone" dataKey="(구)훈령.예규.지침" stroke="#008080" />
                                </LineChart>
                            </ResponsiveContainer>
                        </div>
                        {/* <!--// 목록 --> */}

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

export default FileConnections;