package com.yupi.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.project.common.BaseResponse;
import com.yupi.project.common.ErrorCode;
import com.yupi.project.common.ResultUtils;
import com.yupi.project.exception.BusinessException;
import com.yupi.project.model.dto.mqttlog.MqttLogQueryRequest;
import com.yupi.project.model.entity.MqttCommunicationLog;
import com.yupi.project.service.MqttCommunicationLogService;
import com.yupi.project.annotation.AuthCheck;
import com.yupi.project.constant.UserConstant;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@RestController
@RequestMapping("/admin/mqtt-log")
@RequiredArgsConstructor
@Slf4j
public class MqttCommunicationLogController {

    private final MqttCommunicationLogService mqttCommunicationLogService;

    /**
     * 分页获取MQTT通信日志列表
     *
     * @param mqttLogQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<MqttCommunicationLog>> listMqttCommunicationLogsByPage(@RequestBody MqttLogQueryRequest mqttLogQueryRequest, HttpServletRequest request) {
        if (mqttLogQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = mqttLogQueryRequest.getCurrent();
        long size = mqttLogQueryRequest.getPageSize();
        // 限制爬虫
        if (size > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求数据量过大");
        }

        QueryWrapper<MqttCommunicationLog> queryWrapper = getQueryWrapper(mqttLogQueryRequest);
        Page<MqttCommunicationLog> logPage = mqttCommunicationLogService.page(new Page<>(current, size), queryWrapper);
        return ResultUtils.success(logPage);
    }

    private QueryWrapper<MqttCommunicationLog> getQueryWrapper(MqttLogQueryRequest queryRequest) {
        QueryWrapper<MqttCommunicationLog> queryWrapper = new QueryWrapper<>();
        if (queryRequest == null) {
            return queryWrapper;
        }

        String messageId = queryRequest.getMessageId();
        String direction = queryRequest.getDirection();
        String clientId = queryRequest.getClientId();
        String topic = queryRequest.getTopic();
        String payloadContains = queryRequest.getPayloadContains();
        Integer qos = queryRequest.getQos();
        Date startTime = queryRequest.getStartTime();
        Date endTime = queryRequest.getEndTime();
        Long relatedSessionId = queryRequest.getRelatedSessionId();
        Long relatedTaskId = queryRequest.getRelatedTaskId();
        String sortField = queryRequest.getSortField();
        String sortOrder = queryRequest.getSortOrder();

        if (StringUtils.isNotBlank(messageId)) {
            queryWrapper.like("message_id", messageId);
        }
        if (StringUtils.isNotBlank(direction)) {
            queryWrapper.eq("direction", direction);
        }
        if (StringUtils.isNotBlank(clientId)) {
            queryWrapper.like("client_id", clientId);
        }
        if (StringUtils.isNotBlank(topic)) {
            queryWrapper.like("topic", topic);
        }
        if (StringUtils.isNotBlank(payloadContains)) {
            queryWrapper.like("payload", payloadContains);
        }
        if (qos != null) {
            queryWrapper.eq("qos", qos);
        }
        if (startTime != null) {
            queryWrapper.ge("log_timestamp", startTime);
        }
        if (endTime != null) {
            queryWrapper.le("log_timestamp", endTime);
        }
        if (relatedSessionId != null) {
            queryWrapper.eq("related_session_id", relatedSessionId);
        }
        if (relatedTaskId != null) {
            queryWrapper.eq("related_task_id", relatedTaskId);
        }

        // 默认按日志时间降序排序
        if (StringUtils.isNotBlank(sortField)) {
            boolean isAsc = "asc".equalsIgnoreCase(sortOrder);
            queryWrapper.orderBy(true, isAsc, sortField);
        } else {
            queryWrapper.orderByDesc("log_timestamp");
        }
        return queryWrapper;
    }
} 