package com.lesingle.edu.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lesingle.edu.common.annotation.Log;
import com.lesingle.edu.common.enums.LogModule;
import com.lesingle.edu.common.enums.LogOperationType;
import com.lesingle.edu.common.annotation.RequireRole;
import com.lesingle.edu.common.enums.CourseStatus;
import com.lesingle.edu.common.enums.UserRole;
import com.lesingle.edu.common.response.PageResult;
import com.lesingle.edu.common.response.Result;
import com.lesingle.edu.dto.request.CourseCreateRequest;
import com.lesingle.edu.dto.request.CoursePageQueryRequest;
import com.lesingle.edu.dto.request.CourseUpdateRequest;
import com.lesingle.edu.dto.request.CourseRejectRequest;
import com.lesingle.edu.dto.response.CoursePackageStatsResponse;
import com.lesingle.edu.dto.response.CourseResponse;
import com.lesingle.edu.entity.CoursePackage;
import com.lesingle.edu.service.CoursePackageStatsService;
import com.lesingle.edu.service.CoursePackageService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 课程包管理控制器（超管端）
 * 管理通过7步创建流程创建的课程包
 */
@RestController
@RequestMapping("/api/v1/admin/packages")
@RequiredArgsConstructor
@Slf4j
@RequireRole(UserRole.ADMIN)
@Tag(name = "超管端 - 课程包管理")
public class AdminCourseController {

    private final CoursePackageService courseService;
    private final CoursePackageStatsService coursePackageStatsService;

    @PostMapping
    @Log(module = LogModule.COURSE_PACKAGE, type = LogOperationType.CREATE, description = "创建课程包")
    @Operation(summary = "创建课程包")
    public Result<CourseResponse> createCourse(@Valid @RequestBody CourseCreateRequest request) {
        log.info("收到课程包创建请求，name={}, themeId={}, gradeTags={}", request.getName(), request.getThemeId(), request.getGradeTags());
        try {
            CoursePackage course = courseService.createSystemCourse(request);
            log.info("课程包创建成功，id={}", course.getId());
            return Result.success(courseService.getCourseByIdWithLessons(course.getId()));
        } catch (Exception e) {
            log.error("课程包创建失败", e);
            throw e;
        }
    }

    @PutMapping("/{id}")
    @Log(module = LogModule.COURSE_PACKAGE, type = LogOperationType.UPDATE, description = "更新课程包")
    @Operation(summary = "更新课程包")
    public Result<CourseResponse> updateCourse(@PathVariable Long id, @RequestBody CourseUpdateRequest request) {
        courseService.updateCourse(id, request);
        return Result.success(courseService.getCourseByIdWithLessons(id));
    }

    @GetMapping("/{id}")
    @Operation(summary = "查询课程包详情")
    public Result<CourseResponse> getCourse(@PathVariable Long id) {
        return Result.success(courseService.getCourseByIdWithLessons(id));
    }

    @GetMapping
    @Operation(summary = "分页查询课程包")
    public Result<PageResult<CourseResponse>> getCoursePage(CoursePageQueryRequest request) {
        log.info("查询课程列表，pageNum={}, pageSize={}, keyword={}, category={}, status={}, gradeTags={}, reviewOnly={}",
                request.getPageNum(), request.getPageSize(), request.getKeyword(), request.getCategory(), request.getStatus(), request.getGradeTags(), request.getReviewOnly());
        // 页码
        // 每页数量
        // 关键词
        // 分类
        // 状态
        // 年级筛选
        // 是否仅查询待审核
        Page<CoursePackage> page = courseService.getSystemCoursePage(
                request.getPageNum(),
                request.getPageSize(),
                request.getKeyword(),
                request.getCategory(),
                request.getStatus(),
                request.getGradeTags(),
                request.getReviewOnly());

        // 转换为 CourseResponse
        List<CourseResponse> responseList = page.getRecords().stream()
                .map(course -> courseService.getCourseByIdWithLessons(course.getId()))
                .collect(Collectors.toList());

        // 合并实时统计数据（使用次数、教师数、平均评分）
        List<Long> packageIds = responseList.stream().map(CourseResponse::getId).collect(Collectors.toList());
        Map<Long, CoursePackageStatsService.PackageStats> statsMap = coursePackageStatsService.getBatchStats(packageIds);
        for (CourseResponse resp : responseList) {
            CoursePackageStatsService.PackageStats stats = statsMap.get(resp.getId());
            if (stats != null) {
                resp.setUsageCount(stats.usageCount());
                resp.setTeacherCount(stats.teacherCount());
                resp.setAvgRating(stats.avgRating());
            }
        }

        PageResult<CourseResponse> result = PageResult.of(responseList, page.getTotal(), page.getCurrent(), page.getSize());
        log.info("课程包列表查询结果，total={}, list={}", result.getTotal(), result.getList().size());
        return Result.success(result);
    }

    @DeleteMapping("/{id}")
    @Log(module = LogModule.COURSE_PACKAGE, type = LogOperationType.DELETE, description = "删除课程包")
    @Operation(summary = "删除课程包")
    public Result<Void> deleteCourse(@PathVariable Long id) {
        courseService.deleteCourse(id);
        return Result.success();
    }

    @PostMapping("/{id}/publish")
    @Log(module = LogModule.COURSE_PACKAGE, type = LogOperationType.UPDATE, description = "发布课程包")
    @Operation(summary = "发布课程包")
    public Result<Void> publishCourse(@PathVariable Long id) {
        courseService.publishCourse(id);
        return Result.success();
    }

    @PostMapping("/{id}/archive")
    @Log(module = LogModule.COURSE_PACKAGE, type = LogOperationType.UPDATE, description = "归档课程包")
    @Operation(summary = "归档课程包")
    public Result<Void> archiveCourse(@PathVariable Long id) {
        courseService.archiveCourse(id);
        return Result.success();
    }

    @PostMapping("/{id}/submit")
    @Log(module = LogModule.COURSE_PACKAGE, type = LogOperationType.UPDATE, description = "提交课程包审核")
    @Operation(summary = "提交课程包审核")
    public Result<Void> submitCourse(@PathVariable Long id) {
        courseService.submitCourse(id);
        return Result.success();
    }

    @PostMapping("/{id}/reject")
    @Log(module = LogModule.COURSE_PACKAGE, type = LogOperationType.UPDATE, description = "驳回课程包审核")
    @Operation(summary = "驳回课程包审核")
    public Result<Void> rejectCourse(@PathVariable Long id, @Valid @RequestBody CourseRejectRequest request) {
        courseService.rejectCourse(id, request.getComment());
        return Result.success();
    }

    @GetMapping("/{id}/stats")
    @Operation(summary = "获取课程包数据统计")
    public Result<CoursePackageStatsResponse> getCourseStats(@PathVariable Long id) {
        return Result.success(coursePackageStatsService.getStats(id));
    }

    @GetMapping("/all")
    @Operation(summary = "获取所有已发布的课程包")
    public Result<List<CourseResponse>> getAllPublishedCourses() {
        log.info("获取所有已发布的课程包");
        List<CoursePackage> courses = courseService.list(
                new LambdaQueryWrapper<CoursePackage>()
                        .eq(CoursePackage::getStatus, CourseStatus.PUBLISHED.getCode())
                        .orderByDesc(CoursePackage::getUsageCount));
        List<CourseResponse> responseList = courses.stream()
                .map(course -> courseService.getCourseByIdWithLessons(course.getId()))
                .collect(Collectors.toList());
        return Result.success(responseList);
    }

}
