package com.lesingle.edu.controller.school;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lesingle.edu.common.response.PageResult;
import com.lesingle.edu.common.response.Result;
import com.lesingle.edu.common.security.SecurityUtils;
import com.lesingle.edu.dto.response.CourseResponse;
import com.lesingle.edu.dto.response.LessonTagResponse;
import com.lesingle.edu.dto.response.SchoolCourseResponse;
import com.lesingle.edu.entity.CourseLesson;
import com.lesingle.edu.entity.CoursePackage;
import com.lesingle.edu.mapper.LessonMapper;
import com.lesingle.edu.service.CourseLessonService;
import com.lesingle.edu.service.CoursePackageService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

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

/**
 * 课程管理控制器（学校端）
 * gradeTags/domainTags 规范为 String[]，与套餐管理适用年级对齐
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/school/courses")
@RequiredArgsConstructor
@Tag(name = "学校端 - 课程管理")
public class SchoolCourseController {

    private final CoursePackageService courseService;
    private final CourseLessonService courseLessonService;
    private final LessonMapper lessonMapper;

    @GetMapping
    @Operation(summary = "获取学校课程包列表（分页）")
    public Result<PageResult<SchoolCourseResponse>> getSchoolCourses(
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String grade,
            @RequestParam(required = false) String domain,
            @RequestParam(required = false) String lessonType) {
        log.info("获取学校课程包列表（分页），pageNum={}, pageSize={}, keyword={}, grade={}, domain={}, lessonType={}",
                pageNum, pageSize, keyword, grade, domain, lessonType);
        Long tenantId = SecurityUtils.getCurrentTenantId();

        // 使用分页查询方法
        Page<CoursePackage> page = courseService.getTenantPackageCoursePage(
                tenantId, pageNum, pageSize, keyword, grade, domain, lessonType, null);

        List<SchoolCourseResponse> list = page.getRecords().stream()
                .map(SchoolCourseResponse::toSchoolCourseResponse)
                .collect(Collectors.toList());

        // 按租户 ID 统计每个课程的使用次数（已完成状态的 Lesson 数量）
        if (!list.isEmpty()) {
            List<Long> courseIds = list.stream().map(SchoolCourseResponse::getId).collect(Collectors.toList());
            List<Map<String, Object>> usageStats = lessonMapper.countUsageByTenantAndCourseIds(tenantId, courseIds);

            // 构建课程 ID -> 使用次数的映射
            Map<Long, Integer> usageCountMap = usageStats.stream()
                    .collect(Collectors.toMap(
                            m -> ((Number) m.get("course_id")).longValue(),
                            m -> ((Number) m.get("usageCount")).intValue(),
                            (v1, v2) -> v1 // 如果有重复，取第一个值
                    ));

            // 填充 usageCount，如果没有统计数据显示为 0
            for (SchoolCourseResponse vo : list) {
                vo.setUsageCount(usageCountMap.getOrDefault(vo.getId(), 0));
            }
        }

        // 填充 lessonTags
        for (SchoolCourseResponse vo : list) {
            List<CourseLesson> lessons = courseLessonService.findByCourseId(vo.getId());
            vo.setLessonTags(lessons.stream()
                    .map(l -> LessonTagResponse.builder()
                            .name(l.getName())
                            .lessonType(l.getLessonType())
                            .build())
                    .collect(Collectors.toList()));
        }

        return Result.success(PageResult.of(list, page.getTotal(), page.getCurrent(), page.getSize()));
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取课程详情（包含课程环节、介绍、资源等完整信息）")
    public Result<CourseResponse> getSchoolCourse(@PathVariable Long id) {
        log.info("获取课程详情，id={}", id);
        Long tenantId = SecurityUtils.getCurrentTenantId();
        // 验证权限
        courseService.getCourseByIdWithTenantCheck(id, tenantId);
        // 返回完整详情（与教师端一致）
        return Result.success(courseService.getCourseByIdWithLessons(id));
    }


}
