package com.sundot.airport.exam.controller;

import com.sundot.airport.common.core.controller.BaseController;
import com.sundot.airport.common.core.domain.AjaxResult;
import com.sundot.airport.common.utils.SecurityUtils;
import com.sundot.airport.exam.domain.WeakModuleAnalysis;
import com.sundot.airport.exam.dto.UserStatisticsDTO;
import com.sundot.airport.exam.service.IDailyStatisticsService;
import com.sundot.airport.exam.service.IWeakModuleAnalysisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <b>功能名：</b>DailyStatisticsController<br>
 * <b>说明：</b> 每日答题统计Controller <br>
 * <b>著作权：</b> Copyright (C) 2025 SUNDOT CORPORATION<br>
 * <b>修改履历：
 *
 * @author Simon Lin
 */
@RestController
@RequestMapping("/exam/daily/statistics")
public class DailyStatisticsController extends BaseController {

    @Autowired
    private IDailyStatisticsService dailyStatisticsService;

    @Autowired
    private IWeakModuleAnalysisService weakModuleAnalysisService;

    /**
     * 获取当前用户的统计数据
     */
//    @PreAuthorize("@ss.hasPermi('exam:daily:statistics:query')")
    @GetMapping("/my-statistics")
    public AjaxResult getMyStatistics() {
        Long userId = SecurityUtils.getUserId();

        try {
            UserStatisticsDTO statistics = dailyStatisticsService.getUserStatistics(userId);
            return AjaxResult.success(statistics);
        } catch (Exception e) {
            logger.error("查询统计数据失败 - userId: {}", userId, e);
            return error("查询统计数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取当前用户的薄弱模块列表
     */
    @GetMapping("/weak-modules")
    public AjaxResult getWeakModules() {
        Long userId = SecurityUtils.getUserId();

        try {
            List<WeakModuleAnalysis> weakModules = weakModuleAnalysisService.getUserWeakModules(userId);
            return AjaxResult.success(weakModules);
        } catch (Exception e) {
            logger.error("查询薄弱模块失败 - userId: {}", userId, e);
            return error("查询薄弱模块失败：" + e.getMessage());
        }
    }

    /**
     * 获取当前用户所有模块的分析数据
     */
    @GetMapping("/all-modules")
    public AjaxResult getAllModules() {
        Long userId = SecurityUtils.getUserId();

        try {
            List<WeakModuleAnalysis> allModules = weakModuleAnalysisService.getAllModuleAnalysis(userId);
            return AjaxResult.success(allModules);
        } catch (Exception e) {
            logger.error("查询模块分析数据失败 - userId: {}", userId, e);
            return error("查询模块分析数据失败：" + e.getMessage());
        }
    }

    /**
     * 手动触发薄弱模块分析更新（管理员功能）
     */
    @PreAuthorize("@ss.hasPermi('exam:daily:statistics:update') or @ss.hasRole('test') or @ss.hasRole('zhijianke')")
    @PostMapping("/update-weak-analysis/{userId}")
    public AjaxResult updateWeakAnalysis(@PathVariable Long userId) {
        try {
            weakModuleAnalysisService.updateUserWeakModuleAnalysis(userId);
            return success("薄弱模块分析更新成功");
        } catch (Exception e) {
            logger.error("更新薄弱模块分析失败 - userId: {}", userId, e);
            return error("更新失败：" + e.getMessage());
        }
    }

    /**
     * 获取全局统计数据（管理员视角）
     * 统计所有用户的任务完成情况、答题正确率、部门排名等
     */
    @PreAuthorize("@ss.hasPermi('exam:daily:statistics:admin') or @ss.hasRole('test') or @ss.hasRole('zhijianke')")
    @GetMapping("/global-statistics")
    public AjaxResult getGlobalStatistics() {
        try {
            com.sundot.airport.exam.dto.GlobalStatisticsDTO statistics = dailyStatisticsService.getGlobalStatistics();
            return AjaxResult.success(statistics);
        } catch (Exception e) {
            logger.error("查询全局统计数据失败", e);
            return error("查询全局统计数据失败：" + e.getMessage());
        }
    }
}
