import { useAjax } from "@/Hook/useAjax"
import TableData from "@/pages/launchSystemNew/components/TableData"
import { delSysWarningRuleApi, getSysWarningRuleListApi, RuleProps } from "@/services/adMonitor/earlyWarning"
import { Button, Card, Input, message, Space } from "antd"
import React, { useEffect, useState } from "react"
import AddEdit from "./addEdit"
import ExpandedRowTable from "./expandedRowTable"
import tableConfig from "./tableConfig"
import RuleLog from "./ruleLog"



/**
 * 监控预警
 * @returns 
 */
const EarlyWarning: React.FC = () => {

    /**************************/
    const [addVisible, setAddVisible] = useState<boolean>(false)
    const [queryParams, setQueryParams] = useState<{ ruleName?: string }>({})
    const [editData, setEditData] = useState<{ initialValues?: any }>({})

    const [logVisible, setLogVisible] = useState<boolean>(false)
    const [ruleId, setrRleId] = useState<number>(0)
    const [ruleName, setrRuleName] = useState<string>('')

    const [detailsVisible, setDetailsVisible] = useState<boolean>(false)
    const [detailsData, setDetailsData] = useState<any>({})

    const getSysWarningRuleList = useAjax((params) => getSysWarningRuleListApi(params), { formatResult: true })
    const delSysWarningRule = useAjax((params) => delSysWarningRuleApi(params))
    /**************************/

    // 获取列表
    useEffect(() => {
        getList()
    }, [])

    const getList = () => {
        getSysWarningRuleList.run(queryParams)
    }

    /** 修改 */
    const edit = (data: any) => {
        let newData = JSON.parse(JSON.stringify(data))
        newData.defaultRule = newData.defaultRule ? true : false
        newData.enable = newData.enable ? true : false
        newData.rules = newData.rules.map((item: { rule: RuleProps[], operationType: number, operationValue: number }) => {
            let field: string[] = []
            let data: any = {}
            item.rule.forEach(i => {
                let { field: oldField, ...newItem } = i
                field.push(oldField)
                data[oldField] = { ...newItem }
            })
            return {
                ...data,
                field,
                operationType: item.operationType,
                operationValue: item?.operationValue
            }
        })
        console.log(newData)

        setEditData({ initialValues: newData })
        setAddVisible(true)
    }
    /** 删除 */
    const del = (id: number) => {
        delSysWarningRule.run(id).then(res => {
            message.success('删除成功')
            getSysWarningRuleList.refresh()
        })
    }

    const log = (value: any) => {
        setrRleId(value.id)
        setrRuleName(value.ruleName)
        setLogVisible(true)
    }

    const details = (value: any) => {
        setDetailsData(value)
        setDetailsVisible(true)
    }

    return <Card
        title={<div style={{ color: 'red', fontWeight: 600 }}>
            {`广告告警规则可以配置为默认规则或者给指定广告账号、广告配置。告警的优先级为 广告 > 广告账号 > 默认规则（只会触发同一级别的告警规则，如果在广告上配置了告警规则，那么广告账号的告警规则就不会触发）。`}
        </div>}
    >

        <TableData
            size="small"
            isCard={false}
            columns={() => tableConfig(edit, del, log, details)}
            ajax={getSysWarningRuleList}
            dataSource={getSysWarningRuleList?.data?.data}
            loading={getSysWarningRuleList?.loading}
            total={getSysWarningRuleList?.data?.data?.length}
            gutter={[0, 10]}
            leftChild={<Space>
                <Input placeholder="请输入规则名字" value={queryParams?.ruleName} onChange={(e) => setQueryParams({ ...queryParams, ruleName: e.target.value })} />
                <Button type="primary" onClick={getList}>搜索</Button>
                <Button type="primary" onClick={() => setAddVisible(true)}>新增告警规则</Button>
            </Space>}
        />

        {/* 设置预警 */}
        {addVisible && <AddEdit visible={addVisible} onChange={() => { setAddVisible(false); getSysWarningRuleList.refresh(); setEditData({}) }} onClose={() => { setAddVisible(false); setEditData({}) }} {...editData} />}

        {logVisible && <RuleLog ruleName={ruleName} ruleId={ruleId} visible={logVisible} onClose={() => setLogVisible(false)} />}

        {detailsVisible && <ExpandedRowTable data={detailsData} onClose={() => setDetailsVisible(false)} visible={detailsVisible} onChange={() => { }} />}
    </Card>
}

export default React.memo(EarlyWarning)