package com.dora.controller;

import com.dora.common.Result;
import com.dora.dto.ToolDto;
import com.dora.service.AdminToolConfigService;
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.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

/**
 * 管理端工具配置控制器
 */
@Slf4j
@RestController
@RequestMapping("/admin/tools")
@Tag(name = "工具配置管理（管理端）", description = "管理端API - 工具配置和使用统计")
@RequiredArgsConstructor
@PreAuthorize("hasRole('ADMIN')")
public class AdminToolConfigController {

    private final AdminToolConfigService adminToolConfigService;

    // ==================== 工具配置管理 ====================

    /**
     * 获取所有工具配置
     */
    @GetMapping("/configs")
    @Operation(summary = "获取所有工具配置", description = "获取所有工具配置列表")
    public Result<List<ToolDto.ConfigResponse>> getAllConfigs() {
        try {
            List<ToolDto.ConfigResponse> configs = adminToolConfigService.getAllConfigs();
            return Result.success(configs);
        } catch (Exception e) {
            log.error("获取工具配置列表失败", e);
            return Result.error("获取配置列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取工具配置详情
     */
    @GetMapping("/configs/{id}")
    @Operation(summary = "获取工具配置详情", description = "根据ID获取工具配置详情")
    public Result<ToolDto.ConfigResponse> getConfigById(
            @Parameter(description = "工具ID", required = true)
            @PathVariable Long id) {
        try {
            ToolDto.ConfigResponse config = adminToolConfigService.getConfigById(id);
            return Result.success(config);
        } catch (Exception e) {
            log.error("获取工具配置详情失败: id={}", id, e);
            return Result.error("获取配置详情失败: " + e.getMessage());
        }
    }

    /**
     * 创建工具配置
     */
    @PostMapping("/configs")
    @Operation(summary = "创建工具配置", description = "创建新的工具配置")
    public Result<ToolDto.ConfigResponse> createConfig(@RequestBody ToolDto.ConfigRequest request) {
        try {
            ToolDto.ConfigResponse config = adminToolConfigService.createConfig(request);
            return Result.success(config, "创建成功");
        } catch (Exception e) {
            log.error("创建工具配置失败", e);
            return Result.error("创建失败: " + e.getMessage());
        }
    }

    /**
     * 更新工具配置
     */
    @PutMapping("/configs/{id}")
    @Operation(summary = "更新工具配置", description = "更新指定工具配置")
    public Result<ToolDto.ConfigResponse> updateConfig(
            @Parameter(description = "工具ID", required = true)
            @PathVariable Long id,
            @RequestBody ToolDto.ConfigRequest request) {
        try {
            ToolDto.ConfigResponse config = adminToolConfigService.updateConfig(id, request);
            return Result.success(config, "更新成功");
        } catch (Exception e) {
            log.error("更新工具配置失败: id={}", id, e);
            return Result.error("更新失败: " + e.getMessage());
        }
    }

    /**
     * 更新工具积分消耗
     */
    @PatchMapping("/configs/{id}/points-cost")
    @Operation(summary = "更新积分消耗", description = "单独更新工具的积分消耗配置")
    public Result<Void> updatePointsCost(
            @Parameter(description = "工具ID", required = true)
            @PathVariable Long id,
            @Parameter(description = "积分消耗", required = true)
            @RequestParam Integer pointsCost) {
        try {
            boolean success = adminToolConfigService.updatePointsCost(id, pointsCost);
            return success ? Result.success(null, "更新成功") : Result.error("更新失败");
        } catch (Exception e) {
            log.error("更新积分消耗失败: id={}, pointsCost={}", id, pointsCost, e);
            return Result.error("更新失败: " + e.getMessage());
        }
    }

    /**
     * 更新工具状态
     */
    @PatchMapping("/configs/{id}/status")
    @Operation(summary = "更新工具状态", description = "启用或禁用工具")
    public Result<Void> updateStatus(
            @Parameter(description = "工具ID", required = true)
            @PathVariable Long id,
            @Parameter(description = "是否启用（0禁用/1启用）", required = true)
            @RequestParam Integer isEnabled) {
        try {
            boolean success = adminToolConfigService.updateStatus(id, isEnabled);
            return success ? Result.success(null, "更新成功") : Result.error("更新失败");
        } catch (Exception e) {
            log.error("更新工具状态失败: id={}, isEnabled={}", id, isEnabled, e);
            return Result.error("更新失败: " + e.getMessage());
        }
    }

    /**
     * 删除工具配置
     */
    @DeleteMapping("/configs/{id}")
    @Operation(summary = "删除工具配置", description = "删除指定工具配置（逻辑删除）")
    public Result<Void> deleteConfig(
            @Parameter(description = "工具ID", required = true)
            @PathVariable Long id) {
        try {
            boolean success = adminToolConfigService.deleteConfig(id);
            return success ? Result.success(null, "删除成功") : Result.error("删除失败");
        } catch (Exception e) {
            log.error("删除工具配置失败: id={}", id, e);
            return Result.error("删除失败: " + e.getMessage());
        }
    }

    // ==================== 使用统计 ====================

    /**
     * 获取工具统计信息
     */
    @GetMapping("/stats/info")
    @Operation(summary = "获取统计概览", description = "获取工具数量和今日调用统计")
    public Result<AdminToolConfigService.ToolStatsInfo> getStatsInfo() {
        try {
            AdminToolConfigService.ToolStatsInfo info = adminToolConfigService.getToolStatsInfo();
            return Result.success(info);
        } catch (Exception e) {
            log.error("获取统计信息失败", e);
            return Result.error("获取统计信息失败: " + e.getMessage());
        }
    }

    /**
     * 获取统计汇总
     */
    @GetMapping("/stats/summary")
    @Operation(summary = "获取统计汇总", description = "获取指定日期范围内的统计汇总")
    public Result<ToolDto.StatsSummaryResponse> getStatsSummary(
            @Parameter(description = "开始日期（yyyy-MM-dd）")
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @Parameter(description = "结束日期（yyyy-MM-dd）")
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        try {
            ToolDto.StatsSummaryResponse summary = adminToolConfigService.getStatsSummary(startDate, endDate);
            return Result.success(summary);
        } catch (Exception e) {
            log.error("获取统计汇总失败", e);
            return Result.error("获取统计汇总失败: " + e.getMessage());
        }
    }

    /**
     * 获取每日统计
     */
    @GetMapping("/stats/daily")
    @Operation(summary = "获取每日统计", description = "获取每日统计数据列表")
    public Result<List<ToolDto.DailyStatsResponse>> getDailyStats(
            @Parameter(description = "开始日期（yyyy-MM-dd）")
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @Parameter(description = "结束日期（yyyy-MM-dd）")
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
            @Parameter(description = "工具编码（可选）")
            @RequestParam(required = false) String toolCode) {
        try {
            List<ToolDto.DailyStatsResponse> stats = adminToolConfigService.getDailyStats(startDate, endDate, toolCode);
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取每日统计失败", e);
            return Result.error("获取每日统计失败: " + e.getMessage());
        }
    }

    /**
     * 刷新每日统计
     */
    @PostMapping("/stats/refresh")
    @Operation(summary = "刷新每日统计", description = "手动刷新指定日期的统计数据")
    public Result<Void> refreshDailyStats(
            @Parameter(description = "日期（yyyy-MM-dd），默认今天")
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
        try {
            adminToolConfigService.refreshDailyStats(date);
            return Result.success(null, "刷新成功");
        } catch (Exception e) {
            log.error("刷新统计失败: date={}", date, e);
            return Result.error("刷新失败: " + e.getMessage());
        }
    }
}
