import { useAjax } from "@/Hook/useAjax"
import Tables from "@/components/Tables"
import { getGameListNewApi } from "@/services/gameData"
import { getSendLogListApi, getSendMsgTaskListApi, reSendMsgByResultIdApi, reSendMsgByTaskIdApi } from "@/services/gameData/roleOperate"
import { SyncOutlined } from "@ant-design/icons"
import { Button, Modal, Select, Space, message } from "antd"
import React, { useEffect, useState } from "react"
import { columnsMsgTask, columnsMsgTaskLog } from "./tableConfig"

interface Props {
    sourceSystem?: string
}
/**
 * 消息推送任务列表
 * @returns 
 */
const TaskList: React.FC<Props> = ({ sourceSystem }) => {

    /****************************/
    const [visible, setVisible] = useState<boolean>(false)
    const [gameList, setGameList] = useState<any[]>([])
    const [gameId, setGameId] = useState<number>()
    const [taskStatus, setTaskStatus] = useState<string>()
    const [sendStatus, setSendStatus] = useState<string>()
    const [queryForm, setQueryForm] = useState<{ pageNum: number, pageSize: number }>({ pageNum: 1, pageSize: 20 })
    const [queryFormLog, setQueryFormLog] = useState<{ pageNum: number, pageSize: number }>({ pageNum: 1, pageSize: 20 })
    const [taskId, setTaskId] = useState<number>()
    const [taskName, setTaskName] = useState<string>('')
    const [visibleLog, setVisibleLog] = useState<boolean>(false)

    const getGameListNew = useAjax((params) => getGameListNewApi(params))
    const getSendMsgTaskList = useAjax((params) => getSendMsgTaskListApi(params))
    const getSendLogList = useAjax((params) => getSendLogListApi(params))
    const reSendMsgByTaskId = useAjax((params) => reSendMsgByTaskIdApi(params))
    const reSendMsgByResultId = useAjax((params) => reSendMsgByResultIdApi(params))

    /****************************/

    useEffect(() => {
        if (visible) {
            getSendMsgTaskList.run({ ...queryForm, gameId, taskStatus })
        }
    }, [queryForm, gameId, taskStatus, visible])

    useEffect(() => {
        if (taskId && visibleLog) {
            getSendLogList.run({ ...queryFormLog, taskId, sendStatus })
        }
    }, [taskId, visibleLog, queryFormLog, sendStatus])

    const open = () => {
        if (sourceSystem) {
            setVisible(true)
            getGameListNew.run({ sourceSystem }).then(res => {
                const { parentGameList } = res
                setGameList(parentGameList?.map((item: { parent_game_id: any; parent_game_name: any }) => ({ id: item.parent_game_id, name: item.parent_game_name })) || [])
            })
        } else {
            message.error('请选择数据源')
        }
    }

    /** 发送记录按钮 */
    const sendLog = (data: any) => {
        setTaskName(data.taskName)
        setTaskId(data.id)
        setVisibleLog(true)
    }
    /**重发task*/
    const reloadTask = (data: { gameId: any, taskId: any }) => {
        reSendMsgByTaskId.run(data).then(res => {
            message.success("操作成功")
            getSendMsgTaskList.refresh()
        })
    }
    /**重发result*/
    const reloadResult = (data: { resultId: any }) => {
        reSendMsgByResultId.run(data).then(res => {
            message.success("操作成功")
            getSendLogList.refresh()
        })
    }
    return <>
        <Button type="primary" size="small" onClick={open}>消息推送任务列表</Button>
        <Modal
            title={<Space>
                <strong>消息推送任务列表</strong>
                <Select
                    maxTagCount={1}
                    showSearch
                    style={{ minWidth: 140 }}
                    loading={getGameListNew.loading}
                    placeholder={'请选择游戏'}
                    filterOption={(input, option) =>
                        (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                    allowClear
                    value={gameId}
                    onChange={(e) => setGameId(e)}
                >
                    {gameList?.map((item: any) => <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>)}
                </Select>
                <Select
                    maxTagCount={1}
                    showSearch
                    style={{ minWidth: 100 }}
                    placeholder={'任务状态'}
                    filterOption={(input, option) =>
                        (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                    allowClear
                    value={taskStatus}
                    onChange={(e) => setTaskStatus(e)}
                >
                    <Select.Option value="SUCCESS_SEND">已发送</Select.Option>
                    <Select.Option value="WAIT_SEND">待发送</Select.Option>
                </Select>
                <Button type="link" icon={<SyncOutlined />} onClick={() => getSendMsgTaskList.refresh()} loading={getSendMsgTaskList.loading} />
            </Space>}
            visible={visible}
            onCancel={() => setVisible(false)}
            footer={null}
            width={900}
        >
            <Tables
                bordered
                current={queryForm.pageNum}
                pageSize={queryForm.pageSize}
                columns={columnsMsgTask(sendLog, reloadTask, reSendMsgByTaskId.loading)}
                dataSource={getSendMsgTaskList?.data?.records}
                scroll={{ x: 1000, y: 600 }}
                onChange={(pagination: any, filters: any, sortData: any) => {
                    let { current, pageSize } = pagination
                    let newQueryForm = JSON.parse(JSON.stringify(queryForm))
                    newQueryForm.pageNum = current
                    newQueryForm.pageSize = pageSize
                    setQueryForm({ ...newQueryForm })
                }}
                size="small"
                total={getSendMsgTaskList?.data?.total}
                loading={getSendMsgTaskList?.loading}
                defaultPageSize={20}
            />
        </Modal>

        {visibleLog && <Modal
            title={<Space>
                <strong>{taskName} 发送记录</strong>
                <Select
                    maxTagCount={1}
                    showSearch
                    style={{ minWidth: 100 }}
                    placeholder={'发送状态'}
                    filterOption={(input, option) =>
                        (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                    allowClear
                    value={sendStatus}
                    onChange={(e) => setSendStatus(e)}
                >
                    <Select.Option value="CP_SEND_ROLE_RESULT_SUCCESS">发送成功</Select.Option>
                    <Select.Option value="CP_SEND_ROLE_RESULT_FAIL">发送失败</Select.Option>
                </Select>
                <Button type="link" icon={<SyncOutlined />} onClick={() => getSendLogList.refresh()} loading={getSendLogList.loading} />
            </Space>}
            visible={visibleLog}
            onCancel={() => {
                setVisibleLog(false)
                setTaskId(undefined)
                setTaskName('')
            }}
            footer={null}
            width={1000}
        >
            <Tables
                bordered
                current={queryFormLog.pageNum}
                pageSize={queryFormLog.pageSize}
                columns={columnsMsgTaskLog(reloadResult, reSendMsgByResultId.loading)}
                dataSource={getSendLogList?.data?.records}
                scroll={{ x: 1000, y: 600 }}
                onChange={(pagination: any) => {
                    let { current, pageSize } = pagination
                    let newQueryForm = JSON.parse(JSON.stringify(queryFormLog))
                    newQueryForm.pageNum = current
                    newQueryForm.pageSize = pageSize
                    setQueryFormLog({ ...newQueryForm })
                }}
                size="small"
                total={getSendLogList?.data?.total}
                loading={getSendLogList?.loading}
                defaultPageSize={20}
            />
        </Modal>}
    </>
}

export default React.memo(TaskList)