package org.dromara.ai.controller.admin;

import cn.dev33.satoken.annotation.SaCheckPermission;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.web.core.BaseController;
import org.dromara.ai.domain.bo.AiUsageStatsBo;
import org.dromara.ai.domain.vo.AiUsageStatsVo;
import org.dromara.ai.service.AiUsageStatsService;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * AI使用统计管理
 *
 * @author pengles
 */
@Tag(name = "管理端-AI使用统计管理", description = "AI使用统计管理接口")
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/ai/usage/stats")
public class AdminAiUsageStatsController extends BaseController {

    private final AiUsageStatsService aiUsageStatsService;

    /**
     * 查询AI使用统计列表
     */
    @Operation(summary = "查询AI使用统计列表", description = "分页查询AI使用统计列表，支持多条件搜索")
    @SaCheckPermission("ai:usage:stats:list")
    @GetMapping("/list")
    public TableDataInfo<AiUsageStatsVo> list(@Parameter(description = "使用统计查询条件") AiUsageStatsBo bo,
                                               @Parameter(description = "分页参数") PageQuery pageQuery) {
        return aiUsageStatsService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出AI使用统计列表
     */
    @Operation(summary = "导出AI使用统计列表", description = "导出AI使用统计到Excel")
    @SaCheckPermission("ai:usage:stats:export")
    @Log(title = "AI使用统计", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(@Parameter(description = "使用统计查询条件") AiUsageStatsBo bo,
                       @Parameter(description = "响应对象") HttpServletResponse response) {
        List<AiUsageStatsVo> list = aiUsageStatsService.queryList(bo);
        ExcelUtil.exportExcel(list, "AI使用统计", AiUsageStatsVo.class, response);
    }

    /**
     * 获取AI使用统计详细信息
     */
    @Operation(summary = "获取AI使用统计详情", description = "根据统计ID获取详细信息")
    @SaCheckPermission("ai:usage:stats:query")
    @GetMapping("/{id}")
    public R<AiUsageStatsVo> getInfo(@Parameter(description = "统计ID", required = true)
                                      @NotNull(message = "主键不能为空")
                                      @PathVariable Long id) {
        return R.ok(aiUsageStatsService.queryById(id));
    }

    /**
     * 获取汇总统计
     */
    @Operation(summary = "获取汇总统计", description = "获取指定时间范围内的汇总统计数据")
    @SaCheckPermission("ai:usage:stats:query")
    @GetMapping("/summary")
    public R<Map<String, Object>> getSummary(
            @Parameter(description = "开始日期") @DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(required = false) Date startDate,
            @Parameter(description = "结束日期") @DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(required = false) Date endDate) {
        return R.ok(aiUsageStatsService.getSummaryStats(startDate, endDate));
    }

    /**
     * 获取用户统计
     */
    @Operation(summary = "获取用户统计", description = "获取指定用户的统计数据")
    @SaCheckPermission("ai:usage:stats:query")
    @GetMapping("/user/{userId}")
    public R<Map<String, Object>> getUserStats(
            @Parameter(description = "用户ID", required = true) @PathVariable @NotNull Long userId,
            @Parameter(description = "开始日期") @DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(required = false) Date startDate,
            @Parameter(description = "结束日期") @DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(required = false) Date endDate) {
        return R.ok(aiUsageStatsService.getUserStats(userId, startDate, endDate));
    }

    /**
     * 获取Provider统计
     */
    @Operation(summary = "获取Provider统计", description = "获取指定Provider的统计数据")
    @SaCheckPermission("ai:usage:stats:query")
    @GetMapping("/provider/{providerName}")
    public R<Map<String, Object>> getProviderStats(
            @Parameter(description = "Provider名称", required = true) @PathVariable @NotNull String providerName,
            @Parameter(description = "开始日期") @DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(required = false) Date startDate,
            @Parameter(description = "结束日期") @DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(required = false) Date endDate) {
        return R.ok(aiUsageStatsService.getProviderStats(providerName, startDate, endDate));
    }

    /**
     * 获取趋势数据
     */
    @Operation(summary = "获取趋势数据", description = "获取指定时间范围内的趋势数据（支持按日/周/月分组）")
    @SaCheckPermission("ai:usage:stats:query")
    @GetMapping("/trend")
    public R<List<Map<String, Object>>> getTrend(
            @Parameter(description = "开始日期") @DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(required = false) Date startDate,
            @Parameter(description = "结束日期") @DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(required = false) Date endDate,
            @Parameter(description = "分组方式（day/week/month）") @RequestParam(defaultValue = "day") String groupBy) {
        return R.ok(aiUsageStatsService.getTrendData(startDate, endDate, groupBy));
    }

}
