package com.lesingle.edu.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lesingle.edu.entity.CoursePackage;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;
import java.util.Map;

@Mapper
public interface CoursePackageMapper extends BaseMapper<CoursePackage> {

    /**
     * 增加课程包使用次数
     * @param coursePackageId 课程包 ID
     */
    @Update("UPDATE course_package SET usage_count = usage_count + 1 WHERE id = #{coursePackageId}")
    void incrementUsageCount(@Param("coursePackageId") Long coursePackageId);

    /**
     * 减少课程包使用次数（课程取消时调用）
     * @param coursePackageId 课程包 ID
     */
    @Update("UPDATE course_package SET usage_count = GREATEST(usage_count - 1, 0) WHERE id = #{coursePackageId}")
    void decrementUsageCount(@Param("coursePackageId") Long coursePackageId);

    /**
     * 更新课程包教师数量（去重统计已完成课程的教师）
     * @param coursePackageId 课程包 ID
     */
    @Update("UPDATE course_package cp " +
            "SET teacher_count = ( " +
            "  SELECT COUNT(DISTINCT l.teacher_id) " +
            "  FROM lesson l " +
            "  WHERE l.course_id = #{coursePackageId} " +
            "  AND l.status = 'COMPLETED' " +
            ") " +
            "WHERE cp.id = #{coursePackageId}")
    void updateTeacherCount(@Param("coursePackageId") Long coursePackageId);

    /**
     * 获取学校端课程分布统计
     * @param tenantId 租户 ID
     * @return 课程包名称和使用次数的列表
     */
    @Select("SELECT cp.name, COUNT(l.id) as value " +
            "FROM course_package cp " +
            "INNER JOIN lesson l ON cp.id = l.course_id " +
            "WHERE l.tenant_id = #{tenantId} " +
            "AND l.status = 'COMPLETED' " +
            "GROUP BY cp.id, cp.name " +
            "ORDER BY value DESC")
    List<Map<String, Object>> getCourseDistribution(@Param("tenantId") Long tenantId);
}
