import { useAjax } from "@/Hook/useAjax"
import { addOrUpDatePackApi } from "@/services/gameData/roleOperate"
import { Form, Input, Modal, Select, message } from "antd"
import React, { useEffect, useState } from "react"


interface Props {
    gameList: any[]
    initialValues?: any
    visible?: boolean
    onClose?: () => void
    onChange?: () => void
}
/**
 * 礼包操作
 * @returns 
 */
const StagingModal: React.FC<Props> = ({ visible, onClose, onChange, initialValues = {}, gameList = [] }) => {
    
    /******************************/
    const [form] = Form.useForm()
    const [superGameId, setSuperGameId] = useState<number>()
    const addOrUpDatePack = useAjax((params) => addOrUpDatePackApi(params))
    /******************************/

    useEffect(() => {
        setSuperGameId(initialValues?.superGameId)
    }, [initialValues])

    const handleOk = async () => {
        form.submit()
        let data = await form.validateFields()
        data.superGameId = superGameId
        if (initialValues?.id) {
            data.id = initialValues?.id
        }
        addOrUpDatePack.run(data).then(res => {
            if (res) {
                if (initialValues?.id) {
                    message.success('修改成功')
                } else {
                    message.success('新增成功')
                }
                onChange && onChange()
            }
        })
    }

    return <Modal
        title={`${initialValues?.id ? '修改' : '新增'}礼包`}
        visible={visible}
        onCancel={onClose}
        onOk={handleOk}
        confirmLoading={addOrUpDatePack.loading}
    >
        <Form
            name="basicPack"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            form={form}
            autoComplete="off"
            initialValues={{ ...initialValues }}
        >
            <Form.Item label="礼包名称" name="giftName" rules={[{ required: true, message: '请输入礼包名称!' }]}>
                <Input placeholder="请输入礼包名称"/>
            </Form.Item>
            <Form.Item label="游戏" name="parentGameId" rules={[{ required: true, message: '请选择游戏!' }]}>
                <Select
                    showSearch
                    style={{ minWidth: 180 }}
                    allowClear
                    placeholder="选择游戏"
                    filterOption={(input, option) =>
                        (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                    onChange={(e, option: any) => {
                        setSuperGameId(option?.['data-super-id'])
                    }}
                >
                    {gameList?.map((item: any) => <Select.Option value={item.id} key={item.id} data-super-id={item.superId}>{item.name}</Select.Option>)}
                </Select>
            </Form.Item>
        </Form>
    </Modal>
}

export default React.memo(StagingModal)