using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using ToolHub.Services;
using ToolHub.Models;
namespace ToolHub.Controllers;
[Authorize(Roles = "Admin")]
public class ToolStatisticsController : Controller
{
private readonly IToolService _toolService;
public ToolStatisticsController(IToolService toolService)
{
_toolService = toolService;
}
///
/// 获取工具统计数据页面
///
public async Task Index(int toolId = 0)
{
ViewData["Title"] = "工具统计";
if (toolId > 0)
{
var tool = await _toolService.GetToolByIdAsync(toolId);
if (tool != null)
{
ViewData["ToolName"] = tool.Name;
ViewData["ToolId"] = toolId;
}
}
return View();
}
///
/// 获取工具统计数据
///
[HttpGet]
public async Task GetToolStatistics(int toolId, DateTime? date = null)
{
try
{
var targetDate = date ?? DateTime.Today;
var stats = await _toolService.GetToolStatisticsAsync(toolId, targetDate);
return Json(new { success = true, data = stats });
}
catch (Exception ex)
{
return Json(new { success = false, message = ex.Message });
}
}
///
/// 获取工具访问记录
///
[HttpGet]
public async Task GetToolAccessRecords(int toolId, DateTime? startDate = null, DateTime? endDate = null, int limit = 100)
{
try
{
var records = await _toolService.GetToolAccessRecordsAsync(toolId, startDate, endDate, limit);
return Json(new { success = true, data = records });
}
catch (Exception ex)
{
return Json(new { success = false, message = ex.Message });
}
}
///
/// 获取用户访问记录
///
[HttpGet]
public async Task GetUserAccessRecords(int userId, DateTime? startDate = null, DateTime? endDate = null, int limit = 100)
{
try
{
var records = await _toolService.GetUserToolAccessRecordsAsync(userId, startDate, endDate, limit);
return Json(new { success = true, data = records });
}
catch (Exception ex)
{
return Json(new { success = false, message = ex.Message });
}
}
///
/// 获取工具使用趋势
///
[HttpGet]
public async Task GetToolUsageTrend(int toolId, int days = 30)
{
try
{
var trend = await _toolService.GetToolUsageTrendAsync(toolId, days);
return Json(new { success = true, data = trend });
}
catch (Exception ex)
{
return Json(new { success = false, message = ex.Message });
}
}
///
/// 获取热门工具
///
[HttpGet]
public async Task GetPopularTools(int count = 10, DateTime? startDate = null)
{
try
{
var tools = await _toolService.GetPopularToolsAsync(count, startDate);
return Json(new { success = true, data = tools });
}
catch (Exception ex)
{
return Json(new { success = false, message = ex.Message });
}
}
///
/// 记录工具操作
///
[HttpPost]
public async Task RecordToolAction([FromBody] RecordToolActionRequest request)
{
try
{
await _toolService.RecordToolActionAsync(request.ToolId, request.ActionType, request.Duration);
return Json(new { success = true });
}
catch (Exception ex)
{
return Json(new { success = false, message = ex.Message });
}
}
}
public class RecordToolActionRequest
{
public int ToolId { get; set; }
public string ActionType { get; set; } = "view";
public int Duration { get; set; } = 0;
}