import { useRef, useState, useEffect } from 'react';
import { connect, history } from '@umijs/max';
import type { ActionType, ProFormInstance } from '@ant-design/pro-components';
import {
    ProTable, TableDropdown
} from '@ant-design/pro-components';
import { Button, Space, ConfigProvider, message, Popconfirm, Modal } from 'antd';
import { GetActivityaddressList, PostActivityExportUsers, PostActivityaddressDel } from '@/apis/api';
import { Imageprefix } from '@/constants';

const PagesMainActivityListTable: React.FC = ({ dispatch, openModel, getId }: any) => {
    const actionRef = useRef<ActionType>();
    const [list, setList] = useState<object[]>([])
    const [total, setTotal] = useState<number>(0)
    const [page, setPage] = useState<number>(1)
    const [pageSize, setPageSize] = useState<number>(10)
    const [ids, setIds] = useState<number[]>([])

    const setId = (id: number) => {
        getId(id)
    }

    useEffect(() => {
        if (!openModel.openModal) {
            actionRef.current?.reload();
        }
    }, [openModel.openModal])

    return (
        <>
            <ConfigProvider
                theme={{
                    token: {
                        colorPrimary: '#4FBE70',
                        colorLink: '#4FBE70',
                    }
                }}
            >
                <ProTable
                    scroll={{ y: 480, x: 'auto' }}
                    bordered={true}
                    actionRef={actionRef}
                    dataSource={list}
                    search={{ span: 6, labelWidth: 'auto' }}
                    tableAlertRender={({
                        selectedRowKeys,
                        selectedRows,
                        onCleanSelected,
                    }) => {
                        setIds(selectedRows)
                        return (
                            <Space size={24}>
                                <span>
                                    已选 {selectedRows.length} 项
                                    <a style={{ marginInlineStart: 8 }} onClick={onCleanSelected}>
                                        取消选择
                                    </a>
                                </span>
                            </Space>
                        );
                    }}
                    tableAlertOptionRender={() => {
                        return (
                            <Space>
                                <Button danger type="primary" onClick={() => {
                                    Modal.confirm({
                                        title: '批量删除',
                                        content: '确定要删除所选的数据吗',
                                        onOk() {
                                            const promises = ids.map(item => {
                                                return PostActivityaddressDel({ id: item.id });
                                            });

                                            // 等待所有请求完成
                                            Promise.all(promises)
                                                .then(() => {
                                                    message.success('批量删除成功');
                                                    actionRef.current?.clearSelected();
                                                    actionRef.current?.reload();
                                                })
                                                .catch(error => {
                                                    console.error('批量删除成功:', error);
                                                    message.error('批量删除成功');
                                                });

                                        },
                                        onCancel() {
                                            console.log('Cancel');
                                        },
                                        okText: '确定',
                                        cancelText: '取消',
                                        centered: true
                                    });
                                }}>
                                    批量删除
                                </Button>,
                            </Space>
                        );
                    }}
                    rowSelection={{
                        type: 'checkbox'
                    }}
                    columns={[{
                        title: 'ID',
                        dataIndex: 'id',
                        width: 200,
                        search: false,
                    },
                    {
                        title: '地址',
                        dataIndex: 'address',
                        width: 200,
                        search: false
                    },
                    {
                        title: '地址分类',
                        dataIndex: 'cate',
                        valueType: 'select',
                        width: 200,
                        valueEnum: {
                            '菊城人才': {
                                text: '菊城人才',
                            },
                            '移动': {
                                text: '移动',
                            },
                            '村镇银行': {
                                text: '村镇银行',
                            },
                            '电信': {
                                text: '电信',
                            },
                            '联通': {
                                text: '联通',
                            },
                        },
                    },
                    {
                        title: '审核账号',
                        dataIndex: 'audit_mobile',
                        ellipsis: true,
                        width: 200,
                        search: false
                    },
                    {
                        title: '审核人',
                        dataIndex: 'contact_person',
                        width: 200,
                        search: false
                    },
                    {
                        title: '操作',
                        key: 'option',
                        valueType: 'option',
                        render: (_, record, action) => [
                            <Button key='1' type='link' onClick={() => {
                                setId(record.id)
                                dispatch({ type: 'openModel/getOpenModal', payload: true })
                            }}>编辑</Button>,
                            <Popconfirm
                                title="是否删除"
                                onConfirm={(e) => {
                                    PostActivityaddressDel({ id: record.id }).then(res => {
                                        message.success('删除成功')
                                        actionRef.current?.reload();
                                    })
                                }}
                                okText="删除"
                                cancelText="取消"
                            >
                                <Button danger type='link'>删除</Button>
                            </Popconfirm>
                        ],
                    },
                    ]}
                    rowKey="id"
                    pagination={{
                        current: page,
                        pageSize: pageSize,
                        showSizeChanger: true,
                        total: total,
                        pageSizeOptions: [9, 18, 27, 99],
                        onChange(page, pageSize) {
                            setPage(page)
                            setPageSize(pageSize)
                        },
                        onShowSizeChange(current, size) {
                            setPage(current)
                            setPageSize(size)
                        }
                    }}
                    request={async (params = {} as Record<string, any>) =>
                        GetActivityaddressList({
                            page: page,
                            pagesize: pageSize,
                            sort: 'id',
                            sortby: 'desc',
                            keyword: params.name,
                            cate: params.cate

                        }).then(res => {
                            setList(res.data.addresss)
                            setTotal(res.data.total)
                        })
                    }
                    headerTitle="活动门店"
                    toolBarRender={() => [
                        <Button type="primary" onClick={() => {
                            message.info('数据导出需要时间，请耐心等待')
                            PostActivityExportUsers().then(res => {
                                let url = Imageprefix + res.data.excel_url;
                                window.open(url);
                                message.info('数据导出完毕')
                            })
                        }}>
                            导出数据
                        </Button>,
                        <Button type="primary" onClick={() => {
                            dispatch({ type: 'openModel/getOpenModal', payload: true })
                        }}>
                            添加活动门店
                        </Button>
                    ]}
                />
            </ConfigProvider>
        </>
    );
};


export default connect(({ openModel }: any) => ({
    openModel
}))(PagesMainActivityListTable);
