package org.xyzh.study.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.xyzh.common.core.domain.ResultDomain;
import org.xyzh.common.core.page.PageDomain;
import org.xyzh.common.core.page.PageRequest;
import org.xyzh.common.dto.study.TbLearningHistory;
import org.xyzh.common.vo.LearningHistoryVO;
import org.xyzh.common.vo.LearningStatisticsVO;
import org.xyzh.study.service.SCLearningHistoryService;

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

/**
 * @description 学习历史控制器
 * @filename LearningHistoryController.java
 * @author yslg
 * @copyright xyzh
 * @since 2025-10-27
 */
@RestController
@RequestMapping("/study/history")
public class LearningHistoryController {
    
    private static final Logger logger = LoggerFactory.getLogger(LearningHistoryController.class);

    @Autowired
    private SCLearningHistoryService learningHistoryService;

    /**
     * 记录学习历史
     * POST /study/history/record
     * 
     * @param learningHistory 学习历史
     * @return ResultDomain<TbLearningHistory> 记录结果
     */
    @PostMapping("/record")
    public ResultDomain<TbLearningHistory> recordLearningHistory(@RequestBody TbLearningHistory learningHistory) {
        logger.info("记录学习历史，资源类型: {}, 资源ID: {}", learningHistory.getResourceType(), learningHistory.getResourceID());
        return learningHistoryService.recordLearningHistory(learningHistory);
    }

    /**
     * 批量记录学习历史
     * POST /study/history/batch-record
     * 
     * @param historyList 学习历史列表
     * @return ResultDomain<Boolean> 记录结果
     */
    @PostMapping("/batch-record")
    public ResultDomain<Boolean> batchRecordLearningHistory(@RequestBody List<TbLearningHistory> historyList) {
        logger.info("批量记录学习历史，数量: {}", historyList != null ? historyList.size() : 0);
        return learningHistoryService.batchRecordLearningHistory(historyList);
    }

    /**
     * 查询学习历史列表
     * POST /study/history/list
     * 
     * @param filter 过滤条件
     * @return ResultDomain<LearningHistoryVO> 学习历史列表
     */
    @PostMapping("/list")
    public ResultDomain<LearningHistoryVO> getLearningHistories(@RequestBody TbLearningHistory filter) {
        logger.info("查询学习历史列表，用户ID: {}", filter != null ? filter.getUserID() : null);
        return learningHistoryService.getLearningHistories(filter);
    }

    /**
     * 分页查询学习历史
     * POST /study/history/page
     * 
     * @param pageRequest 分页查询请求
     * @return ResultDomain<PageDomain<LearningHistoryVO>> 分页结果
     */
    @PostMapping("/page")
    public ResultDomain<PageDomain<LearningHistoryVO>> getLearningHistoriesPage(@RequestBody PageRequest<TbLearningHistory> pageRequest) {
        logger.info("分页查询学习历史，页码: {}, 每页数量: {}", 
            pageRequest.getPageParam() != null ? pageRequest.getPageParam().getPageNumber() : null,
            pageRequest.getPageParam() != null ? pageRequest.getPageParam().getPageSize() : null);
        return learningHistoryService.getLearningHistoriesPage(pageRequest);
    }

    /**
     * 根据ID查询学习历史
     * GET /study/history/{id}
     * 
     * @param id 历史记录ID
     * @return ResultDomain<TbLearningHistory> 学习历史
     */
    @GetMapping("/{id}")
    public ResultDomain<TbLearningHistory> getLearningHistoryById(@PathVariable String id) {
        logger.info("查询学习历史，ID: {}", id);
        return learningHistoryService.getLearningHistoryById(id);
    }

    /**
     * 获取当前用户的学习历史
     * POST /study/history/my-histories
     * 
     * @param filter 过滤条件
     * @return ResultDomain<LearningHistoryVO> 学习历史列表
     */
    @PostMapping("/my-histories")
    public ResultDomain<LearningHistoryVO> getCurrentUserLearningHistories(@RequestBody(required = false) TbLearningHistory filter) {
        logger.info("查询当前用户学习历史");
        return learningHistoryService.getCurrentUserLearningHistories(filter);
    }

    /**
     * 获取当前用户最近的学习历史
     * GET /study/history/recent
     * 
     * @param limit 限制数量（可选，默认10）
     * @return ResultDomain<LearningHistoryVO> 学习历史列表
     */
    @GetMapping("/recent")
    public ResultDomain<LearningHistoryVO> getRecentLearningHistories(@RequestParam(required = false, defaultValue = "10") Integer limit) {
        logger.info("查询最近学习历史，限制数量: {}", limit);
        // 从当前登录用户获取
        return learningHistoryService.getRecentLearningHistories(null, limit);
    }

    /**
     * 获取用户学习统计（按时间范围）
     * GET /study/history/statistics
     * 
     * @param userId 用户ID
     * @param startTime 开始时间（时间戳，毫秒）
     * @param endTime 结束时间（时间戳，毫秒）
     * @return ResultDomain<LearningStatisticsVO> 学习统计
     */
    @GetMapping("/statistics")
    public ResultDomain<LearningStatisticsVO> getUserLearningStatistics(
            @RequestParam String userId,
            @RequestParam Long startTime,
            @RequestParam Long endTime) {
        logger.info("查询学习统计，用户ID: {}, 开始时间: {}, 结束时间: {}", userId, startTime, endTime);
        return learningHistoryService.getUserLearningStatistics(
            userId, 
            new Date(startTime), 
            new Date(endTime)
        );
    }

    /**
     * 获取用户学习统计（按周期）
     * GET /study/history/statistics/{userId}/{periodType}
     * 
     * @param userId 用户ID
     * @param periodType 周期类型（day/week/month）
     * @return ResultDomain<LearningStatisticsVO> 学习统计
     */
    @GetMapping("/statistics/{userId}/{periodType}")
    public ResultDomain<LearningStatisticsVO> getUserLearningStatisticsByPeriod(
            @PathVariable String userId,
            @PathVariable String periodType) {
        logger.info("查询学习统计，用户ID: {}, 周期类型: {}", userId, periodType);
        return learningHistoryService.getUserLearningStatisticsByPeriod(userId, periodType);
    }

    /**
     * 获取当前用户的学习统计
     * GET /study/history/my-statistics/{periodType}
     * 
     * @param periodType 周期类型（day/week/month）
     * @return ResultDomain<LearningStatisticsVO> 学习统计
     */
    @GetMapping("/my-statistics/{periodType}")
    public ResultDomain<LearningStatisticsVO> getCurrentUserLearningStatistics(@PathVariable String periodType) {
        logger.info("查询当前用户学习统计，周期类型: {}", periodType);
        return learningHistoryService.getCurrentUserLearningStatistics(periodType);
    }

    /**
     * 删除学习历史
     * DELETE /study/history/{id}
     * 
     * @param id 历史记录ID
     * @return ResultDomain<Boolean> 删除结果
     */
    @DeleteMapping("/{id}")
    public ResultDomain<Boolean> deleteLearningHistory(@PathVariable String id) {
        logger.info("删除学习历史，ID: {}", id);
        return learningHistoryService.deleteLearningHistory(id);
    }

    /**
     * 批量删除学习历史
     * DELETE /study/history/batch
     * 
     * @param ids 历史记录ID列表
     * @return ResultDomain<Boolean> 删除结果
     */
    @DeleteMapping("/batch")
    public ResultDomain<Boolean> batchDeleteLearningHistories(@RequestBody List<String> ids) {
        logger.info("批量删除学习历史，数量: {}", ids != null ? ids.size() : 0);
        return learningHistoryService.batchDeleteLearningHistories(ids);
    }

    /**
     * 健康检查
     * GET /study/history/health
     * 
     * @return ResultDomain<String> 健康状态
     */
    @GetMapping("/health")
    public ResultDomain<String> health() {
        ResultDomain<String> resultDomain = new ResultDomain<>();
        resultDomain.success("学习历史服务运行正常", "OK");
        return resultDomain;
    }
}

