import { Form, Input, message, Modal, Radio } from "antd"
import React from "react"
import '../../tencentAdPutIn/index.less'
import { useAjax } from "@/Hook/useAjax"
import { addApplicationApi, updateApplicationApi } from "@/services/adqV3/global"

interface Props {
    initialValues?: any
    visible?: boolean
    onClose?: () => void
    onChange?: () => void
}

const Modify: React.FC<Props> = ({ initialValues, visible, onClose, onChange }) => {

    /****************************************/
    const [form] = Form.useForm()

    const addApplication = useAjax((params) => addApplicationApi(params))
    const updateApplication = useAjax((params) => updateApplicationApi(params))
    /****************************************/

    const handleOk = () => {
        form.validateFields().then(valid => {
            console.log(valid)
            let params = JSON.parse(JSON.stringify(valid))
            if (params?.contentList) {
                params.contentList = params?.contentList?.split(/[\n\s]+/ig).filter((item: any) => item)
            }
            if (initialValues?.id) {
                params.id = initialValues.id
                updateApplication.run(params).then(res => {
                    if (res) {
                        message.success('修改成功')
                        onChange?.()
                    }
                })
            } else {
                addApplication.run(params).then(res => {
                    if (res) {
                        message.success('新增成功')
                        onChange?.()
                    }
                })
            }

        })
    }

    return <Modal
        title={<strong>{initialValues?.id ? '修改文案' : '新增文案'}</strong>}
        open={visible}
        onCancel={onClose}
        className="modalResetCss"
        onOk={handleOk}
        confirmLoading={addApplication.loading || updateApplication.loading}
    >
        <Form
            name="basicApplication"
            form={form}
            layout='vertical'
            autoComplete="off"
            initialValues={initialValues || {
                type: 'ANDROID'
            }}
        >
            <Form.Item label={<strong>应用名称</strong>} name="name" rules={[{ required: true, message: '请输入应用名称!' }]}>
                <Input placeholder="请输入应用名称" allowClear />
            </Form.Item>
            <Form.Item label={<strong>应用ID</strong>} name="applicationId" rules={[{ required: true, message: '请输入应用ID!' }]}>
                <Input placeholder="请输入应用ID" allowClear />
            </Form.Item>
            <Form.Item label={<strong>应用类型</strong>} name="type" rules={[{ required: true, message: '请选择应用类型!' }]}>
                <Radio.Group buttonStyle="solid">
                    <Radio.Button value="ANDROID">Android</Radio.Button>
                    <Radio.Button value="IOS">Ios</Radio.Button>
                </Radio.Group>
            </Form.Item>
        </Form>
    </Modal>
}

export default React.memo(Modify)