<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ynfy.buss.course.usercoursecatalog.mapper.UserCourseCatalogMapper">
    <resultMap id="studyMap" type="com.ynfy.buss.course.usercoursecatalog.entity.vo.UserCourseStudyVO">
        <result column="course_id" property="courseId" jdbcType="VARCHAR"/>
        <result column="task_num" property="taskNum" jdbcType="INTEGER"/>
        <result column="finish_num" property="finishNum" jdbcType="INTEGER"/>
        <result column="study_num" property="studyNum" jdbcType="INTEGER"/>
    </resultMap>

    <select id="getUserCourseStudy" resultMap="studyMap">
        SELECT
            cc.course_id,
            count(*) AS task_num,
            sum(
                CASE
                WHEN ucc.learn_process IS NOT NULL
                AND ucc.learn_process >= 1 THEN
                1 ELSE 0
                END
            ) AS finish_num,
            sum(
                CASE
                WHEN ucc.learn_process IS NOT NULL
                THEN
                1 ELSE 0 END
            ) as study_num
        FROM
            course_catalog cc
        LEFT JOIN user_course_catalog ucc ON cc.id = ucc.course_catalog_id
        AND ucc.user_id = #{userId}
        WHERE
            cc.course_id IN
            <foreach collection="courseIds" index="index" item="id" open="(" separator="," close=")">
                #{id}
            </foreach>
            AND cc.type = 2
        GROUP BY
            cc.course_id
    </select>

    <select id="selectPageList" resultType="com.ynfy.buss.course.usercoursecatalog.entity.dto.UserStudyDTO">
        SELECT
            ucc.*,
            c.name as courseName,
            cc.name as taskName,
            case when ucc.update_time is not null then ucc.update_time else ucc.create_time end as lastLearnTime
        FROM user_course_catalog ucc
        LEFT JOIN course_catalog cc on cc.id=ucc.course_catalog_id
        LEFT JOIN course c on cc.course_id = c.id
        <where>
            <if test="userCourseCatalog.courseName != null and userCourseCatalog.courseName != ''">
                AND c.name like concat('%', #{userCourseCatalog.courseName}, '%')
            </if>
            <if test="userCourseCatalog.taskName != null and userCourseCatalog.taskName != ''">
                AND cc.name like concat('%', #{userCourseCatalog.taskName}, '%')
            </if>
            <if test="userCourseCatalog.userId != null and userCourseCatalog.userId != ''">
                AND ucc.user_id = #{userCourseCatalog.userId}
            </if>
            ORDER by lastLearnTime desc
        </where>
    </select>
</mapper>