import { useAjax } from "@/Hook/useAjax"
import { addSysWarningRuleApi, editSysWarningRuleApi } from "@/services/adMonitor/earlyWarning"
import { DeleteOutlined, PlusOutlined } from "@ant-design/icons"
import { Button, Form, Input, InputNumber, message, Modal, Popconfirm, Select, Space, Switch } from "antd"
import React, { useEffect } from "react"
import { MonitorFieldEnum, WarningTypeEnum } from "./config"
import './index.less'
import PriceInput from "./priceInput"
import { OperationType } from "./ruleLog"


interface Props {
    visible?: boolean
    onClose?: () => void
    onChange?: () => void,
    initialValues?: any
}
const AddEdit: React.FC<Props> = (props) => {

    /******************************/
    const { visible, onClose, onChange, initialValues } = props
    const [form] = Form.useForm();
    const rules = Form.useWatch('rules', form);

    const addSysWarningRule = useAjax((params) => addSysWarningRuleApi(params))
    const editSysWarningRule = useAjax((params) => editSysWarningRuleApi(params))
    /******************************/

    useEffect(() => {
        if (rules?.some((item: { field: string[] }) => item?.field?.includes('cost_trend_last_three_hour') && !(item?.['cost_trend_last_three_hour']?.value === 1))) {
            form.setFieldsValue({ rules: rules.map((item: any) => ({ ...item, cost_trend_last_three_hour: { value: 1, condition: '=' } })) })
        }
    }, [rules])

    const handleOk = () => {
        form.validateFields().then(values => {
            if (values?.rules) {
                let newValues = JSON.parse(JSON.stringify(values))
                let { rules, defaultRule, enable, notifyFrequency, ruleName, warningType, unTipWhenStop } = newValues
                console.log(rules)
                let params = rules?.map((item: any) => {
                    const { field, operationType, operationValue, ...newItem } = item
                    let ov = {}
                    if (operationValue) {
                        ov = { operationValue }
                    }
                    return {
                        rule: Object.keys(newItem).filter(key => field.includes(key)).map(key => {
                            return {
                                ...newItem[key],
                                field: key
                            }
                        }),
                        operationType,
                        ...ov
                    }
                })
                if (initialValues?.id) {
                    editSysWarningRule.run({ ruleId: initialValues.id, rules: params, notifyFrequency, ruleName, warningType, defaultRule: defaultRule ? 1 : 0, enable: enable ? 1 : 0, unTipWhenStop }).then(res => {
                        message.success('修改成功')
                        onChange?.()
                    })
                } else {
                    addSysWarningRule.run({ rules: params, notifyFrequency, ruleName, warningType, defaultRule: defaultRule ? 1 : 0, enable: enable ? 1 : 0, unTipWhenStop }).then(res => {
                        message.success('新增成功')
                        onChange?.()
                    })
                }
            } else {
                message.error('请添加最少一项规则')
            }
        })
    }
    return <Modal
        title={<Space size={2} align='end'>
            <strong>{initialValues?.id ? '修改预警规则' : '新增预警规则'}</strong>
            <span style={{ fontSize: 12, color: 'red' }}>(条件与条件之间是或者关系，条件内字段是并且关系, 满足任意一条件立即触发报警提醒)</span>
        </Space>}
        visible={visible}
        onOk={handleOk}
        width={750}
        confirmLoading={addSysWarningRule.loading || editSysWarningRule.loading}
        onCancel={() => onClose?.()}
    >
        <Form
            name="dynamic_form_nest_item"
            form={form}
            className="addEdit_form"
            labelCol={{ span: 6 }}
            colon={false}
            initialValues={initialValues || {
                enable: true,
                notifyFrequency: 5,
                defaultRule: false,
                rules: [{
                    field: []
                }],
                unTipWhenStop: true
            }}
            labelAlign="left"
        >
            <div style={{ padding: '0 4px' }}>
                <Form.Item name="ruleName" label={<strong>规则名称</strong>} rules={[{ required: true, message: '请输入规则名称' }]}>
                    <Input placeholder="规则名称" />
                </Form.Item>
                <Form.Item name="warningType" label={<strong>告警方式</strong>} rules={[{ required: true, message: '请选择通知频率' }]}>
                    <Select
                        mode="multiple"
                        showSearch
                        allowClear
                        placeholder="选择告警方式"
                        filterOption={(input, option) =>
                            ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                        }
                    >
                        {Object.keys(WarningTypeEnum).map((item, index) => <Select.Option value={item} key={index}>{WarningTypeEnum[item]}</Select.Option>)}
                    </Select>
                </Form.Item>
                <Form.Item name="notifyFrequency" label={<strong>通知频率</strong>} rules={[{ required: true, message: '请选择通知频率' }]}>
                    <InputNumber min={5} addonAfter="分钟" />
                </Form.Item>
                <Form.Item name="enable" label={<strong>Enable?</strong>} valuePropName="checked" rules={[{ required: true }]}>
                    <Switch />
                </Form.Item>
                <Form.Item name="defaultRule" label={<strong>是否默认规则</strong>} valuePropName="checked" rules={[{ required: true }]}>
                    <Switch />
                </Form.Item>
                <Form.Item name="unTipWhenStop" label={<strong>暂停/删除广告不通知</strong>} valuePropName="checked" rules={[{ required: true }]}>
                    <Switch />
                </Form.Item>
            </div>
            <Form.List name="rules">
                {(fields, { add, remove }) => <>
                    <>{fields.map(({ key, name, ...restField }) => {
                        return <div key={key} style={{ width: '100%' }} className="field">
                            <Space className="field_name">
                                <span>条件{key + 1}</span>
                                {fields.length > 1 && <Popconfirm
                                    title="确定删除"
                                    onConfirm={() => remove(name)}
                                    okText="Yes"
                                    cancelText="No"
                                >
                                    <DeleteOutlined style={{ color: 'red' }} />
                                </Popconfirm>}
                            </Space>
                            <Form.Item
                                {...restField}
                                label={<strong>字段</strong>}
                                name={[name, 'field']}
                                rules={[{ required: true, message: '请选择字段' }]}
                            >
                                <Select
                                    mode="multiple"
                                    showSearch
                                    allowClear
                                    placeholder="选择要设置的字段"
                                    filterOption={(input, option) =>
                                        ((option?.children ?? '') as any).toLowerCase().includes(input.toLowerCase())
                                    }
                                >
                                    {Object.keys(MonitorFieldEnum).map((item, index) => <Select.Option disabled={rules?.[key]?.['field']?.length >= 3 && !rules?.[key]['field'].includes(item)} value={item} key={index}>{MonitorFieldEnum[item]}</Select.Option>)}
                                </Select>
                            </Form.Item>
                            {rules?.[key]?.['field']?.map((field: string, index: number) => <Form.Item
                                {...restField}
                                key={index}
                                label={<strong>{MonitorFieldEnum[field]}</strong>}
                                name={[name, field]}
                                rules={[{
                                    required: true, message: MonitorFieldEnum[field] + '的值不能为0', validator(rule, value, callback) {
                                        if (!value?.value) {
                                            return Promise.reject()
                                        }
                                        return Promise.resolve()
                                    },
                                }]}
                            >
                                <PriceInput disabled={field === 'cost_trend_last_three_hour'} />
                            </Form.Item>)}
                            <Form.Item
                                {...restField}
                                label={<strong>操作类型</strong>}
                                name={[name, 'operationType']}
                                rules={[{ required: true }]}
                            >
                                <Select
                                    showSearch
                                    allowClear
                                    placeholder="选择操作类型"
                                    filterOption={(input, option) =>
                                        ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                                    }
                                >
                                    {OperationType.map((item, index) => <Select.Option value={item.value} key={item.value}>{item.label}</Select.Option>)}
                                </Select>
                            </Form.Item>
                            {[3, 4].includes(rules?.[key]?.['operationType']) && <Form.Item
                                {...restField}
                                label={<strong>操作值</strong>}
                                name={[name, 'operationValue']}
                                rules={[{ required: true }]}
                            >
                                <InputNumber style={{ width: '100%' }} min={0} placeholder="请输入操作值" />
                            </Form.Item>}
                        </div>
                    })}</>

                    <Form.Item>
                        <Button type="dashed" onClick={() => add({
                            field: []
                        })} block icon={<PlusOutlined />}>新增条件</Button>
                    </Form.Item>
                </>}
            </Form.List>

        </Form>
    </Modal>
}

export default React.memo(AddEdit)