package com.common.service.impl;



import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.entity.SyslogNonNormalMessage;
import com.common.mapper.SyslogNonNormalMessageMapper;
import com.common.service.SyslogNonNormalMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.List;
import java.util.UUID;

/**
 * 非标日志服务实现类
 */
@Slf4j
@Service
public class SyslogNonNormalMessageServiceImpl
        extends ServiceImpl<SyslogNonNormalMessageMapper, SyslogNonNormalMessage>
        implements SyslogNonNormalMessageService {

    @Autowired
    private SyslogNonNormalMessageMapper messageMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveMessage(SyslogNonNormalMessage message) {
        try {
            // 设置ID（如果未提供）
            if (message.getId() == null || message.getId().isEmpty()) {
                message.setId(generateMessageId());
            }

            // 设置默认值
            if (message.getCreatedAt() == null) {
                // 设置为当前UTC时间
                message.setCreatedAt(OffsetDateTime.now(ZoneOffset.UTC));
            }

            if (message.getCreateTime() == null) {
                message.setCreateTime(LocalDateTime.now());
            }

            if (message.getUpdateTime() == null) {
                message.setUpdateTime(LocalDateTime.now());
            }

            if (message.getDelFlag() == null || message.getDelFlag().isEmpty()) {
                message.setDelFlag("0");
            }

            if (message.getRuleResult() == null || message.getRuleResult().isEmpty()) {
                message.setRuleResult("FAIL");
            }

            if (message.getTenantId() == null || message.getTenantId().isEmpty()) {
                message.setTenantId("000000");
            }

            // 执行插入
            return this.save(message);
        } catch (Exception e) {
            log.error("保存非标日志失败: {}", e.getMessage(), e);
            throw new RuntimeException("保存非标日志失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveBatchMessages(List<SyslogNonNormalMessage> messages) {
        if (messages == null || messages.isEmpty()) {
            return 0;
        }

        try {
            // 为每条记录设置默认值
            for (SyslogNonNormalMessage message : messages) {
                if (message.getId() == null || message.getId().isEmpty()) {
                    message.setId(generateMessageId());
                }

                if (message.getCreatedAt() == null) {
                    message.setCreatedAt(OffsetDateTime.now(ZoneOffset.UTC));
                }

                if (message.getCreateTime() == null) {
                    message.setCreateTime(LocalDateTime.now());
                }

                if (message.getUpdateTime() == null) {
                    message.setUpdateTime(LocalDateTime.now());
                }

                if (message.getDelFlag() == null || message.getDelFlag().isEmpty()) {
                    message.setDelFlag("0");
                }

                if (message.getRuleResult() == null || message.getRuleResult().isEmpty()) {
                    message.setRuleResult("FAIL");
                }

                if (message.getTenantId() == null || message.getTenantId().isEmpty()) {
                    message.setTenantId("000000");
                }
            }

            // 批量插入
            return messageMapper.batchInsert(messages);
        } catch (Exception e) {
            log.error("批量保存非标日志失败: {}", e.getMessage(), e);
            throw new RuntimeException("批量保存非标日志失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateMessage(SyslogNonNormalMessage message) {
        try {
            // 设置更新时间
            message.setUpdateTime(LocalDateTime.now());

            // 构建更新条件
            LambdaQueryWrapper<SyslogNonNormalMessage> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SyslogNonNormalMessage::getId, message.getId())
                    .eq(SyslogNonNormalMessage::getDelFlag, "0");

            return this.update(message, wrapper);
        } catch (Exception e) {
            log.error("更新非标日志失败: {}", e.getMessage(), e);
            throw new RuntimeException("更新非标日志失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteMessage(String id) {
        try {
            // 逻辑删除，设置del_flag为1
            return messageMapper.logicalDelete(id) > 0;
        } catch (Exception e) {
            log.error("删除非标日志失败: {}", e.getMessage(), e);
            throw new RuntimeException("删除非标日志失败", e);
        }
    }

    @Override
    public SyslogNonNormalMessage getMessageById(String id) {
        try {
            LambdaQueryWrapper<SyslogNonNormalMessage> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SyslogNonNormalMessage::getId, id)
                    .eq(SyslogNonNormalMessage::getDelFlag, "0");

            return this.getOne(wrapper);
        } catch (Exception e) {
            log.error("查询非标日志失败: {}", e.getMessage(), e);
            throw new RuntimeException("查询非标日志失败", e);
        }
    }

    @Override
    public List<SyslogNonNormalMessage> queryMessages(Integer deviceId, LocalDateTime startTime,
                                                      LocalDateTime endTime, String ruleResult) {
        try {
            return messageMapper.findByTimeRange(startTime, endTime);
        } catch (Exception e) {
            log.error("查询非标日志失败: {}", e.getMessage(), e);
            throw new RuntimeException("查询非标日志失败", e);
        }
    }
    /**
     * 根据ID和创建时间批量查询非标日志
     */
    @Override
    public List<SyslogNonNormalMessage> getMessagesByIdsAndCreatedAts(
            List<String> ids, List<String> createdAts) {
        return messageMapper.getMessagesByIdsAndCreatedAts(ids, createdAts);
    }

    /**
     * 根据ID列表批量查询非标日志
     */
    @Override
    public List<SyslogNonNormalMessage> getMessagesByIds(List<String> ids) {
        return messageMapper.getMessagesByIds(ids);
    }

    /**
     * 批量更新del_flag字段
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBatchDelFlag(List<SyslogNonNormalMessage> messages) {
        return messageMapper.updateBatchDelFlag(messages);
    }

    /**
     * 批量更新记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBatch(List<SyslogNonNormalMessage> messages) {
        return messageMapper.updateBatch(messages);
    }
    /**
     * 生成消息ID
     */
    private String generateMessageId() {
        // 使用UUID生成唯一ID
        return   UUID.randomUUID().toString().replace("-", "").substring(0, 20);
    }
}