import { useAjax } from "@/Hook/useAjax"
import { delSendEmailLogApi, getSendEmailListApi, getSendEmailLogProps } from "@/services/gameData/roleOperate"
import { Button, DatePicker, Popconfirm, Space, Table, Tag, message } from "antd"
import React, { useEffect, useState } from "react"
import { columnsSendEmailLog } from "./tableConfig"
import './index.less'
import moment from "moment"
import SendMail from "./sendMail"

interface Props {
    data: any
    onChange?: () => void
}
const SendEmailTable: React.FC<Props> = ({ data, onChange }) => {

    /*********************************/
    const [queryForm, setQueryForm] = useState<getSendEmailLogProps>({ pageNum: 1, pageSize: 20 })
    const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([])
    const [sendEmialvisible, setSendEmialVisible] = useState<boolean>(false)
    const [ids, setIds] = useState<string[]>([])
    const getSendEmailList = useAjax((params) => getSendEmailListApi(params))
    const delSendEmailLog = useAjax((params) => delSendEmailLogApi(params))
    /*********************************/

    useEffect(() => {
        getSendEmailList.run({
            ...queryForm,
            gameId: data.role_reg_game_id,
            roleId: data.role_id,
            serverId: data.server_id,
            userId: data.association_user_id
        })
    }, [queryForm, data])

    const del = (ids: any[]) => {
        delSendEmailLog.run(ids.toString()).then(res => {
            if (res) {
                onChange?.()
                getSendEmailList.refresh()
                message.success('删除成功')
            }
        })
    }

    const update = (ids: any[]) => {
        setIds(ids)
        setSendEmialVisible(true)
    }

    return <Space style={{ width: '100%' }} direction="vertical">
        <Space>
            <DatePicker.RangePicker
                size="small"
                showTime
                allowClear
                placeholder={['发送开始时间', '发送结束时间']}
                value={queryForm?.startDateTime && queryForm?.endDateTime ? [moment(queryForm?.startDateTime), moment(queryForm?.endDateTime)] as any : undefined}
                onChange={(e) => {
                    if (e && e.length === 2) {
                        setQueryForm({ ...queryForm, pageNum: 1, startDateTime: moment(e[0]).format('YYYY-MM-DD HH:mm:ss'), endDateTime: moment(e[1]).format('YYYY-MM-DD HH:mm:ss') })
                    } else {
                        setQueryForm({ ...queryForm, startDateTime: undefined, endDateTime: undefined })
                    }
                }}
            />
            <Button type="primary" size="small" onClick={() => { update(selectedRowKeys) }} disabled={selectedRowKeys.length === 0}>批量更新</Button>
            <Popconfirm
                title="确定删除?"
                disabled={selectedRowKeys.length === 0}
                onConfirm={() => { del(selectedRowKeys.map(item => item.id)) }}
            >
                <Button danger size="small" disabled={selectedRowKeys.length === 0}>批量删除</Button>
            </Popconfirm>
        </Space>
        <Table
            dataSource={getSendEmailList?.data?.records}
            columns={columnsSendEmailLog(update, del)}
            loading={getSendEmailList.loading}
            scroll={{ x: 380, y: 300 }}
            className="uuTable"
            rowKey={'id'}
            pagination={
                {
                    total: getSendEmailList?.data?.total || 0,//总共多少条数据,服务器给,设置后分页自动计算页数
                    current: getSendEmailList?.data?.current || 1,//当前页数,需state控制配合翻页
                    pageSize: getSendEmailList?.data?.size || 20,
                    defaultCurrent: 1,//默认初始的当前页数
                    pageSizeOptions: ['10', '20', '30', '40', '50', '60', '70', '80', '90', '100'],
                    showTotal: (total) => <Tag color="cyan">总共{total}数据</Tag>,
                    showSizeChanger: true, //手动开启条数筛选器，默认超过50条开启
                    size: 'small',//设置分页尺寸
                    onChange: (page: number, pageSize: number) => {
                        setQueryForm({ ...queryForm, pageNum: page, pageSize })
                    },
                    showLessItems: true
                }
            }
            rowSelection={{
                selectedRowKeys: selectedRowKeys.map(item => item?.id),
                onChange: (selectedRowKeys: React.Key[], selectedRows: any[]) => {
                    setSelectedRowKeys(selectedRows)
                },
            }}
        />

        {/* 发送礼包 */}
        {sendEmialvisible && <SendMail
            visible={sendEmialvisible}
            ids={ids as any}
            data={[data]}
            onClose={() => setSendEmialVisible(false)}
            onChange={() => {
                setSendEmialVisible(false);
                getSendEmailList?.refresh();
                setIds([])
                setSelectedRowKeys([])
            }}
        />}
    </Space>
}

export default React.memo(SendEmailTable)