import {Button, Dropdown, Flex, MenuProps, Modal, Popconfirm, Space, Table, TableProps, Tag} from "antd";
import {PlusOutlined} from "@ant-design/icons";
import {useEffect, useRef, useState} from "react";
import {get, put} from "../../util/AjaxUtils.ts";
import {IListPage} from "../../interfaces/listpage/IListPage.ts";
import useMessage from "antd/es/message/useMessage";
import InvoiceSave from "./InvoiceSave.tsx";
import InvoiceEdit from "./InvoiceEdit.tsx";
import InvoiceShow from "./InvoiceShow.tsx";

enum InvoiceStatusEnum {
    PENDING = 'PENDING',
    COMPLETE = 'COMPLETE',
    FAILED = 'FAILED',
    CANCEL = 'CANCEL',
}

type DataType = {
    examineOpinion: string;
    examineUserId: string;
    examineUserUsername: string;
    gmtCreate: string;
    gmtExamine: string;
    invoiceAccount: string;
    invoiceAddress: string;
    invoiceAmount: number;
    invoiceBank: string;
    invoiceFileList: string[];
    invoiceFiles: string;
    invoiceId: string;
    invoiceNo: string;
    invoiceNote: string;
    invoicePhone: string;
    invoiceStatus: InvoiceStatusEnum;
    invoiceTitle: string;
    orderIds: string[];
}

export default function InvoiceList() {
    const [messageApi, messageContext] = useMessage();
    const [page, setPage] = useState(1);
    const [total, setTotal] = useState(0);
    const [dataArray, setDataArray] = useState<DataType[]>([]);
    const [isSaveModalOpen, setIsSaveModalOpen] = useState(false);
    const [isEditModalOpen, setIsEditModalOpen] = useState(false);
    const [isShowModalOpen, setIsShowModalOpen] = useState(false);
    const invoiceId = useRef('');

    const columns: TableProps<DataType>['columns'] = [
        {
            title: '名称',
            dataIndex: 'invoiceTitle',
            align: 'center',
            width: 180
        },
        {
            title: '纳税人识别号',
            dataIndex: 'invoiceNo',
            align: 'center',
            width: 180
        },
        {
            title: '地址',
            dataIndex: 'invoiceAddress',
            align: 'center',
            width: 180
        },
        {
            title: '电话',
            dataIndex: 'invoicePhone',
            align: 'center',
            width: 180
        },
        {
            title: '开户行',
            dataIndex: 'invoiceBank',
            align: 'center',
            width: 180
        },
        {
            title: '开户行账号',
            dataIndex: 'invoiceAccount',
            align: 'center',
            width: 180
        },
        {
            title: '金额',
            dataIndex: 'invoiceAmount',
            align: 'center',
            width: 160,
            render: (value) => {
                return (value / 100).toFixed(2)
            }
        },
        {
            title: '备注',
            dataIndex: 'invoiceNote',
            align: 'center',
            width: 180
        },
        {
            title: '创建时间',
            dataIndex: 'gmtCreate',
            align: 'center',
            width: 180
        },
        {
            title: '状态',
            dataIndex: 'invoiceStatus',
            align: 'center',
            width: 100,
            fixed: 'right',
            render: (value) => {
                if(value === InvoiceStatusEnum.PENDING) {
                    return <Tag color="magenta">待审核</Tag>
                }
                if(value === InvoiceStatusEnum.COMPLETE) {
                    return <Tag color="green">已开票</Tag>
                }
                if(value === InvoiceStatusEnum.FAILED) {
                    return <Tag color="red">失败</Tag>
                }
                if(value === InvoiceStatusEnum.CANCEL) {
                    return <Tag color="cyan">已取消</Tag>
                }
            }
        },
        {
            title: '操作',
            dataIndex: 'operate',
            align: 'center',
            width: 120,
            fixed: 'right',
            render: (_value, record) => {
                if(record.invoiceStatus === InvoiceStatusEnum.PENDING) {
                    return <Flex justify="center">
                        <Space>
                            <Button type="link" style={{
                                color: 'var(--color-dark)',
                                padding: '0'
                            }} onClick={() => {
                                invoiceId.current = record.invoiceId;
                                setIsShowModalOpen(true);
                            }}>查看</Button>
                            <Popconfirm
                                title={false}
                                placement="right"
                                description="确定取消吗?"
                                okText="确定"
                                cancelText="取消"
                                okButtonProps={{
                                    style: {
                                        backgroundColor: 'var(--color-primary)'
                                    }
                                }}
                                onConfirm={() => {
                                    put<any>({
                                        messageApi,
                                        url: `/api/invoice/update-cancel/${record.invoiceId}`,
                                        onSuccess() {
                                            messageApi.success('取消成功');
                                            getData();
                                        }
                                    })
                                }}
                            >
                                <Button type="link" danger style={{
                                    padding: '0'
                                }}>取消</Button>
                            </Popconfirm>

                        </Space>
                    </Flex>
                }
                if(record.invoiceStatus === InvoiceStatusEnum.CANCEL) {
                    return <Button type="link" style={{
                        padding: '0'
                    }} onClick={() => {
                        invoiceId.current = record.invoiceId;
                        setIsEditModalOpen(true);
                    }}>编辑</Button>
                }
                if(record.invoiceStatus == InvoiceStatusEnum.COMPLETE) {
                    const items: MenuProps['items'] = [];
                    record.invoiceFileList.forEach((item, index) => {
                        items.push({
                            key: index,
                            label: (
                                <a href={item} download target="_blank">下载发票{index + 1}</a>
                            )
                        });
                    })
                    return (
                        <Dropdown menu={{ items }} placement="bottom" arrow>
                            <Button type="link">下载发票</Button>
                        </Dropdown>
                    )
                }
            }
        },
    ]

    const getData = () => {
        get<IListPage<DataType>>({
            messageApi,
            url: '/api/invoice/listpage/self',
            config: {
                params: {
                    page: page,
                    rows: 20
                }
            },
            onSuccess({data}) {
                setPage(data.page);
                setTotal(data.total);
                setDataArray(data.rows);
            }
        })
    }

    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={() => {
                            setIsSaveModalOpen(true);
                        }}><PlusOutlined/> 新增</Button>
                    </div>
                    <Table columns={columns} dataSource={dataArray} pagination={
                        {
                            pageSize: 20,
                            total: total,
                            onChange: (currentPage) => {
                                setPage(currentPage); 
                            },
                        }
                    } scroll={{y: 500}} bordered key="dataTable" rowKey="invoiceId"/>
                </div>
            </div>
            <Modal open={isSaveModalOpen}
                   title="申请开票"
                   footer={false}
                   onCancel={() => setIsSaveModalOpen(false)}
            >
                <InvoiceSave
                    handleOk={() => {
                        getData();
                        setIsSaveModalOpen(false);
                    }}
                    handleCancel={() => {
                        setIsSaveModalOpen(false);
                    }}
                />
            </Modal>
            <Modal open={isEditModalOpen}
                   title="修改开票信息"
                   footer={false}
                   onCancel={() => setIsEditModalOpen(false)}
            >
                <InvoiceEdit
                    invoiceId={invoiceId.current}
                    handleOk={() => {
                        getData();
                        setIsEditModalOpen(false);
                    }}
                    handleCancel={() => {
                        setIsEditModalOpen(false);
                    }}
                />
            </Modal>
            <Modal open={isShowModalOpen}
                   title="查看开票信息"
                   footer={false}
                   onCancel={() => setIsShowModalOpen(false)}
            >
                <InvoiceShow
                    invoiceId={invoiceId.current}
                />
            </Modal>
            {messageContext}
        </>
    )
}