package com.common.service;

import com.common.entity.XdrHoneypot;
import com.common.mapper.XdrHoneypotMapper;
import com.common.util.MyBatisUtil;
import com.influx.SyslogToInfluxApp;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.common.mapper.DmNormalizeRuleMapper;
import com.common.entity.DmNormalizeRule;

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



@Service
@CacheConfig(cacheNames = "normalizeRule")
public class DmNormalizeRuleService {

    @Autowired
    private DmNormalizeRuleMapper dmNormalizeRuleMapper;

    private static final Logger logger = LoggerFactory.getLogger(DmNormalizeRuleService.class);


    /**
     * 根据ID查询规则
     */
    @Cacheable(key = "'id:' + #id")
    public DmNormalizeRule getById(Long id) {
        return dmNormalizeRuleMapper.selectById(id);
    }

    /**
     * 根据ID和租户查询规则
     */
    public DmNormalizeRule getByIdAndTenant(Long id, String tenantId) {
        return dmNormalizeRuleMapper.selectByIdAndTenant(id, tenantId);
    }
    /**
     * 根据ID更新规则
     */
    public boolean updateById(DmNormalizeRule rule) {
        // 设置更新时间
        rule.setUpdatedAt(java.time.LocalDateTime.now());
        rule.setUpdateTime(java.time.LocalDateTime.now());
        int result = dmNormalizeRuleMapper.updateById(rule);
        return result > 0;
    }

    /**
     * 根据ID和租户更新规则
     */
    public boolean updateByIdAndTenant(DmNormalizeRule rule) {
        // 设置更新时间
        rule.setUpdatedAt(java.time.LocalDateTime.now());
        rule.setUpdateTime(java.time.LocalDateTime.now());
        int result = dmNormalizeRuleMapper.updateByIdAndTenant(rule);
        return result > 0;
    }
    /**
     * 根据device ID 获取normal rule 信息
     */
    @Cacheable(key = "'deviceId:' + #id")
    public List<Map<String, Object>> selectByDeviceId(  Long id)
    {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            dmNormalizeRuleMapper = sqlSession.getMapper(DmNormalizeRuleMapper.class);

            List<Map<String, Object>>  ruleMap=dmNormalizeRuleMapper.selectByDeviceId(id);
            sqlSession.commit();
            return convertClobToString(ruleMap);

        } catch (Exception e) {
            logger.error("DmNormalizeRuleService MyBatisUtil getSqlSession 异常", e);
        }
        return null;
    }

    /**
     * 根据device ID 获取关联的Normalize Rule 信息
     * @param id
     * @return
     */
    @Cacheable(key = "'deviceId:' + #id")
    public List<Map<String, Object>> selectByDeviceIdAuto( Long id)
    {
        System.out.println("调用selectByDeviceIdAuto 方法,id:"+id);
        List<Map<String, Object>>  ruleMap=dmNormalizeRuleMapper.selectByDeviceId(id);
        return convertClobToString(ruleMap);
    }

    /**
     * 将达梦 JDBC CLOB/NCLOB 对象转换为 String，避免缓存序列化报错
     * 达梦驱动返回的 TEXT/CLOB 列可能是 dm.jdbc.driver.DmdbNClob 等内部类型，
     * toString() 只返回对象引用（如 DmdbNClob@xxx），必须通过 Clob 接口获取实际文本
     */
    private List<Map<String, Object>> convertClobToString(List<Map<String, Object>> list) {
        if (list == null) return null;
        for (Map<String, Object> map : list) {
            if (map == null) continue;
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                Object value = entry.getValue();
                if (value != null && value.getClass().getName().startsWith("dm.jdbc.")) {
                    try {
                        if (value instanceof java.sql.Clob) {
                            java.sql.Clob clob = (java.sql.Clob) value;
                            long length = clob.length();
                            if (length > 0) {
                                entry.setValue(clob.getSubString(1, (int) length));
                            } else {
                                entry.setValue("");
                            }
                        } else {
                            entry.setValue(value.toString());
                        }
                    } catch (Exception e) {
                        logger.warn("CLOB/NCLOB 转换 String 失败: " + e.getMessage());
                        entry.setValue(null);
                    }
                }
            }
        }
        return list;
    }

}