import React, { useState, useEffect } from 'react'
import LogAuth from './View'
import {
    listTransReconciliation,
    deleteTranInReconciliation,
    addTransInReconciliation,
} from 'app/apis/Functions/reconciliation'
import { useHistory } from 'react-router-dom'
import { toPriceVnd, convertDate } from 'app/config/Function'
import { connect } from 'react-redux'
import { showLoading, hideLoading } from 'app/redux/actions/loadingAction'
import { toast } from 'react-toastify'
import useDebounce from 'app/hooks/useDebounce'
import { useTranslation } from 'react-i18next'
import { dropdownMerchant, dropdownStore } from 'app/apis/Functions/dropdown'

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 searchDebount = useDebounce(txtSearch, 1000)
    const [startDate, setStartDate] = useState()
    const [endDate, setEndDate] = useState()
    const { t } = useTranslation()
    const [data, setData] = useState([])
    const [type, setType] = useState()
    const [listType, setListType] = useState([])
    const [merchant, setMerchant] = useState()
    const [listMerchant, setListMerchant] = useState([])
    const [store, setStore] = useState()
    const [listStore, setListStore] = useState([])
    const [total, setTotal] = useState(0)

    useEffect(() => {
        getDataMerchant()
    }, [])

    const changeDateRange = (start, end) => {
        setStartDate(start)
        setEndDate(end)
    }

    const getData = async (init) => {
        if (props?.idReconciliation) {
            let res
            if (init) {
                setPageIndex(0)
                res = await listTransReconciliation({
                    page_no: 0,
                    page_size: pageSize,
                    date_from: startDate ? convertDate(startDate) : null,
                    date_to: endDate ? convertDate(endDate) : null,
                    product_code: null,
                    payment_gate_code: null,
                    statusReconciliation: 0,
                    type_payment: null,
                    idReconciliation: props?.idReconciliation,
                    is_reconciliation: true,
                    text: searchDebount,
                })
            } else {
                res = await listTransReconciliation({
                    page_no: pageIndex + 1,
                    page_size: pageSize,
                    date_from: startDate ? convertDate(startDate) : null,
                    date_to: endDate ? convertDate(endDate) : null,
                    product_code: null,
                    payment_gate_code: null,
                    statusReconciliation: 0,
                    type_payment: null,
                    idReconciliation: props?.idReconciliation,
                    is_reconciliation: true,
                    text: searchDebount,
                })
            }

            if (res.data.code == 200 && res.data.data) {
                console.log(' res.data.data', 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)
                setTotal(res.data.data.total_commision)
            } else if (res.data.code == 401) {
                setTimeout(() => {
                    history.push('/')
                }, 100)
            } else {
                toast.error(t(res.data.error), {
                    theme: 'colored',
                })
            }
        }
    }

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

    useEffect(() => {
        getData(true)
    }, [searchDebount, startDate, type, merchant, store])

    useEffect(() => {
        if (merchant) {
            getDropdownStore(merchant)
        }
        setStore()
    }, [merchant])

    const getDataMerchant = async () => {
        const res = await dropdownMerchant({})

        if (res.data.code == 200 && res.data.data) {
            const newList = res.data.data.map((e) => {
                return { ...e, name: e.merchant_name }
            })
            setListMerchant(newList)
        } else {
            toast.error(t(res.data.error), {
                theme: 'colored',
            })
        }
    }

    const getDropdownStore = async (id) => {
        const res = await dropdownStore(id)

        if (res.data.code == 200 && res.data.data) {
            console.log('res.data.data', res.data.data)
            const newList = res.data.data.map((e) => {
                return { ...e, name: e.store_name }
            })
            setListStore(newList)
        } else {
            toast.error(t(res.data.error), {
                theme: 'colored',
            })
        }
    }

    const removeItem = async (id) => {
        props.showLoading()
        const res = await deleteTranInReconciliation(id)
        props.hideLoading()
        if (res.data.code == 200) {
            getData(true)
            toast.success('Xoá giao dịch trong phiếu đối soát thành công!', {
                theme: 'colored',
            })
        } else {
            toast.error('Xoá bản ghi thất bại!', {
                theme: 'colored',
            })
        }
    }
    const onAddTrans = async (listTrans) => {
        if (listTrans.length > 0) {
            props.showLoading()
            const res = await addTransInReconciliation({
                id: props?.idReconciliation,
                idTrans: listTrans,
            })
            props.hideLoading()
            if (res.data.code == 200) {
                getData(true)
                toast.success('Thêm giao dịch vào phiếu đối soát thành công!', {
                    theme: 'colored',
                })
            } else {
                toast.error('Thêm giao dịch vào phiếu đối soát thất bại!', {
                    theme: 'colored',
                })
            }
        }
    }

    return (
        <LogAuth
            data={data}
            setTxtSearch={setTxtSearch}
            pageIndex={pageIndex}
            setPageIndex={setPageIndex}
            totalRecords={totalRecords}
            setApplications={setApplications}
            applications={applications}
            startDate={startDate}
            changeDateRange={changeDateRange}
            type={type}
            setType={setType}
            listType={listType}
            merchant={merchant}
            setMerchant={setMerchant}
            listMerchant={listMerchant}
            store={store}
            setStore={setStore}
            listStore={listStore}
            isDetail={props.isDetail}
            idPaymentPartner={props?.idPaymentPartner}
            removeItem={removeItem}
            onAddTrans={onAddTrans}
            total={total}
            id={props.id}
        />
    )
}

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