package com.dora.controller;

import com.dora.common.Result;
import com.dora.dto.UvStatisticsDto;
import com.dora.service.UvStatisticsService;
import com.dora.util.IpUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * UV统计控制器 - 用户端
 * 用于记录网站访问量和获取基础统计信息
 * 
 * @author dora
 * @date 2024/12/01
 */
@Slf4j
@RestController
@RequestMapping("/user/uv")
@Tag(name = "UV统计", description = "网站访问量统计接口")
@RequiredArgsConstructor
public class UvController {

    private final UvStatisticsService uvStatisticsService;

    /**
     * 记录访问
     * 前端页面加载时调用此接口记录访问
     */
    @PostMapping("/record")
    @Operation(summary = "记录访问", description = "记录用户访问，用于UV/PV统计")
    public Result<Map<String, Object>> recordVisit(
            HttpServletRequest request,
            @Parameter(description = "页面路径") @RequestParam(required = false) String page,
            @Parameter(description = "来源页面") @RequestParam(required = false) String referrer) {
        
        try {
            // 获取客户端IP
            String clientIp = IpUtil.getClientIp(request);
            
            // 获取用户代理信息
            String userAgent = request.getHeader("User-Agent");
            
            // 记录访问
            boolean isNewVisitor = uvStatisticsService.recordVisit(clientIp, userAgent);
            
            // 构建响应数据
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("isNewVisitor", isNewVisitor);
            responseData.put("clientIp", IpUtil.maskIp(clientIp)); // 返回脱敏IP
            responseData.put("timestamp", System.currentTimeMillis());
            
            if (page != null) {
                responseData.put("page", page);
            }
            if (referrer != null) {
                responseData.put("referrer", referrer);
            }

            log.debug("记录访问成功 - IP: {}, 新访客: {}, 页面: {}", 
                     IpUtil.maskIp(clientIp), isNewVisitor, page);

            return Result.success(responseData);

        } catch (Exception e) {
            log.error("记录访问失败", e);
            return Result.error("记录访问失败：" + e.getMessage());
        }
    }

    /**
     * 获取今日UV统计
     * 公开接口，用于前端展示网站活跃度
     */
    @GetMapping("/today")
    @Operation(summary = "获取今日UV", description = "获取今日网站访问统计数据")
    public Result<Map<String, Object>> getTodayUv() {
        try {
            UvStatisticsDto todayData = uvStatisticsService.getTodayUv();
            
            // 只返回基础统计数据，不返回敏感信息
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("date", todayData.getDate());
            responseData.put("uv", todayData.getUv());
            responseData.put("pv", todayData.getPv());
            
            return Result.success(responseData);

        } catch (Exception e) {
            log.error("获取今日UV失败", e);
            return Result.error("获取统计数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取访问统计概览
     * 公开接口，展示网站基础统计信息
     */
    @GetMapping("/overview")
    @Operation(summary = "获取访问概览", description = "获取网站访问统计概览信息")
    public Result<Map<String, Object>> getUvOverview() {
        try {
            UvStatisticsDto.UvSummary summary = uvStatisticsService.getUvSummary();
            
            // 只返回适合公开展示的数据
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("todayUv", summary.getTodayUv());
            responseData.put("todayPv", summary.getTodayPv());
            responseData.put("weeklyUv", summary.getWeeklyUv());
            responseData.put("weeklyAvgUv", Math.round(summary.getWeeklyAvgUv() * 100.0) / 100.0); // 保留2位小数
            
            return Result.success(responseData);

        } catch (Exception e) {
            log.error("获取访问概览失败", e);
            return Result.error("获取统计概览失败：" + e.getMessage());
        }
    }

    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    @Operation(summary = "健康检查", description = "UV统计服务健康检查")
    public Result<String> healthCheck() {
        return Result.success("UV统计服务运行正常");
    }
}
