import { useAjax } from "@/Hook/useAjax"
import { addBanIpApi } from "@/services/gameData/player"
import { Form, Input, message, Modal, Select } from "antd"
import React from "react"

interface Props {
    gameList: any[]
    initialValues?: any
    visible?: boolean,
    onChange?: () => void,
    onClose?: () => void
}
/**
 * 新增封禁IP
 * @param props 
 * @returns 
 */
const AddBanIp: React.FC<Props> = (props) => {

    /** ----------变量开始------- */
    const { visible, onChange, onClose, gameList, initialValues = {} } = props
    const [form] = Form.useForm()
    /** ----------变量结束------- */

    const addBanIp = useAjax((params: { ipList: string[] }) => addBanIpApi(params))


    // 确定
    const handleOk = async () => {
        form.submit()
        let data = await form.validateFields()
        let regexIP = /^((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))$/
        let ips = data.ips.split(/,|，/ig)
        if (!ips?.every((ip: string) => regexIP.test(ip))) {
            message.error('请正确输入ip地址')
            return
        }
        addBanIp.run({ ipList: ips, gameId: data.gameId }).then(res => {
            if (res) {
                message.success('添加成功')
                onChange && onChange()
            }
        })
    }

    return <Modal title={Object.keys(initialValues).length > 0 ? "复制IP封禁" : `新增封禁IP`} visible={visible} onOk={handleOk} onCancel={() => { onClose && onClose() }} confirmLoading={addBanIp.loading}>
        <Form
            name="basicBanIp"
            form={form}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            autoComplete="off"
            initialValues={{ ...initialValues }}
        >
            <Form.Item label="游戏" name="gameId" rules={[{ required: true, message: '请选择游戏!' }]}>
                <Select
                    showSearch
                    style={{ minWidth: 180 }}
                    allowClear
                    placeholder="选择游戏"
                    filterOption={(input, option) =>
                        (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                >
                    {gameList?.map((item: any) => <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>)}
                </Select>
            </Form.Item>
            <Form.Item label="IP" name="ips" rules={[{ type: 'string', required: true, message: '请输入IP!' }]}>
                <Input.TextArea rows={4} placeholder="请输入需要封禁的IP地址，多个IP请用逗号“，”隔开" disabled={Object.keys(initialValues).length > 0}/>
            </Form.Item>
        </Form>
    </Modal>
}

export default React.memo(AddBanIp)