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.YhyAudioUploadLog;
import com.rj.mapper.YhyAudioUploadLogMapper;
import com.rj.service.IYhyAudioUploadLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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-29
 */
@Slf4j
@Service
public class YhyAudioUploadLogServiceImpl extends ServiceImpl<YhyAudioUploadLogMapper, YhyAudioUploadLog> implements IYhyAudioUploadLogService {

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

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

            Page<YhyAudioUploadLog> yhyAudioUploadLogPage = this.page(page, queryWrapper);

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

    @Override
    public Map<String, Object> getYhyAudioUploadLogById(String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            YhyAudioUploadLog yhyAudioUploadLog = this.getById(id);
            if (yhyAudioUploadLog != null) {
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("data", yhyAudioUploadLog);
            } 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> getYhyAudioUploadLogByDeviceNo(String deviceNo) {
        Map<String, Object> result = new HashMap<>();
        try {
            LambdaQueryWrapper<YhyAudioUploadLog> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(YhyAudioUploadLog::getDeviceNo, deviceNo);
            queryWrapper.orderByDesc(YhyAudioUploadLog::getCreateTime);

            List<YhyAudioUploadLog> yhyAudioUploadLogs = this.list(queryWrapper);

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

    @Override
    public Map<String, Object> addYhyAudioUploadLog(YhyAudioUploadLog yhyAudioUploadLog) {
        Map<String, Object> result = new HashMap<>();
        try {
            LocalDateTime now = LocalDateTime.now();
            if (yhyAudioUploadLog.getId() == null || yhyAudioUploadLog.getId().trim().isEmpty()) {
                yhyAudioUploadLog.setId(UUID.randomUUID().toString());
            }
            yhyAudioUploadLog.setCreateTime(now);
            yhyAudioUploadLog.setUpdateTime(now);

            boolean success = this.save(yhyAudioUploadLog);
            if (success) {
                result.put("success", true);
                result.put("message", "音频上传日志添加成功");
                result.put("data", yhyAudioUploadLog);
            } 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> updateYhyAudioUploadLog(YhyAudioUploadLog yhyAudioUploadLog) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (yhyAudioUploadLog.getId() == null || yhyAudioUploadLog.getId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "音频上传日志ID不能为空");
                return result;
            }

            yhyAudioUploadLog.setUpdateTime(LocalDateTime.now());
            boolean success = this.updateById(yhyAudioUploadLog);

            if (success) {
                result.put("success", true);
                result.put("message", "音频上传日志信息更新成功");
                result.put("data", yhyAudioUploadLog);
            } 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> deleteYhyAudioUploadLog(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<YhyAudioUploadLog> buildQueryWrapper(String deviceNo, String startTime,
                                                                   String endTime, String createStartTime,
                                                                   String createEndTime) {
        LambdaQueryWrapper<YhyAudioUploadLog> queryWrapper = new LambdaQueryWrapper<>();

        // 添加设备号查询条件
        if (deviceNo != null && !deviceNo.trim().isEmpty()) {
            queryWrapper.eq(YhyAudioUploadLog::getDeviceNo, deviceNo.trim());
        }

        // 添加开始时间范围查询条件（start_time字段是varchar类型，存储格式：251129185131）
        if (startTime != null && !startTime.trim().isEmpty()) {
            queryWrapper.ge(YhyAudioUploadLog::getStartTime, startTime.trim());
        }
        if (endTime != null && !endTime.trim().isEmpty()) {
            queryWrapper.le(YhyAudioUploadLog::getEndTime, endTime.trim());
        }

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

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

        return queryWrapper;
    }
}

