import { useAjax } from "@/Hook/useAjax"
import { PlayerListProps, getPlayerListApi, getUserInfotApi, getUserUpdateApi, interdictionGamerApi } from "@/services/gameData/player"
import React, { useEffect, useState } from "react"
import columns12 from "./tableConfig"
import TableData from "../../components/TableData"
import QueryForm from "@/components/QueryForm"
import moment from "moment"
import { getPresetsRanking } from "@/components/QueryForm/const"
import { message } from "antd"
import ExportH5Modal from "./exportH5Modal"
import Look from "./look"

let ajax: any = null, ajax1: any = null
const List: React.FC = () => {

    /************************/
    const [queryForm, setQueryForm] = useState<PlayerListProps>({ pageNum: 1, pageSize: 50, sourceSystem: 'ZX_ONE' })
    const [lookShow, setLookShow] = useState<boolean>(false) // 新增标签控制弹窗
    const [exportData, setExportData] = useState<any>({})
    const [exportShow, setExportShow] = useState<boolean>(false)
    const getPlayerList = useAjax((params) => getPlayerListApi(params))
    ajax = getPlayerList
    const getUserInfo = useAjax((params) => getUserInfotApi(params))
    ajax1 = getUserInfo
    const interdictionGamer = useAjax((params) => interdictionGamerApi(params))
    const getUserUpdate = useAjax((params) => getUserUpdateApi(params))
    /************************/

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


    // 查看详情
    const lookHandle = (data: any) => {
        setLookShow(true)
        getUserInfo.run(data)
    }

    //编辑玩家按钮
    const exportH5 = (data: any) => {
        setExportData({
            username: data?.username,
            mobile: data?.mobile,
            userId: data.id
        })
        setExportShow(true)
    }

    // 封禁
    const interdictionHandle = (userId: number, status: number) => {

        interdictionGamer.run({ userId, status }).then(res => {
            if (res) {
                message.success(status === 1 ? '封禁成功！' : '解封成功！');
                ajax.refresh();
            } else {
                message.error(res.msg)
            }
        })
    }

    // 编辑确定发送
    const editUser = (params: any) => {
        Object.keys(params).forEach(key => {
            if (!params[key]) {
                delete params[key]
            }
        })
        getUserUpdate.run(params).then(res => {
            if (res) {
                message.success('编辑成功！')
                ajax.refresh()//重新获取用户列表
                ajax1.refresh()//重新获取详情列表
            } else {
                message.error(res.msg)
            }
        })
    }
    return <div>
        <TableData
            leftChild={<QueryForm
                initialValues={{ sourceSystem: 'ZX_ONE' }}
                onChange={(data: any) => {
                    const { gameUserId, username, gameClassify, regStartDay, regEndDay, userLastRegTime, rechargeDay, regPayIntervalTime, userStatus, agentId, roleCount, ...par } = data
                    let newQueryForm = JSON.parse(JSON.stringify(queryForm))
                    newQueryForm.pageNum = 1
                    newQueryForm.userId = gameUserId
                    newQueryForm.userName = username
                    newQueryForm.gameCategoryId = gameClassify
                    newQueryForm.status = userStatus
                    newQueryForm.channelId = agentId

                    if (regStartDay && regEndDay) {
                        newQueryForm.beginDate = regStartDay
                        newQueryForm.endDate = regEndDay
                    } else {
                        delete newQueryForm.beginDate
                        delete newQueryForm.endDate
                    }

                    if (userLastRegTime) {
                        newQueryForm['userLastRegTime'] = moment(userLastRegTime).format('YYYY-MM-DD')
                    } else {
                        delete newQueryForm['userLastRegTime']
                    }

                    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 (regPayIntervalTime?.length > 0 && (regPayIntervalTime[0] || regPayIntervalTime[1])) {
                        newQueryForm.regPayIntervalTimeMin = regPayIntervalTime[0]
                        newQueryForm.regPayIntervalTimeMax = regPayIntervalTime[1]
                    } else {
                        delete newQueryForm.regPayIntervalTimeMin
                        delete newQueryForm.regPayIntervalTimeMax
                    }

                    if (roleCount?.length > 0 && (roleCount[0] || roleCount[1])) {
                        newQueryForm.roleCountMin = roleCount[0]
                        newQueryForm.roleCountMax = roleCount[1]
                    } else {
                        delete newQueryForm.roleCountMin
                        delete newQueryForm.roleCountMax
                    }
                    setQueryForm({ ...newQueryForm, ...par })
                }}
                isSource
                isGameUserId
                isUserName
                isNickname
                isMobile
                isRegIp
                isIsAuth
                isIsBindMobile
                isCpId
                isGameId
                isBGGameClassify
                isRegDay={{ ranges: getPresetsRanking() }}
                rechargeDay={{ ranges: getPresetsRanking() }}
                isIsRecharge
                isUserStatus
                isAgentId
                isAccountId
                isSysUserId
                isCreateRole
                isGameRoleName
                isPayIntervalTime={{ tips: '充值距注册时间区间(分钟)' }}
                isRoleCount={{ tips: '每个账号角色数量区间' }}
                isUserLastPitcherId
                isUserLastRegAgentId
                isUserLastRegTime
            />}
            scroll={{ x: 1000, y: 600 }}
            ajax={getPlayerList}
            fixed={{ left: 1, right: 2 }}
            dataSource={getPlayerList?.data?.records}
            page={getPlayerList?.data?.current || 1}
            pageSize={getPlayerList?.data?.size || 20}
            total={getPlayerList?.data?.total || 0}
            title='玩家列表'
            onChange={(props: any) => {
                console.log('props--->', props)
                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 })
            }}
            config={columns12(lookHandle, exportH5, interdictionHandle)}
            configName={'玩家列表'}
        />

        {exportShow && <ExportH5Modal initialValues={exportData} visible={exportShow} onClose={() => { setExportShow(false); setExportData({}) }} onChange={() => { setExportShow(false); setExportData({}); ajax.refresh() }} />}
        {/* 查看详情 */}
        {lookShow && <Look visible={lookShow} onClose={() => { setLookShow(false) }} onChange={(params: any) => { editUser(params) }} userInfo={getUserInfo?.data || null} />}
    </div>
}

export default List