import { useAjax } from "@/Hook/useAjax"
import { configAdWarningRuleApi } from "@/services/adMonitor/adMonitor"
import { getSysWarningRuleListApi } from "@/services/adMonitor/earlyWarning"
import { AlertOutlined } from "@ant-design/icons"
import { Button, Form, message, Modal, Select } from "antd"
import React, { useState } from "react"



interface Props {
    accountId: any
    adgroupId: any
    onChange?: () => void
}
const SetEarlyWarnings: React.FC<Props> = (props) => {

    /******************************/
    const { accountId, adgroupId, onChange } = props
    const [visible, setVisible] = useState<boolean>(false)
    const [form] = Form.useForm();
    const getSysWarningRuleList = useAjax((params) => getSysWarningRuleListApi(params))
    const configAdWarningRule = useAjax((params) => configAdWarningRuleApi(params), { formatResult: true })
    /******************************/

    const openModal = () => {
        setVisible(true)
        getSysWarningRuleList.run()
        form.setFieldsValue({ adgroupId })
    }

    const handleOk = () => {
        form.validateFields().then(values => {
            configAdWarningRule.run({ accountId, adgroupId, ruleIds: values.ruleIds?.toString() }).then(res => {
                message.success('设置成功')
                onChange?.()
                setVisible(false)
            })
        })
    }

    return <>
        <Button icon={<AlertOutlined />} type="link" onClick={openModal}>设置预警</Button>
        {visible && <Modal
            open={visible}
            title="预警设置"
            onOk={handleOk}
            confirmLoading={configAdWarningRule.loading}
            onCancel={() => setVisible(false)}
        >
            <Form
                form={form}
                labelCol={{ span: 5 }}
                colon={false}
                initialValues={{

                }}
            >
                <Form.Item name="ruleIds" label={<strong>选择预警规则</strong>} rules={[{ required: true, message: '请选择预警规则' }]}>
                    <Select
                        showSearch
                        allowClear
                        mode='multiple'
                        placeholder="选择预警规则"
                        filterOption={(input, option) =>
                            ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                        }
                    >
                        {getSysWarningRuleList?.data?.filter((item: any) => !item?.defaultRule)?.map((item: any) => <Select.Option value={item.id} key={item.id}>{item.ruleName}</Select.Option>)}
                    </Select>
                </Form.Item>
            </Form>
        </Modal>}
    </>
}


export default React.memo(SetEarlyWarnings)