import {
    Button, Flex, Space, Table, TableProps,Empty
} from "antd";
import useMessage from "antd/es/message/useMessage";
import { useEffect, useState, useContext } from "react";

import { getRechargeRecordList } from '../../../request/api.ts'
import { GlobalContext } from "../../../context/GlobalContext.ts";


type DataType = {
    rechargeMoney: number;
    thirdParty: string;
    reconciliationTime: string;
    rechargeFinalTime: string;
    accountRechargeId: string;
}

interface ListProps {
    selectedOrderIds?: string[];
    handleOk: (selectedOrders: DataType[]) => void;
    handleCancel: () => void;
    selectedOrders?: any;
    setSelectedOrders?: React.Dispatch<React.SetStateAction<any[]>>;
    // isInvoiceInfoListOpen?: any;
}

export default function InvoiceInfoList(props: ListProps) {
    const {
        selectedOrders,
        setSelectedOrders,
    } = props;
    const [messageApi, messageContext] = useMessage();
    const [page, setPage] = useState(1);
    const [total, setTotal] = useState(0);
    const [dataArray, setDataArray] = useState<DataType[]>([]);
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [applyOrders, setApplyOrders] = useState<DataType[]>(selectedOrders);

    const columns: TableProps<DataType>['columns'] = [

        {
            title: '充值金额',
            dataIndex: 'rechargeMoney',
            align: 'center',
            width: 80,

        },
        {
            title: '充值方式',
            dataIndex: 'thirdParty',
            align: 'center',
            width: 80,

        },
        {
            title: '充值时间',
            dataIndex: 'reconciliationTime',
            align: 'center',
            width: 100,

        },
        {
            title: '充值到账时间',
            dataIndex: 'rechargeFinalTime',
            align: 'center',
            width: 100,
        },

    ]
    const globalContext = useContext(GlobalContext);
    const getData = async () => {
        try {
            const res: any = await getRechargeRecordList(globalContext.user.userId, { page: page, rows: 20 })
            // console.log('数据', res);
            setPage(res.page);
            setTotal(res.total);
            setDataArray(res.rows);

        } catch (error: any) {
            if (error.response) {
                const data = error.response.data;
                messageApi.open({
                    type: 'error',
                    content: data.msg ? data.msg : `${data.path}(${data.status})`,
                });
            } else {
                console.error(error)
            }
        }

    }

    useEffect(() => {
        getData();
    }, [page]);

    useEffect(() => {
        // console.log('11', applyOrders);
        if (applyOrders) {
            const selectedIds = applyOrders.map((order: DataType) => order.accountRechargeId);
            setSelectedRowKeys(selectedIds);
        }
    }, [applyOrders])

    return (
        <>
            <div className="invoice-list-container">
                <div className="mod-list">
                    {dataArray.length > 0 ?
                        <>
                            <Table rowSelection={
                                {
                                    selectedRowKeys,
                                    onSelect: (data) => {
                                        const isSelect = applyOrders?.some((item: DataType) => item.accountRechargeId === data.accountRechargeId)
                                        // console.log('onSelect', data, isSelect);
                                        if (!isSelect) {
                                            setApplyOrders?.([...applyOrders, data])
                                        } else {
                                            setApplyOrders?.(applyOrders?.filter((item: DataType) => item.accountRechargeId !== data.accountRechargeId))
                                        }
                                    },
                                    onSelectAll: (isAll) => {
                                        if (isAll) {
                                            const newSelectedOrders = dataArray.filter((item: DataType) => !applyOrders?.some((order: DataType) => order.accountRechargeId === item.accountRechargeId));
                                            // const setectSelectedOrders = applyOrders?.filter((item: DataType) => !dataArray?.some((order: DataType) => order.accountRechargeId === item.accountRechargeId));
                                            // console.log('newSelectedOrders', newSelectedOrders, setectSelectedOrders);
                                            setApplyOrders?.([...applyOrders, ...newSelectedOrders])
                                        } else {
                                            const setectSelectedOrders = applyOrders?.filter((item: DataType) => !dataArray?.some((order: DataType) => order.accountRechargeId === item.accountRechargeId));
                                            // console.log('setectSelectedOrders', setectSelectedOrders);
                                            setApplyOrders?.([...setectSelectedOrders])
                                        }
                                    },

                                }
                            } columns={columns} dataSource={dataArray} pagination={
                                {
                                    pageSize: 20,
                                    total: total,
                                    showSizeChanger: false,
                                    onChange: (currentPage) => {
                                        setPage(currentPage);
                                    }
                                }
                            } scroll={{ y: 500 }} bordered key="dataTable" rowKey="accountRechargeId" />
                        </> :
                        <>
                            <div style={{
                                width: '100%', height: '200px', display: 'flex', justifyContent: 'center', alignItems: 'center', fontSize: '20px'
                            }}>
                                <Empty description='暂无信息' />
                            </div>
                        </>
                    }
                    {/* <Table rowSelection={
                        {
                            selectedRowKeys,
                            onSelect: (data) => {
                                const isSelect = applyOrders?.some((item: DataType) => item.accountRechargeId === data.accountRechargeId)
                                // console.log('onSelect', data, isSelect);
                                if (!isSelect) {
                                    setApplyOrders?.([...applyOrders, data])
                                } else {
                                    setApplyOrders?.(applyOrders?.filter((item: DataType) => item.accountRechargeId !== data.accountRechargeId))
                                }
                            },
                            onSelectAll: (isAll) => {
                                if (isAll) {
                                    const newSelectedOrders = dataArray.filter((item: DataType) => !applyOrders?.some((order: DataType) => order.accountRechargeId === item.accountRechargeId));
                                    // const setectSelectedOrders = applyOrders?.filter((item: DataType) => !dataArray?.some((order: DataType) => order.accountRechargeId === item.accountRechargeId));
                                    // console.log('newSelectedOrders', newSelectedOrders, setectSelectedOrders);
                                    setApplyOrders?.([...applyOrders, ...newSelectedOrders])
                                } else {
                                    const setectSelectedOrders = applyOrders?.filter((item: DataType) => !dataArray?.some((order: DataType) => order.accountRechargeId === item.accountRechargeId));
                                    // console.log('setectSelectedOrders', setectSelectedOrders);
                                    setApplyOrders?.([...setectSelectedOrders])
                                }
                            },

                        }
                    } columns={columns} dataSource={dataArray} pagination={
                        {
                            pageSize: 20,
                            total: total,
                            showSizeChanger: false,
                            onChange: (currentPage) => {
                                setPage(currentPage);
                            }
                        }
                    } scroll={{ y: 500 }} bordered key="dataTable" rowKey="accountRechargeId" /> */}
                </div>
                <Flex justify="center">
                    <Space size={5}>
                        <Button type="primary"
                            style={{ backgroundColor: 'var(--color-primary)' }}
                            onClick={() => {
                                // console.log('onok', applyOrders);
                                if (!applyOrders || applyOrders?.length === 0) {
                                    messageApi.error('请选择开票订单');
                                    return;
                                }
                                // setSelectedOrders?.(applyOrders);
                                setSelectedOrders?.(applyOrders);
                                props.handleOk(applyOrders);
                            }}
                        >确定</Button>
                        <Button type="default" onClick={() => {
                            setSelectedOrders?.(selectedOrders);
                            props.handleCancel();
                        }}>关闭</Button>
                    </Space>
                </Flex>
            </div>
            {messageContext}
        </>
    );
}