import React, { useState, useEffect } from 'react'
import LogAuth from './View'
import { getLogApi } from 'app/apis/Functions/System/Logging'
import { useHistory } from 'react-router-dom'
import KEY from '../../../assets/Key'
import { connect } from 'react-redux'
import { showLoading, hideLoading } from 'app/redux/actions/loadingAction'
import { toast } from 'react-toastify'

const ToolNotificate = (props) => {
    const [txtSearch, setTxtSearch] = useState('')
    const [applications, setApplications] = useState('')
    const [pageIndex, setPageIndex] = useState(0)
    const [pageSize] = useState(10)
    const [totalRecords, setTotalRecord] = useState(0)
    const history = useHistory()

    const [data, setData] = useState([])

    const getData = async (isInit) => {
        props.showLoading()

        let res
        if (isInit) {
            setPageIndex(0)
            res = await getLogApi({
                search: txtSearch,
                applications,
                page_no: 0,
                page_size: pageSize,
            })
        } else {
            res = await getLogApi({
                search: txtSearch,
                applications,
                page_no: pageIndex + 1,
                page_size: pageSize,
            })
        }

        props.hideLoading()
        if (res.data.code == 200 && res.data.data) {
            const newList = res.data.data.data.map((e, i) => {
                return { ...e, index: i + 1 + pageIndex * pageSize }
            })
            setData(newList)
            setTotalRecord(res.data.data.total_elements)
        } else if (res.data.code == 401) {
            setTimeout(() => {
                history.push('/')
            }, 100)
        } else {
            toast.error('Lấy dữ liệu thất bại!', {
                theme: 'colored',
            })
        }
    }

    useEffect(() => {
        getData(true)
    }, [txtSearch, applications])

    useEffect(() => {
        getData(false)
    }, [pageIndex])

    return (
        <LogAuth
            data={data}
            setTxtSearch={setTxtSearch}
            pageIndex={pageIndex}
            setPageIndex={setPageIndex}
            totalRecords={totalRecords}
            setApplications={setApplications}
            applications={applications}
        />
    )
}

const mapStateToProps = (state) => {
    return {}
}
export default connect(mapStateToProps, { showLoading, hideLoading })(
    ToolNotificate
)
