package com.common.service.impl;


import com.common.entity.DeviceReceiveLog;
import com.common.mapper.DeviceReceiveLogMapper;
import com.common.service.DeviceReceiveLogService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class DeviceReceiveLogServiceImpl implements DeviceReceiveLogService {

    private final DeviceReceiveLogMapper deviceReceiveLogMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insertLog(DeviceReceiveLog log) {
        // 设置默认时间
        if (log.getCreatedAt() == null) {
            log.setCreatedAt(LocalDateTime.now());
        }

        if (log.getReceiveTimeStr() == null && log.getReceiveTime() != null) {
            log.setReceiveTimeStr(log.getReceiveTime().toString());
        }

        deviceReceiveLogMapper.insert(log);
       // log.info("插入设备接收日志成功，ID: {}", log.getId());
        return log.getId();
    }

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

        // 批量处理，每1000条提交一次
        int batchSize = 1000;
        int totalInserted = 0;

        for (int i = 0; i < logs.size(); i += batchSize) {
            int end = Math.min(i + batchSize, logs.size());
            List<DeviceReceiveLog> batchList = logs.subList(i, end);

            // 设置默认值
            batchList.forEach(log -> {
                if (log.getCreatedAt() == null) {
                    log.setCreatedAt(LocalDateTime.now());
                }
                if (log.getReceiveTimeStr() == null && log.getReceiveTime() != null) {
                    log.setReceiveTimeStr(log.getReceiveTime().toString());
                }
            });

            int inserted = deviceReceiveLogMapper.batchInsert(batchList);
            totalInserted += inserted;
            log.info("批量插入进度: {}/{}", end, logs.size());
        }

        return totalInserted;
    }

    @Override
    public DeviceReceiveLog getById(Long id) {
        return deviceReceiveLogMapper.selectById(id);
    }

    @Override
    public List<DeviceReceiveLog> getByDeviceId(Integer deviceId) {
        return deviceReceiveLogMapper.selectByDeviceId(deviceId);
    }

    @Override
    public List<DeviceReceiveLog> getByCollectId(Integer collectId) {
        return deviceReceiveLogMapper.selectByCollectId(collectId);
    }

    @Override
    public List<DeviceReceiveLog> getByTimeRange(LocalDateTime startTime, LocalDateTime endTime) {
        if (startTime == null || endTime == null) {
            throw new IllegalArgumentException("时间范围不能为空");
        }
        if (startTime.isAfter(endTime)) {
            throw new IllegalArgumentException("开始时间不能晚于结束时间");
        }
        return deviceReceiveLogMapper.selectByTimeRange(startTime, endTime);
    }

    @Override
    public List<DeviceReceiveLog> getByCondition(DeviceReceiveLog condition) {
        return deviceReceiveLogMapper.selectByCondition(condition);
    }

    @Override
    public PageInfo<DeviceReceiveLog> getByConditionPage(DeviceReceiveLog condition, Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }

        PageHelper.startPage(pageNum, pageSize);
        List<DeviceReceiveLog> list = deviceReceiveLogMapper.selectByCondition(condition);
        return new PageInfo<>(list);
    }

    @Override
    public Long countByCondition(DeviceReceiveLog condition) {
        return deviceReceiveLogMapper.countByCondition(condition);
    }

    @Override
    public List<Map<String, Object>> getDeviceLogStatistics() {
        return deviceReceiveLogMapper.countByDeviceGroup();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteOldLogs(LocalDateTime beforeTime) {
        if (beforeTime == null) {
            throw new IllegalArgumentException("删除时间点不能为空");
        }

        LocalDateTime endTime = LocalDateTime.now().minusDays(30); // 默认保留30天
        if (beforeTime.isAfter(endTime)) {
            log.warn("删除时间点{}晚于默认保留时间{}，使用默认时间", beforeTime, endTime);
            beforeTime = endTime;
        }

        int deleted = deviceReceiveLogMapper.deleteByTimeRange(
                LocalDateTime.of(2000, 1, 1, 0, 0), // 很早的时间
                beforeTime
        );

        log.info("删除{}天前的日志，共删除{}条", beforeTime, deleted);
        return deleted;
    }

    @Override
    public List<DeviceReceiveLog> getRecentLogs(Integer limit) {
        if (limit == null || limit < 1) {
            limit = 50; // 默认返回50条
        }
        return deviceReceiveLogMapper.selectRecent(limit);
    }
}