import { useAjax } from "@/Hook/useAjax"
import { RoleRechargeRankingProps, getRoleRechargeRankingListApi } from "@/services/gameData/roleOperate"
import React, { useEffect, useState } from "react"
import moment from "moment"
import TableData from "../../components/TableData"
import QueryForm from "@/components/QueryForm"
import { getPresetsRanking } from "@/components/QueryForm/const"
import columns12 from "./tableConfig"
import SendMail from "./sendMail"
import SendPack from "./sendPack"
import { Button, Space } from "antd"
import RoleCz from "./roleCz"
import Assign from "./assign"
import ChangeLog from "./changeLog"
import MsgPushModal from "./msgPushModal"
import TaskList from "./taskList"

let ajax: any = null
const RoleRechargeRanking: React.FC = () => {


    /**********************************/
    const [queryForm, setQueryForm] = useState<RoleRechargeRankingProps>({ pageNum: 1, pageSize: 50, sourceSystem: 'ZX_ONE', rechargeBeginDate: moment().format('YYYY-MM-DD'), rechargeEndDate: moment().format('YYYY-MM-DD') })
    const [data, setData] = useState<any[]>([])
    const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([])
    const [sendEmailvisible, setSendEmailVisible] = useState<boolean>(false)
    const [sendPackvisible, setSendPackVisible] = useState<boolean>(false)
    const [assignvisible, setAssignVisible] = useState<boolean>(false)
    const [changeLogVisible, setChangeLogVisible] = useState<boolean>(false)
    const [czvisible, setCzVisible] = useState<boolean>(false)
    const [msgVisible, setMsgVisible] = useState<boolean>(false)
    const getRoleRechargeRankingList = useAjax((params) => getRoleRechargeRankingListApi(params))
    ajax = getRoleRechargeRankingList
    /**********************************/

    useEffect(() => {
        getRoleRechargeRankingList.run(queryForm)
    }, [queryForm])

    const sendEmail = (data: any[]) => {
        setData(data)
        setSendEmailVisible(true)
    }

    const sendPack = (data: any[]) => {
        setData(data)
        setSendPackVisible(true)
    }

    const handleIsTrue = (value: string, data: any, type: string) => {
        switch (type) {
            case 'isChangeGameType': // 是否转端
                break
            case 'isAddCorpWechat': // 是否添加企微
                break
            case 'isRemoveGame': // 是否退游
                break
            case 'isWakeUp': // 是否唤醒
                break
        }
    }

    const handleSave = (row: any) => {
        // const hide = message.loading(`广告“${row.adgroupId}”广告名称修改成<${row.adgroupName}>,修改中`, 0, () => {
        //     message.success('修改成功');
        // });
        // editAdqAdgroups.run({ adgroupIds: [row.adgroupId], adgroupName: row.adgroupName }).then(res => {
        //     message.success('修改广告名称成功')
        //     listAjax.refresh()
        //     hide()
        // })
    }

    const roleHandle = (data: any[]) => {
        setData(data)
        setCzVisible(true)
    }

    // 指派
    const assignHandle = (data: any[]) => {
        setData(data)
        setAssignVisible(true)
    }

    const changeLog = (data: any[]) => {
        setData(data)
        setChangeLogVisible(true)
    }

    return <div>
        <TableData
            czChild={<Space>
                <Button type="primary" size="small" disabled={selectedRowKeys.length === 0} onClick={() => sendPack(selectedRowKeys)}>批量发送礼包</Button>
                <Button type="primary" size="small" disabled={selectedRowKeys.length === 0} onClick={() => sendEmail(selectedRowKeys)}>批量发送邮件</Button>
                {/* <Button type="primary" size="small" disabled={selectedRowKeys.length === 0} onClick={() => roleHandle(selectedRowKeys)}>批量角色操作</Button> */}
                <Button type="primary" size="small" disabled={selectedRowKeys.length === 0} onClick={() => assignHandle(selectedRowKeys)}>批量指派</Button>
                <Button type="primary" size="small" disabled={selectedRowKeys.length === 0} onClick={() => setMsgVisible(true)}>游戏内消息推送</Button>
                <Button type="primary" danger size="small" disabled={selectedRowKeys.length === 0} onClick={() => setSelectedRowKeys([])}>清空选择</Button>
                <TaskList sourceSystem={queryForm.sourceSystem} />
            </Space>}
            leftChild={<QueryForm
                initialValues={{ sourceSystem: 'ZX_ONE', rechargeDay: [moment(), moment()] }}
                onChange={(data: any) => {
                    setSelectedRowKeys([])
                    const { rechargeDay, createRoleDay, superParentGameId, mobile, regPayIntervalTime, LastRechargeDay, lastActiveTime, agentId, regStartDay, regEndDay, ...par } = data
                    let newQueryForm = JSON.parse(JSON.stringify(queryForm))
                    newQueryForm.pageNum = 1
                    newQueryForm.phone = mobile
                    newQueryForm.superGameId = superParentGameId
                    newQueryForm.agentIds = agentId
                    newQueryForm.registerTimeMin = regStartDay
                    newQueryForm.registerTimeMax = regEndDay
                    if (rechargeDay && rechargeDay?.length === 2) {
                        newQueryForm['rechargeBeginDate'] = moment(rechargeDay[0]).format('YYYY-MM-DD')
                        newQueryForm['rechargeEndDate'] = moment(rechargeDay[1]).format('YYYY-MM-DD')
                    } else {
                        delete newQueryForm['rechargeBeginDate']
                        delete newQueryForm['rechargeEndDate']
                    }
                    if (createRoleDay && createRoleDay?.length === 2) {
                        newQueryForm['createRoleBeginDate'] = moment(createRoleDay[0]).format('YYYY-MM-DD')
                        newQueryForm['createRoleEndDate'] = moment(createRoleDay[1]).format('YYYY-MM-DD')
                    } else {
                        delete newQueryForm['createRoleBeginDate']
                        delete newQueryForm['createRoleEndDate']
                    }
                    if (lastActiveTime && lastActiveTime?.length === 2) {
                        newQueryForm['lastActiveTimeMin'] = moment(lastActiveTime[0]).format('YYYY-MM-DD')
                        newQueryForm['lastActiveTimeMax'] = moment(lastActiveTime[1]).format('YYYY-MM-DD')
                    } else {
                        delete newQueryForm['lastActiveTimeMin']
                        delete newQueryForm['lastActiveTimeMax']
                    }
                    if (LastRechargeDay && LastRechargeDay?.length === 2) {
                        newQueryForm['roleLastPayTimeMin'] = moment(LastRechargeDay[0]).format('YYYY-MM-DD')
                        newQueryForm['roleLastPayTimeMax'] = moment(LastRechargeDay[1]).format('YYYY-MM-DD')
                    } else {
                        delete newQueryForm['roleLastPayTimeMin']
                        delete newQueryForm['roleLastPayTimeMax']
                    }
                    if (regPayIntervalTime?.length > 0 && (regPayIntervalTime[0] || regPayIntervalTime[1])) {
                        newQueryForm.totalRechargeMin = regPayIntervalTime[0]
                        newQueryForm.totalRechargeMax = regPayIntervalTime[1]
                    }
                    setQueryForm({ ...newQueryForm, ...par })
                }}
                isSource
                rechargeDay={{ ranges: getPresetsRanking() }}
                isCreateRoleDay={{ ranges: getPresetsRanking() }}
                LastRechargeDay={{}}
                isSuperParentGameId
                isParentIds
                isGameIds
                isIsChange
                isMobile
                isSysUserId
                isGameRoleName
                isGameRoleId
                isIsSendMail
                isWeChatCompany
                isWeChat
                isCustomerServerId
                isOperatorId
                isGsId
                isVipLevel
                isServerIds
                isIsMergeServer
                isRemoveGame
                isRemoveGameForSystem
                isPayIntervalTime={{ tips: '角色累计充值金额区间（单位：元）' }}
                isAddCorpWechat
                isWakeUp
                isUserPhoneStatus
                isOs
                isRechargeAmountWithin24h
                isRechargeTotalAmountWithin24h
                isLastActiveTime={{}}
                isAgentId
                isRegisterType
                isRegDay={{}}
                isRoleLevel
                isIpCity
                isIpProv
                isLoginIpCity
                isLoginIpProv
            />}
            scroll={{ x: 1000, y: 600 }}
            ajax={getRoleRechargeRankingList}
            fixed={{ left: 2, right: 1 }}
            dataSource={getRoleRechargeRankingList?.data?.records?.map((item: any, index: number) => ({ ...item, id: Number(queryForm.pageNum.toString() + index.toString()) }))}
            page={getRoleRechargeRankingList?.data?.current || 1}
            pageSize={getRoleRechargeRankingList?.data?.size || 20}
            total={getRoleRechargeRankingList?.data?.total || 0}
            title='角色充值排行榜'
            tips={<div>
                角色VIP等级档位：(根据角色累计充值划分等级，上限不包含原则)
                <div>1档——【0，2000】</div>
                <div>2档——【2000，5000】</div>
                <div>3档——【5000，10000】</div>
                <div>4档——【10000，20000】</div>
                <div>5档——【20000，50000】</div>
                <div>6档——【50000，+∞】</div>
            </div>}
            onChange={(props: any) => {
                let { pagination, sortData } = props
                let { current, pageSize } = pagination
                let newQueryForm = JSON.parse(JSON.stringify(queryForm))
                if (sortData && sortData?.order) {
                    newQueryForm['sortType'] = sortData?.order === 'ascend' ? 'asc' : 'desc'
                    newQueryForm['sortFiled'] = sortData?.field
                } else {
                    delete newQueryForm['sortType']
                    delete newQueryForm['sortFiled']
                }
                newQueryForm.pageNum = current
                newQueryForm.pageSize = pageSize
                setQueryForm({ ...newQueryForm })
            }}
            rowSelection={{
                getCheckboxProps: (record: any) => ({
                    disabled: selectedRowKeys?.length > 0 && record.role_reg_game_id !== (selectedRowKeys[0] as any).role_reg_game_id
                }),
                selectedRowKeys: selectedRowKeys.map((item: any) => item?.id.toString()),
                // onChange: (selectedRowKeys: React.Key[], selectedRows: any[]) => {
                //     setSelectedRowKeys(selectedRows)
                // },
                onSelect: (record: any, selected: boolean, selectedRows: any) => {
                    let newSelectedRowKeys: any[] = JSON.parse(JSON.stringify(selectedRowKeys))
                    if (selected) {
                        newSelectedRowKeys.push(record)
                    } else {
                        newSelectedRowKeys = newSelectedRowKeys.filter(item => item.id != record.id)
                    }
                    setSelectedRowKeys(newSelectedRowKeys)
                },
                onSelectAll: (selected: boolean, selectedRows: any, changeRows: any) => {
                    let newSelectedRowKeys: any[] = JSON.parse(JSON.stringify(selectedRowKeys))
                    let gameId = newSelectedRowKeys?.[0]?.role_reg_game_id || changeRows?.[0]?.role_reg_game_id
                    if (selected) {
                        newSelectedRowKeys = newSelectedRowKeys.concat(changeRows.filter((item: { role_reg_game_id: any }) => item.role_reg_game_id === gameId))
                    } else {
                        let changeRowsIds: any[] = changeRows.map((item: { id: any }) => item.id);
                        newSelectedRowKeys = newSelectedRowKeys.filter(item => !changeRowsIds.includes(item.id))
                    }
                    setSelectedRowKeys(newSelectedRowKeys)
                }
            }}
            config={columns12(sendEmail, sendPack, handleIsTrue, handleSave, roleHandle, assignHandle, changeLog)}
            configName={'角色充值排行榜'}
        />
        {/* 发送邮件 */}
        {sendEmailvisible && <SendMail visible={sendEmailvisible} data={data} onClose={() => { setSendEmailVisible(false) }} onChange={() => { setSendEmailVisible(false); ajax?.refresh(); setSelectedRowKeys([]) }} />}
        {/* 发送礼包 */}
        {sendPackvisible && <SendPack visible={sendPackvisible} data={data} onClose={() => setSendPackVisible(false)} onChange={() => { setSendPackVisible(false); ajax?.refresh(); setSelectedRowKeys([]) }} />}
        {/* 角色操作 */}
        {czvisible && <RoleCz visible={czvisible} data={data} onClose={() => setCzVisible(false)} onChange={() => { setCzVisible(false); ajax?.refresh(); setSelectedRowKeys([]) }} />}
        {/* 指派 */}
        {assignvisible && <Assign visible={assignvisible} data={data} onClose={() => setAssignVisible(false)} onChange={() => { setAssignVisible(false); ajax?.refresh(); setSelectedRowKeys([]) }} />}
        {/* 变更记录 */}
        {changeLogVisible && <ChangeLog data={data?.[0]} visible={changeLogVisible} onClose={() => setChangeLogVisible(false)} />}
        {/* 游戏内消息推送 */}
        {msgVisible && <MsgPushModal
            gameId={selectedRowKeys?.[0].role_reg_game_id}
            roleRechargeRankingDTO={queryForm}
            roleIds={selectedRowKeys.map(item => item.role_id)}
            visible={msgVisible}
            onClose={() => {
                setMsgVisible(false)
            }}
            onChange={() => {
                setMsgVisible(false)
                setSelectedRowKeys([])
            }}
        />}
    </div>
}

export default RoleRechargeRanking