package com.common.service;

import com.common.entity.SyslogNormalData;
import com.common.mapper.SyslogNormalDataMapper;
import com.common.mapper.SyslogNormalAlarmMapper;

import com.influx.SyslogToInfluxApp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.net.InetAddress;
import java.net.UnknownHostException;

import java.util.List;
import java.util.Map;

@Service
public class SyslogNormalDataService {
    private static final Logger logger = LoggerFactory.getLogger(SyslogNormalDataService.class);
    @Autowired
    private SyslogNormalDataMapper syslogNormalDataMapper;
    @Autowired
    private SyslogNormalAlarmMapper syslogNormalAlarmMapper;


    /**
     * 动态插入单条数据 - Map方式
     */
    @Transactional
    public int insertDynamic(Map<String, Object> dataMap) {
        // 设置必要字段的默认值
        if (!dataMap.containsKey("created_at")) {
            dataMap.put("created_at", new java.util.Date());
        }
        if (!dataMap.containsKey("log_time")) {
            dataMap.put("log_time", new java.util.Date());
        }
        if (dataMap.containsKey("tc_hostip")) {
            if(!isValidIP(dataMap.get("tc_hostip").toString()))
            {
                String hostip=dataMap.get("tc_hostip").toString();
                logger.error("tc_hostip 字段非IP类型，值为：{}，将赋值为null",hostip);
                dataMap.remove("tc_hostip");

            }
        }
        //判断是否包含event_level (事件级别）,区分告警日志和访问日志，分别进入不同的标准化数据表
        if (dataMap != null && dataMap.get("event_level") != null) {
            return syslogNormalAlarmMapper.insertDynamic(dataMap);
        }
        else
            return syslogNormalDataMapper.insertDynamic(dataMap);
    }

    /**
     * 插入单条数据 - 实体类方式
     */
    @Transactional
    public int insertByEntity(SyslogNormalData entity) {
        // 设置必要字段的默认值
        if (entity.getCreatedAt() == null) {
            entity.setCreatedAt(java.time.LocalDateTime.now());
        }
        if (entity.getLogTime() == null) {
            entity.setLogTime(java.time.LocalDateTime.now());
        }
        return syslogNormalDataMapper.insertByEntity(entity);
    }

    /**
     * 批量插入数据
     */
    @Transactional
    public int batchInsert(List<Map<String, Object>> dataList) {
        if (dataList == null || dataList.isEmpty()) {
            return 0;
        }

        // 为每条数据设置必要字段的默认值
        for (Map<String, Object> data : dataList) {
            if (!data.containsKey("created_at")) {
                data.put("created_at", new java.util.Date());
            }
            if (!data.containsKey("log_time")) {
                data.put("log_time", new java.util.Date());
            }
        }
        return syslogNormalDataMapper.batchInsert(dataList);
    }

    /**
     * 转换实体类为Map
     */
    public Map<String, Object> convertEntityToMap(SyslogNormalData entity) {
        // 使用反射或对象映射工具将实体类转换为Map
        // 这里可以使用 Jackson 的 ObjectMapper 或 Spring 的 BeanUtils
        org.springframework.beans.BeanWrapper wrapper = new org.springframework.beans.BeanWrapperImpl(entity);
        java.util.Map<String, Object> result = new java.util.HashMap<>();

        for (java.beans.PropertyDescriptor pd : wrapper.getPropertyDescriptors()) {
            String propertyName = pd.getName();
            if (!"class".equals(propertyName)) {
                Object value = wrapper.getPropertyValue(propertyName);
                if (value != null) {
                    // 将驼峰命名转换为下划线命名
                    String columnName = camelToSnake(propertyName);
                    result.put(columnName, value);
                }
            }
        }

        return result;
    }
    // 字符串是否为IP
    public static boolean isValidIP(String ipString) {
        try {
            InetAddress.getByName(ipString);
            // 额外检查：确保不是域名（简单检查）
            return ipString.matches(".*\\d+\\..*");
        } catch (UnknownHostException e) {
            return false;
        }
    }
    /**
     * 驼峰命名转下划线命名
     */
    private String camelToSnake(String str) {
        return str.replaceAll("([a-z])([A-Z])", "$1_$2").toLowerCase();
    }
}