import { Empty,Button, Flex, Modal, Popconfirm, Space, Table, TableProps } from "antd";
import { DeleteOutlined, EditOutlined, PlusOutlined } from "@ant-design/icons";
import useMessage from "antd/es/message/useMessage";
import { useEffect, useRef, useState, useContext } from "react";
// import { del, get } from "../../../util/AjaxUtils.ts";
// import { IListPage } from "../../../interfaces/listpage/IListPage.ts";
import InvoiceInfoSave from "./InvoiceInfoSave.tsx";
import InvoiceInfoEdit from "./InvoiceInfoEdit.tsx";
import { getInvoiceList, deleteInvoiceInfo } from '../../../request/api.ts'
import { GlobalContext } from "../../../context/GlobalContext.ts";
type DataType = {
    invoiceName: string;
    invoiceNumber: string;
    invoiceOrgaddress: string;
    invoiceOrgtel: string;
    invoiceBank: string;
    invoiceBanknumber: string;
    invoiceId: string;
}

interface ListProps {
    handleOk: (selectedInvoice: DataType) => void;
    handleCancel: () => void;
}

export default function InvoiceInfoList(props: ListProps) {
    const [messageApi, messageContext] = useMessage();
    const [isInvoiceInfoSaveOpen, setIsInvoiceInfoSaveOpen] = useState(false);
    const [isInvoiceInfoEditOpen, setIsInvoiceInfoEditOpen] = useState(false);
    const [page, setPage] = useState(1);
    const [total, setTotal] = useState(0);
    const [dataArray, setDataArray] = useState<DataType[]>([]);
    const editInvoiceInfoId = useRef('');
    const selectedInvoice = useRef<DataType | null>(null);

    const columns: TableProps<DataType>['columns'] = [
        {
            title: '公司名称',
            dataIndex: 'invoiceName',
            align: 'center',
            width: 180,
            fixed: 'left'
        },
        {
            title: '纳税人识别号',
            dataIndex: 'invoiceNumber',
            align: 'center',
            width: 180
        },
        {
            title: '公司地址',
            dataIndex: 'invoiceOrgaddress',
            align: 'center',
            width: 180
        },
        {
            title: '联系电话',
            dataIndex: 'invoiceOrgtel',
            align: 'center',
            width: 180
        },
        // {
        //     title: '开户行',
        //     dataIndex: 'invoiceBank',
        //     align: 'center',
        //     width: 180
        // },
        // {
        //     title: '开户行账号',
        //     dataIndex: 'invoiceBanknumber',
        //     align: 'center',
        //     width: 180
        // },
        {
            title: '操作',
            dataIndex: 'option',
            align: 'center',
            width: 100,
            // fixed: 'right',
            render: (_value, record) => {
                return (
                    <Space size={5}>
                        <Button type="primary" size="small" onClick={() => {
                            editInvoiceInfoId.current = record.invoiceId;
                            setIsInvoiceInfoEditOpen(true);
                        }}><EditOutlined /></Button>
                        <Popconfirm
                            placement="right"
                            title={false}
                            description="确定删除吗？"
                            okText="确定"
                            cancelText="取消"
                            onConfirm={() => {
                                deleteInvoice(record.invoiceId);
                                // del<any>({
                                //     messageApi,
                                //     url: `/api/invoice-info/remove/${record.invoiceId}`,
                                //     onSuccess() {
                                //         messageApi.success('删除成功');
                                //         getData();
                                //     }
                                // })
                            }}
                        >
                            <Button type="primary" size="small" danger><DeleteOutlined /></Button>
                        </Popconfirm>
                    </Space>
                )
            }
        },
    ]
    const globalContext = useContext(GlobalContext);
    const getData = async () => {

        try {
            const res: any = await getInvoiceList(globalContext.user.userId, { page: page, rows: 20 })
            // console.log(res);
            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)
            }
        }
        // get<IListPage<DataType>>({
        //     messageApi,
        //     url: '/api/invoice-info/listpage/self',
        //     config: {
        //         params: {
        //             page: page,
        //             rows: 20
        //         }
        //     },
        //     onSuccess({data}) {
        //         setPage(data.page);
        //         setTotal(data.total);
        //         setDataArray(data.rows);
        //     }
        // })
    }
    const deleteInvoice = async (id: string) => {
        try {
            await deleteInvoiceInfo(id)
            // console.log(res);
            messageApi.success('删除成功');
            getData();
        } 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]);
    return (
        <>
            <div className="invoice-list-container">
                <div className="mod-list">
                    <div className="table-btn-group" style={{ marginBottom: '15px' }}>
                        <Button value="small" onClick={() => {
                            setIsInvoiceInfoSaveOpen(true);
                        }}><PlusOutlined /> 新增</Button>
                    </div>
                    {dataArray.length > 0
                        ? <>
                            <Table
                                rowSelection={
                                    {
                                        type: 'radio',
                                        onChange: (_selectedRowKeys, selectedRows) => {
                                            selectedInvoice.current = selectedRows[0];
                                        },

                                    }
                                }

                                columns={columns} dataSource={dataArray} pagination={
                                    {
                                        pageSize: 20,
                                        total: total,
                                        onChange: (currentPage) => {
                                            setPage(currentPage);
                                        }
                                    }
                                } scroll={{ y: 500 }} bordered key="dataTable" rowKey="invoiceId"

                            />
                        </> :
                        <>
                            <div style={{
                                width: '100%', height: '200px', display: 'flex', justifyContent: 'center', alignItems: 'center', fontSize: '20px'
                            }}>
                                <Empty description='暂无开票信息,请添加' />
                            </div>
                        </>
                    }
                    {/* <Table
                        rowSelection={
                            {
                                type: 'radio',
                                onChange: (_selectedRowKeys, selectedRows) => {
                                    selectedInvoice.current = selectedRows[0];
                                },

                            }
                        }

                        columns={columns} dataSource={dataArray} pagination={
                            {
                                pageSize: 20,
                                total: total,
                                onChange: (currentPage) => {
                                    setPage(currentPage);
                                }
                            }
                        } scroll={{ y: 500 }} bordered key="dataTable" rowKey="invoiceId"

                    /> */}
                </div>
                <Flex justify="center">
                    <Space size={5}>
                        <Button type="primary"
                            style={{ backgroundColor: 'var(--color-primary)' }}
                            onClick={() => {
                                if (!selectedInvoice.current) {
                                    messageApi.error('请选择开票信息');
                                    return;
                                }
                                props.handleOk(selectedInvoice.current);
                            }}
                        >确定</Button>
                        <Button type="default" onClick={() => {
                            props.handleCancel();
                        }}>关闭</Button>
                    </Space>
                </Flex>
            </div>
            <Modal open={isInvoiceInfoSaveOpen}
                title="新增"
                footer={false}
                onCancel={() => {
                    setIsInvoiceInfoSaveOpen(false)
                }}
                destroyOnClose
            >
                <InvoiceInfoSave
                    handleOk={() => {
                        getData();
                        setIsInvoiceInfoSaveOpen(false);
                    }}
                    handleCancel={() => {
                        setIsInvoiceInfoSaveOpen(false);
                    }}
                />
            </Modal>
            <Modal open={isInvoiceInfoEditOpen}
                title="编辑"
                footer={false}
                onCancel={() => {
                    setIsInvoiceInfoEditOpen(false)
                }}
            >
                <InvoiceInfoEdit
                    invoiceId={editInvoiceInfoId.current}
                    handleOk={() => {
                        getData();
                        setIsInvoiceInfoEditOpen(false);
                    }}
                    handleCancel={() => {
                        setIsInvoiceInfoEditOpen(false);
                    }}
                />
            </Modal>
            {messageContext}
        </>
    );
}