package com.rj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.entity.YhyDatatypeLog;
import com.rj.mapper.YhyDatatypeLogMapper;
import com.rj.service.IYhyDatatypeLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rj.common.TimeZoneUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 心跳日志表 服务实现类
 * </p>
 *
 * @author Auto Generated
 * @since 2025-01-01
 */
@Slf4j
@Service
public class YhyDatatypeLogServiceImpl extends ServiceImpl<YhyDatatypeLogMapper, YhyDatatypeLog> implements IYhyDatatypeLogService {

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public Map<String, Object> getYhyDatatypeLogList(Integer current, Integer size, String deviceNo,
                                                      String dataType, String createStartTime, String createEndTime) {
        Map<String, Object> result = new HashMap<>();
        try {
            Page<YhyDatatypeLog> page = new Page<>(current, size);
            LambdaQueryWrapper<YhyDatatypeLog> queryWrapper = buildQueryWrapper(
                    deviceNo, dataType, createStartTime, createEndTime);

            Page<YhyDatatypeLog> yhyDatatypeLogPage = this.page(page, queryWrapper);

            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", yhyDatatypeLogPage.getRecords());
            result.put("total", yhyDatatypeLogPage.getTotal());
            result.put("current", yhyDatatypeLogPage.getCurrent());
            result.put("size", yhyDatatypeLogPage.getSize());
            result.put("pages", yhyDatatypeLogPage.getPages());
        } catch (Exception e) {
            log.error("查询心跳日志异常", e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
        }
        return result;
    }

    @Override
    public Map<String, Object> getYhyDatatypeLogById(String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            YhyDatatypeLog yhyDatatypeLog = this.getById(id);
            if (yhyDatatypeLog != null) {
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("data", yhyDatatypeLog);
            } else {
                result.put("success", false);
                result.put("message", "心跳日志不存在");
            }
        } catch (Exception e) {
            log.error("查询心跳日志异常", e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
        }
        return result;
    }

    @Override
    public Map<String, Object> getYhyDatatypeLogByDeviceNo(String deviceNo) {
        Map<String, Object> result = new HashMap<>();
        try {
            LambdaQueryWrapper<YhyDatatypeLog> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(YhyDatatypeLog::getDeviceNo, deviceNo);
            queryWrapper.orderByDesc(YhyDatatypeLog::getCreateTime);

            List<YhyDatatypeLog> yhyDatatypeLogs = this.list(queryWrapper);

            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", yhyDatatypeLogs);
            result.put("count", yhyDatatypeLogs.size());
        } catch (Exception e) {
            log.error("查询心跳日志异常", e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
        }
        return result;
    }

    @Override
    public Map<String, Object> addYhyDatatypeLog(YhyDatatypeLog yhyDatatypeLog) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 使用配置的时区获取当前时间
            LocalDateTime now = TimeZoneUtils.now();
            if (yhyDatatypeLog.getId() == null || yhyDatatypeLog.getId().trim().isEmpty()) {
                yhyDatatypeLog.setId(UUID.randomUUID().toString());
            }
            yhyDatatypeLog.setCreateTime(now);
            yhyDatatypeLog.setUpdateTime(now);

            boolean success = this.save(yhyDatatypeLog);
            if (success) {
                result.put("success", true);
                result.put("message", "心跳日志添加成功");
                result.put("data", yhyDatatypeLog);
            } else {
                result.put("success", false);
                result.put("message", "心跳日志添加失败");
            }
        } catch (Exception e) {
            log.error("添加心跳日志异常", e);
            result.put("success", false);
            result.put("message", "添加异常：" + e.getMessage());
        }
        return result;
    }

    @Override
    public Map<String, Object> updateYhyDatatypeLog(YhyDatatypeLog yhyDatatypeLog) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (yhyDatatypeLog.getId() == null || yhyDatatypeLog.getId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "心跳日志ID不能为空");
                return result;
            }

            // 使用配置的时区获取当前时间
            yhyDatatypeLog.setUpdateTime(TimeZoneUtils.now());
            boolean success = this.updateById(yhyDatatypeLog);

            if (success) {
                result.put("success", true);
                result.put("message", "心跳日志信息更新成功");
                result.put("data", yhyDatatypeLog);
            } else {
                result.put("success", false);
                result.put("message", "心跳日志信息更新失败");
            }
        } catch (Exception e) {
            log.error("更新心跳日志异常", e);
            result.put("success", false);
            result.put("message", "更新异常：" + e.getMessage());
        }
        return result;
    }

    @Override
    public Map<String, Object> deleteYhyDatatypeLog(String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = this.removeById(id);
            if (success) {
                result.put("success", true);
                result.put("message", "心跳日志删除成功");
            } else {
                result.put("success", false);
                result.put("message", "心跳日志删除失败");
            }
        } catch (Exception e) {
            log.error("删除心跳日志异常", e);
            result.put("success", false);
            result.put("message", "删除异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * 构建查询条件
     */
    private LambdaQueryWrapper<YhyDatatypeLog> buildQueryWrapper(String deviceNo, String dataType,
                                                                  String createStartTime, String createEndTime) {
        LambdaQueryWrapper<YhyDatatypeLog> queryWrapper = new LambdaQueryWrapper<>();

        // 添加查询条件
        if (deviceNo != null && !deviceNo.trim().isEmpty()) {
            queryWrapper.eq(YhyDatatypeLog::getDeviceNo, deviceNo.trim());
        }
        if (dataType != null && !dataType.trim().isEmpty()) {
            queryWrapper.eq(YhyDatatypeLog::getDataType, dataType.trim());
        }

        // 添加创建时间范围查询条件
        if (createStartTime != null && !createStartTime.trim().isEmpty()) {
            try {
                LocalDateTime startTime = LocalDateTime.parse(createStartTime, DATE_TIME_FORMATTER);
                queryWrapper.ge(YhyDatatypeLog::getCreateTime, startTime);
            } catch (Exception e) {
                log.warn("创建开始时间格式错误: {}", createStartTime);
                throw new IllegalArgumentException("创建开始时间格式错误，请使用格式：yyyy-MM-dd HH:mm:ss");
            }
        }
        if (createEndTime != null && !createEndTime.trim().isEmpty()) {
            try {
                LocalDateTime endTime = LocalDateTime.parse(createEndTime, DATE_TIME_FORMATTER);
                queryWrapper.le(YhyDatatypeLog::getCreateTime, endTime);
            } catch (Exception e) {
                log.warn("创建结束时间格式错误: {}", createEndTime);
                throw new IllegalArgumentException("创建结束时间格式错误，请使用格式：yyyy-MM-dd HH:mm:ss");
            }
        }

        // 按创建时间倒序排列
        queryWrapper.orderByDesc(YhyDatatypeLog::getCreateTime);

        return queryWrapper;
    }

}

