import { useAjax } from "@/Hook/useAjax"
import TablePro from "@/pages/gameDataStatistics/components/TablePro"
import { getRoleLevelListApi, GetRoleLevelListProps } from "@/services/gsData"
import React, { useEffect, useState } from "react"
import moment from "moment"
import columns12 from "./tableConfig"
import QueryForm from "@/components/QueryForm"
import { Button, Space } from "antd"
import Assign from "@/pages/gameDataStatistics/roleOperate/roleRechargeRanking/assign"

/**
 * 角色等级表-仙剑
 * @returns 
 */
const XjRoleGrade: React.FC = () => {

    /****************************************/
    const [data, setData] = useState<any[]>([])
    const [assignvisible, setAssignVisible] = useState<boolean>(false)
    const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([])
    const [queryForm, setQueryForm] = useState<GetRoleLevelListProps>({
        pageNum: 1,
        pageSize: 30
    })
    const getRoleLevelList = useAjax((params) => getRoleLevelListApi(params))
    /****************************************/

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

    // 指派
    const assignHandle = (data: any[]) => {
        setData(data.map(item => ({ ...item, customer_service_id: item?.customerServiceId, oper_user_id: item?.operUserId, role_reg_game_id: item?.gameId, role_id: item?.roleId, server_id: item?.serverId, association_user_id: item?.userId, agent_id: item?.agentId })))
        setAssignVisible(true)
    }

    return <div>
        <TablePro
            czChild={<Space>
                <Button type="primary" size="small" disabled={selectedRowKeys.length === 0} onClick={() => assignHandle(selectedRowKeys)}>批量指派</Button>
            </Space>}
            leftChild={<QueryForm
                initialValues={{ superParentGameId: 12 }}
                isXjRole
                isRemark
                isGameRoleName
                isGameRoleId
                isSuperParentGameId
                isGameServerName
                isServerIds
                isCreateRoleDay={{}}
                isLastActiveTime={{ placeholder: ['等级上报时间开始', '等级上报时间结束'] }}
                isSysUserId
                isCustomerServerId
                isOperatorId
                isGsId
                onChange={(data: any) => {
                    console.log(data)
                    const { superParentGameId, createRoleDay, serverIds, regPayIntervalTime, lastActiveTime, customerServerId, operatorId, ...params } = data
                    let newQueryForm = JSON.parse(JSON.stringify(queryForm))
                    newQueryForm.pageNum = 1
                    newQueryForm.serverId = serverIds
                    newQueryForm.customerServiceId = customerServerId
                    newQueryForm.operUserId = operatorId
                    if (createRoleDay && createRoleDay?.length === 2) {
                        newQueryForm['createTimeMin'] = moment(createRoleDay[0]).format('YYYY-MM-DD')
                        newQueryForm['createTimeMax'] = moment(createRoleDay[1]).format('YYYY-MM-DD')
                    } else {
                        delete newQueryForm['createTimeMin']
                        delete newQueryForm['createTimeMax']
                    }
                    if (lastActiveTime && lastActiveTime?.length === 2) {
                        newQueryForm['levelTimeMin'] = moment(lastActiveTime[0]).format('YYYY-MM-DD')
                        newQueryForm['levelTimeMax'] = moment(lastActiveTime[1]).format('YYYY-MM-DD')
                    } else {
                        delete newQueryForm['levelTimeMin']
                        delete newQueryForm['levelTimeMax']
                    }
                    if (regPayIntervalTime?.length > 0 && (regPayIntervalTime[0] || regPayIntervalTime[1])) {
                        newQueryForm.roleLevelMin = regPayIntervalTime[0]
                        newQueryForm.roleLevelMax = regPayIntervalTime[1]
                    } else {
                        delete newQueryForm.roleLevelMin
                        delete newQueryForm.roleLevelMax
                    }
                    setQueryForm({ ...newQueryForm, ...params })
                }}
            />}
            config={columns12(assignHandle)}
            configName={'角色等级表-仙剑'}
            fixed={{ left: 2, right: 1 }}
            scroll={{ x: 1000, y: 620 }}
            title='角色等级表-仙剑'
            loading={getRoleLevelList.loading}
            ajax={getRoleLevelList}
            page={getRoleLevelList?.data?.current || 1}
            pageSize={getRoleLevelList?.data?.size || 20}
            total={getRoleLevelList?.data?.total || 0}
            dataSource={getRoleLevelList?.data?.records?.map((item: any, index: number) => ({ ...item, id: Number(queryForm.pageNum.toString() + (index + '')) }))}
            onChange={(pagination: any, _: any, sortData: any) => {
                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.pageNum
                newQueryForm.pageSize = pageSize || newQueryForm.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)
                }
            }}
        />
        {/* 指派 */}
        {assignvisible && <Assign visible={assignvisible} data={data} onClose={() => setAssignVisible(false)} onChange={() => { setAssignVisible(false); getRoleLevelList?.refresh(); setSelectedRowKeys([]) }} />}
    </div>
}

export default XjRoleGrade