import { useAjax } from "@/Hook/useAjax"
import { getPresets } from "@/components/QueryForm/const"
import { getGameChoiceListApi } from "@/services/gameData"
import { IpManageListProps, getIpManageListApi, updateBanIpApi } from "@/services/gameData/player"
import { Button, Card, Col, DatePicker, Form, Input, Row, Select, Space, message } from "antd"
import React, { useEffect, useState } from "react"
import moment from "moment"
import style from '../../components/TableData/index.less'
import Tables from "@/components/Tables"
import columnsPos from "./tableConfig"
import AddBanIp from "./addBanIp"
import { CopyOutlined, PlusOutlined } from "@ant-design/icons"

/**
 * 封禁IP管理
 * @returns 
 */
const BanIpManage: React.FC = () => {

    /*************************/
    const [form] = Form.useForm()
    const [initialValues, setInitialValues] = useState<any>({})
    const [queryFrom, setQueryForm] = useState<IpManageListProps>({ pageNum: 1, pageSize: 20 })
    const [addShow, setAddShow] = useState<boolean>(false)
    const [selectedRows, setSelectedRows] = useState<any[]>([])

    const getGameChoiceList = useAjax(() => getGameChoiceListApi())
    const getIpManageList = useAjax((params: IpManageListProps) => getIpManageListApi(params))
    const updateBanIp = useAjax((params: { ip: string, status: number }) => updateBanIpApi(params))
    /*************************/

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

    useEffect(() => {
        getIpManageList.run(queryFrom)
    }, [queryFrom])

    const onFinish = (data: any) => {
        const { banDate, ...value } = data
        let params = { ...queryFrom, ...value }
        if (banDate) {
            params.beginDate = moment(banDate[0]).format('YYYY-MM-DD')
            params.endDate = moment(banDate[1]).format('YYYY-MM-DD')
        } else {
            delete params?.beginDate
            delete params?.endDate
        }
        setQueryForm({ ...params, pageNum: 1 })
    }

    // 解封 封禁
    const handle = (data: { ip: string, status: number }) => {
        updateBanIp.run({ ip: data.ip, status: data.status === 0 ? 1 : 0 }).then(res => {
            if (res) {
                if (data.status === 0) {
                    message.success('封禁成功')
                } else {
                    message.success('解封成功')
                }
                getIpManageList.refresh()
            }
        })
    }

    return <Card
        style={{ borderRadius: 8 }}
        headStyle={{ textAlign: 'left' }}
        bodyStyle={{ padding: '5px 10px' }}
    >
        <div style={{ textAlign: 'center', fontWeight: 'bold', padding: '4px 6px 6px', fontSize: 16, marginBottom: 4, position: 'relative' }}>
            封禁IP管理
        </div>
        <Space style={{ width: '100%' }} direction="vertical" size={10}>
            <Form layout="inline" className='queryForm' name="basicGameServer" form={form} onFinish={onFinish}>
                <Row gutter={[0, 6]}>
                    <Col><Form.Item name='gameId'>
                        <Select
                            maxTagCount={1}
                            showSearch
                            style={{ minWidth: 140 }}
                            allowClear
                            placeholder={'请选择游戏'}
                            filterOption={(input, option) =>
                                (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            {getGameChoiceList?.data?.map((item: any) => <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>)}
                        </Select>
                    </Form.Item></Col>

                    <Col><Form.Item name='ip'>
                        <Input placeholder="IP" allowClear style={{ width: 140 }} />
                    </Form.Item></Col>

                    <Col><Form.Item name='banDate'>
                        <DatePicker.RangePicker placeholder={['封禁开始日期', '封禁结束日期']} ranges={getPresets() as any} />
                    </Form.Item></Col>

                    <Col><Form.Item name='status'>
                        <Select
                            maxTagCount={1}
                            showSearch
                            allowClear
                            placeholder={'当前封禁状态'}
                            filterOption={(input, option) =>
                                (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            <Select.Option value={'0'}>已解封</Select.Option>
                            <Select.Option value={'1'}>未解封</Select.Option>
                        </Select>
                    </Form.Item></Col>

                    <Col>
                        <Space>
                            <Button type="primary" htmlType="submit">搜索</Button>
                            <Button onClick={() => form.resetFields()}>重置</Button>
                            <Button type="primary" icon={<PlusOutlined />} onClick={() => { setInitialValues({}); setAddShow(true) }}>新增封禁IP</Button>
                            <Button
                                type="dashed"
                                icon={<CopyOutlined />}
                                disabled={selectedRows?.length === 0}
                                onClick={() => {
                                    setInitialValues({ ips: selectedRows?.map(item => item.ip)?.toString() })
                                    setAddShow(true)
                                }}
                            >
                                复制IP封禁
                            </Button>
                            <Button type="link" disabled={selectedRows?.length === 0} onClick={() => { setSelectedRows([]) }}>清空选择</Button>
                        </Space>
                    </Col>
                </Row>
            </Form>

            <div className={`${style['small']}`}>
                <Tables
                    className={`all_table content_table_body`}
                    bordered
                    sortDirections={['ascend', 'descend', null]}
                    current={queryFrom.pageNum}
                    pageSize={queryFrom.pageSize}
                    columns={columnsPos(handle)}
                    dataSource={getIpManageList?.data?.records}
                    scroll={{ x: 1000, y: 600 }}
                    onChange={(pagination: any, filters: any, sortData: any) => {
                        let { current, pageSize } = pagination
                        let newQueryForm = JSON.parse(JSON.stringify(queryFrom))
                        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={{
                        selectedRowKeys: selectedRows.map(item => item.id + ''),
                        onSelect: (record: { id: number }, selected: boolean) => {
                            if (selected) {
                                selectedRows.push({ ...record })
                                setSelectedRows([...selectedRows])
                            } else {
                                let newSelectAccData = selectedRows.filter((item: { id: number }) => item.id !== record.id)
                                setSelectedRows([...newSelectAccData])
                            }
                        },
                        onSelectAll: (selected: boolean, selectedRowss: { id: number }[], changeRows: { id: number }[]) => {
                            if (selected) {
                                let newSelectAccData = [...selectedRows]
                                changeRows.forEach((item: { id: number }) => {
                                    let index = newSelectAccData.findIndex((ite: { id: number }) => ite.id === item.id)
                                    if (index === -1) {
                                        newSelectAccData.push({ ...item })
                                    }
                                })
                                setSelectedRows([...newSelectAccData])
                            } else {
                                let newSelectAccData = selectedRows.filter((item: { id: number }) => {
                                    let index = changeRows.findIndex((ite: { id: number }) => ite.id === item.id)
                                    if (index !== -1) {
                                        return false
                                    } else {
                                        return true
                                    }
                                })
                                setSelectedRows([...newSelectAccData])
                            }
                        }
                    }}
                    size="small"
                    total={getIpManageList?.data?.total}
                    loading={getIpManageList?.loading}
                    defaultPageSize={20}
                />
            </div>
        </Space>

        {/* 新增封禁IP */}
        {addShow && <AddBanIp
            initialValues={initialValues}
            gameList={getGameChoiceList?.data}
            visible={addShow}
            onClose={() => {
                setAddShow(false)
                setInitialValues({})
            }}
            onChange={() => {
                setAddShow(false);
                setInitialValues({})
                getIpManageList?.refresh()
            }} />}
    </Card>
}

export default BanIpManage