<?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.LearningTaskTagMapper">

    <!-- 结果映射 -->
    <resultMap id="BaseResultMap" type="org.xyzh.common.dto.study.TbLearningTaskTag">
        <id column="id" property="id" jdbcType="VARCHAR"/>
        <result column="task_id" property="taskID" jdbcType="VARCHAR"/>
        <result column="tag_id" property="tagID" jdbcType="VARCHAR"/>
        <result column="creator" property="creator" jdbcType="VARCHAR"/>
        <result column="create_time" property="createTime" jdbcType="TIMESTAMP"/>
    </resultMap>

    <!-- TagVO 结果映射 -->
    <resultMap id="TagVOResultMap" type="org.xyzh.common.vo.TagVO">
        <id column="id" property="id" jdbcType="VARCHAR"/>
        <result column="tag_id" property="tagID" jdbcType="VARCHAR"/>
        <result column="tag_name" property="tagName" jdbcType="VARCHAR"/>
        <result column="tag_color" property="tagColor" jdbcType="VARCHAR"/>
        <result column="creator" property="creator" jdbcType="VARCHAR"/>
    </resultMap>

    <!-- 基础列 -->
    <sql id="Base_Column_List">
        id, task_id, tag_id, creator, create_time
    </sql>

    <!-- 根据任务ID查询标签VO列表（包含标签详细信息） -->
    <select id="selectByTaskId" resultMap="TagVOResultMap">
        SELECT
            tlt.id,
            tlt.tag_id,
            t.name AS tag_name,
            t.color AS tag_color,
            tlt.creator
        FROM tb_learning_task_tag tlt
        INNER JOIN tb_tag t ON tlt.tag_id = t.tag_id AND t.deleted = 0
        WHERE tlt.task_id = #{taskId}
        ORDER BY tlt.create_time ASC
    </select>

    <!-- 根据标签ID查询任务关联列表 -->
    <select id="selectByTagId" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"/>
        FROM tb_learning_task_tag
        WHERE tag_id = #{tagId}
        ORDER BY create_time DESC
    </select>

    <!-- 批量插入任务标签关联 -->
    <insert id="batchInsert">
        INSERT INTO tb_learning_task_tag (
            id, task_id, tag_id, creator, create_time
        ) VALUES
        <foreach collection="list" item="item" separator=",">
            (
                #{item.id}, #{item.taskID}, #{item.tagID},
                #{item.creator}, #{item.createTime}
            )
        </foreach>
    </insert>

    <!-- 根据任务ID删除所有标签关联 -->
    <delete id="deleteByTaskId">
        DELETE FROM tb_learning_task_tag
        WHERE task_id = #{taskId}
    </delete>

    <!-- 删除指定任务的指定标签 -->
    <delete id="deleteByTaskIdAndTagId">
        DELETE FROM tb_learning_task_tag
        WHERE task_id = #{taskId} AND tag_id = #{tagId}
    </delete>

</mapper>
