<?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="org.xyzh.study.mapper.TaskItemMapper">

    <!-- 基础结果映射 -->
    <resultMap id="BaseResultMap" type="org.xyzh.common.dto.study.TbTaskItem">
        <id column="id" property="id" jdbcType="VARCHAR"/>
        <result column="task_id" property="taskID" jdbcType="VARCHAR"/>
        <result column="item_type" property="itemType" jdbcType="INTEGER"/>
        <result column="item_id" property="itemID" jdbcType="VARCHAR"/>
        <result column="required" property="required" jdbcType="BOOLEAN"/>
        <result column="order_num" property="orderNum" jdbcType="INTEGER"/>
        <result column="creator" property="creator" jdbcType="VARCHAR"/>
        <result column="create_time" property="createTime" jdbcType="TIMESTAMP"/>
        <result column="updater" property="updater" jdbcType="VARCHAR"/>
        <result column="update_time" property="updateTime" jdbcType="TIMESTAMP"/>
        <result column="delete_time" property="deleteTime" jdbcType="TIMESTAMP"/>
        <result column="deleted" property="deleted" jdbcType="BOOLEAN"/>
    </resultMap>

    <resultMap id="TaskItemResultMap" type="org.xyzh.common.vo.TaskItemVO">
        <id column="id" property="id" jdbcType="VARCHAR"/>
        <result column="task_id" property="taskID" jdbcType="VARCHAR"/>
        <result column="item_type" property="itemType" jdbcType="INTEGER"/>
        <result column="course_id" property="courseID" jdbcType="VARCHAR"/>
        <result column="course_name" property="courseName" jdbcType="VARCHAR"/>
        <result column="resource_id" property="resourceID" jdbcType="VARCHAR"/>
        <result column="resource_name" property="resourceName" jdbcType="VARCHAR"/>
        <result column="user_id" property="userID" jdbcType="VARCHAR"/>
        <result column="user_name" property="userName" jdbcType="VARCHAR"/>
        <result column="status" property="status" jdbcType="INTEGER"/>
        <result column="progress" property="progress" jdbcType="DECIMAL"/>
        <result column="complete_time" property="completeTime" jdbcType="TIMESTAMP"/>
        <result column="required" property="required" jdbcType="BOOLEAN"/>
        <result column="order_num" property="orderNum" jdbcType="INTEGER"/>
        <result column="creator" property="creator" jdbcType="VARCHAR"/>
        <result column="create_time" property="createTime" jdbcType="TIMESTAMP"/>
    </resultMap>

    <!-- 基础字段 -->
    <sql id="Base_Column_List">
        id, task_id, item_type, item_id, required, order_num, creator, create_time, 
        updater, update_time, delete_time, deleted
    </sql>

    <!-- 通用条件 -->
    <sql id="Where_Clause">
        <where>
            deleted = 0
            <if test="taskID != null and taskID != ''">
                AND task_id = #{taskID}
            </if>
            <if test="itemType != null">
                AND item_type = #{itemType}
            </if>
            <if test="itemID != null and itemID != ''">
                AND item_id = #{itemID}
            </if>
            <if test="required != null">
                AND required = #{required}
            </if>
        </where>
    </sql>

    <!-- selectTaskItems -->
    <select id="selectTaskItems" resultMap="BaseResultMap">
        SELECT 
        <include refid="Base_Column_List"/>
        FROM tb_task_item
        <include refid="Where_Clause"/>
        ORDER BY order_num ASC, create_time ASC
    </select>

    <!-- 根据关联ID查询关联信息 -->
    <select id="selectByRelationId" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_task_item
        WHERE id = #{relationId} AND deleted = 0
    </select>

    <!-- 根据任务ID查询项关联列表 -->
    <select id="selectByTaskId" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_task_item
        WHERE task_id = #{taskId} AND deleted = 0
        ORDER BY order_num ASC, create_time ASC
    </select>

    <!-- 根据任务ID和类型查询项关联列表 -->
    <select id="selectByTaskIdAndType" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_task_item
        WHERE task_id = #{taskId} AND item_type = #{itemType} AND deleted = 0
        ORDER BY order_num ASC, create_time ASC
    </select>

    <!-- 根据任务ID查询任务项VO列表（带学习状态） -->
    <select id="selectTaskItemVOByTaskId" resultMap="TaskItemResultMap">
        SELECT
            tti.*,
            CASE
                WHEN tti.item_type = 1 THEN tr.title
                WHEN tti.item_type = 2 THEN tc.name
            END as item_name,
            CASE
                WHEN tti.item_type = 1 THEN tti.item_id
                ELSE NULL
            END as resource_id,
            CASE
                WHEN tti.item_type = 1 THEN tr.title
                ELSE NULL
            END as resource_name,
            CASE
                WHEN tti.item_type = 2 THEN tti.item_id
                ELSE NULL
            END as course_id,
            CASE
                WHEN tti.item_type = 2 THEN tc.name
                ELSE NULL
            END as course_name,
            -- 学习状态：0未开始 1进行中 2已完成
            CASE
                -- 资源类型：直接从学习记录查询
                WHEN tti.item_type = 1 THEN
                    CASE
                        WHEN lr_resource.is_complete = 1 THEN 2
                        WHEN lr_resource.id IS NOT NULL THEN 1
                        ELSE 0
                    END
                -- 课程类型：判断所有节点是否完成
                WHEN tti.item_type = 2 THEN
                    CASE
                        WHEN course_stats.total_nodes = 0 THEN 0
                        WHEN course_stats.completed_nodes = course_stats.total_nodes THEN 2
                        WHEN course_stats.completed_nodes > 0 THEN 1
                        ELSE 0
                    END
                ELSE 0
            END as status,
            -- 学习进度
            CASE
                WHEN tti.item_type = 1 THEN COALESCE(lr_resource.progress, 0)
                WHEN tti.item_type = 2 THEN
                    CASE
                        WHEN course_stats.total_nodes = 0 THEN 0
                        ELSE ROUND((course_stats.completed_nodes * 100.0 / course_stats.total_nodes), 2)
                    END
                ELSE 0
            END as progress
        FROM tb_task_item tti
        LEFT JOIN tb_resource tr ON tti.item_type = 1 AND tti.item_id = tr.resource_id AND tr.deleted = 0
        LEFT JOIN tb_course tc ON tti.item_type = 2 AND tti.item_id = tc.course_id AND tc.deleted = 0
        -- 资源学习记录
        LEFT JOIN tb_learning_record lr_resource ON tti.item_type = 1 
            AND lr_resource.resource_type = 1 
            AND lr_resource.resource_id = tti.item_id
            AND lr_resource.task_id = tti.task_id
            AND lr_resource.deleted = 0
        -- 课程学习统计（统计课程下所有节点的完成情况）
        LEFT JOIN (
            SELECT
                tti.item_id as course_id,
                COUNT(DISTINCT tcn.node_id) as total_nodes,
                COUNT(DISTINCT CASE WHEN lr.is_complete = 1 THEN lr.node_id END) as completed_nodes
            FROM tb_task_item tti
            INNER JOIN tb_course_chapter tcc ON tti.item_type = 2 AND tti.item_id = tcc.course_id AND tcc.deleted = 0
            INNER JOIN tb_course_node tcn ON tcc.chapter_id = tcn.chapter_id AND tcn.deleted = 0
            LEFT JOIN tb_learning_record lr ON lr.resource_type = 2 
                AND tti.item_id = lr.course_id
                AND lr.node_id = tcn.node_id 
                AND lr.deleted = 0
            WHERE tti.task_id = #{taskId} AND tti.deleted = 0
            GROUP BY tti.item_id
        ) course_stats ON tti.item_type = 2 AND course_stats.course_id = tti.item_id
        WHERE tti.task_id = #{taskId} AND tti.deleted = 0
        ORDER BY tti.order_num ASC, tti.create_time ASC
    </select>

    <!-- 根据任务ID和用户ID查询任务项视图对象列表（包含该用户的学习状态） -->
    <select id="selectTaskItemVOByTaskIdAndUserId" resultMap="TaskItemResultMap">
        SELECT
            tti.*,
            CASE
                WHEN tti.item_type = 1 THEN tr.title
                WHEN tti.item_type = 2 THEN tc.name
            END as item_name,
            CASE
                WHEN tti.item_type = 1 THEN tti.item_id
                ELSE NULL
            END as resource_id,
            CASE
                WHEN tti.item_type = 1 THEN tr.title
                ELSE NULL
            END as resource_name,
            CASE
                WHEN tti.item_type = 2 THEN tti.item_id
                ELSE NULL
            END as course_id,
            CASE
                WHEN tti.item_type = 2 THEN tc.name
                ELSE NULL
            END as course_name,
            -- 学习状态：0未开始 1进行中 2已完成
            CASE
                -- 资源类型：直接从学习记录查询
                WHEN tti.item_type = 1 THEN
                    CASE
                        WHEN lr_resource.is_complete = 1 THEN 2
                        WHEN lr_resource.id IS NOT NULL THEN 1
                        ELSE 0
                    END
                -- 课程类型：判断所有节点是否完成
                WHEN tti.item_type = 2 THEN
                    CASE
                        WHEN course_stats.total_nodes = 0 THEN 0
                        WHEN course_stats.completed_nodes = course_stats.total_nodes THEN 2
                        WHEN course_stats.completed_nodes > 0 THEN 1
                        ELSE 0
                    END
                ELSE 0
            END as status,
            -- 学习进度
            CASE
                WHEN tti.item_type = 1 THEN COALESCE(lr_resource.progress, 0)
                WHEN tti.item_type = 2 THEN
                    CASE
                        WHEN course_stats.total_nodes = 0 THEN 0
                        ELSE ROUND((course_stats.completed_nodes * 100.0 / course_stats.total_nodes), 2)
                    END
                ELSE 0
            END as progress
        FROM tb_task_item tti
        LEFT JOIN tb_resource tr ON tti.item_type = 1 AND tti.item_id = tr.resource_id AND tr.deleted = 0
        LEFT JOIN tb_course tc ON tti.item_type = 2 AND tti.item_id = tc.course_id AND tc.deleted = 0
        -- 资源学习记录（限定用户）
        LEFT JOIN tb_learning_record lr_resource ON tti.item_type = 1 
            AND lr_resource.resource_type = 1 
            AND lr_resource.resource_id = tti.item_id
            AND lr_resource.task_id = tti.task_id
            AND lr_resource.user_id = #{userId}
            AND lr_resource.deleted = 0
        -- 课程学习统计（统计课程下所有节点的完成情况，限定用户）
        LEFT JOIN (
            SELECT
                tti.item_id as course_id,
                COUNT(DISTINCT tcn.node_id) as total_nodes,
                COUNT(DISTINCT CASE WHEN lr.is_complete = 1 THEN lr.node_id END) as completed_nodes
            FROM tb_task_item tti
            INNER JOIN tb_course_chapter tcc ON tti.item_type = 2 AND tti.item_id = tcc.course_id AND tcc.deleted = 0
            INNER JOIN tb_course_node tcn ON tcc.chapter_id = tcn.chapter_id AND tcn.deleted = 0
            LEFT JOIN tb_learning_record lr ON lr.resource_type = 2 
                AND tti.item_id = lr.course_id
                AND lr.node_id = tcn.node_id 
                AND lr.user_id = #{userId}
                AND lr.deleted = 0
            WHERE tti.task_id = #{taskId} AND tti.deleted = 0
            GROUP BY tti.item_id
        ) course_stats ON tti.item_type = 2 AND course_stats.course_id = tti.item_id
        WHERE tti.task_id = #{taskId} AND tti.deleted = 0
        ORDER BY tti.order_num ASC, tti.create_time ASC
    </select>

    <!-- 根据项ID查询任务关联列表 -->
    <select id="selectByItemId" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_task_item
        WHERE item_id = #{itemId} AND item_type = #{itemType} AND deleted = 0
        ORDER BY order_num ASC, create_time ASC
    </select>

    <!-- 根据任务ID和项ID查询关联信息 -->
    <select id="selectByTaskIdAndItemId" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_task_item
        WHERE task_id = #{taskId} AND item_id = #{itemId} AND item_type = #{itemType} AND deleted = 0
    </select>

    <!-- 检查任务项关联是否存在 -->
    <select id="countByTaskIdAndItemId" resultType="int">
        SELECT COUNT(1)
        FROM tb_task_item
        WHERE task_id = #{taskId} AND item_id = #{itemId} AND item_type = #{itemType} AND deleted = 0
        <if test="excludeId != null and excludeId != ''">
            AND id != #{excludeId}
        </if>
    </select>

    <!-- 插入任务项关联 -->
    <insert id="insertTaskItem" parameterType="org.xyzh.common.dto.study.TbTaskItem">
        INSERT INTO tb_task_item (
            id, task_id, item_type, item_id, required, order_num, creator, create_time
        ) VALUES (
            #{id}, #{taskID}, #{itemType}, #{itemID}, #{required}, #{orderNum}, #{creator}, #{createTime}
        )
    </insert>

    <!-- 更新任务项关联 -->
    <update id="updateTaskItem" parameterType="org.xyzh.common.dto.study.TbTaskItem">
        UPDATE tb_task_item
        <set>
            <if test="taskID != null and taskID != ''">
                task_id = #{taskID},
            </if>
            <if test="itemType != null">
                item_type = #{itemType},
            </if>
            <if test="itemID != null and itemID != ''">
                item_id = #{itemID},
            </if>
            <if test="required != null">
                required = #{required},
            </if>
            <if test="orderNum != null">
                order_num = #{orderNum},
            </if>
            <if test="updater != null and updater != ''">
                updater = #{updater},
            </if>
            <if test="updateTime != null">
                update_time = #{updateTime},
            </if>
            <if test="deleteTime != null">
                delete_time = #{deleteTime},
            </if>
            <if test="deleted != null">
                deleted = #{deleted},
            </if>
        </set>
        WHERE id = #{id}
    </update>

    <!-- 删除任务项关联（软删除） -->
    <update id="deleteTaskItem" parameterType="org.xyzh.common.dto.study.TbTaskItem">
        UPDATE tb_task_item
        SET deleted = 1, delete_time = NOW()
        WHERE id = #{id}
    </update>

    <!-- 批量插入任务项关联 -->
    <insert id="batchInsertTaskItems" parameterType="java.util.List">
        INSERT INTO tb_task_item (
            id, task_id, item_type, item_id, required, order_num, creator, create_time
        ) VALUES
        <foreach collection="taskItemList" item="item" separator=",">
            (
                #{item.id}, #{item.taskID}, #{item.itemType}, #{item.itemID}, #{item.required}, 
                #{item.orderNum}, #{item.creator}, #{item.createTime}
            )
        </foreach>
    </insert>

    <!-- 批量删除任务项关联（软删除） -->
    <update id="batchDeleteTaskItems">
        UPDATE tb_task_item
        SET deleted = 1, delete_time = NOW()
        WHERE id IN
        <foreach collection="ids" item="id" open="(" separator="," close=")">
            #{id}
        </foreach>
    </update>

    <!-- 根据任务ID批量删除项关联（软删除） -->
    <update id="deleteByTaskId">
        UPDATE tb_task_item
        SET deleted = 1, delete_time = NOW()
        WHERE task_id = #{taskId}
    </update>

    <!-- 根据项ID批量删除任务关联（软删除） -->
    <update id="deleteByItemId">
        UPDATE tb_task_item
        SET deleted = 1, delete_time = NOW()
        WHERE item_id = #{itemId} AND item_type = #{itemType}
    </update>

    <!-- 分页查询任务项关联 -->
    <select id="selectTaskItemsPage" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_task_item
        <include refid="Where_Clause" />
        ORDER BY order_num ASC, create_time ASC
        LIMIT #{pageParam.pageSize} OFFSET #{pageParam.offset}
    </select>

    <!-- 统计任务项关联总数 -->
    <select id="countTaskItems" resultType="long">
        SELECT COUNT(1)
        FROM tb_task_item
        <include refid="Where_Clause" />
    </select>

</mapper>
