<?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.backendsys.modules.ai.chat.dao.ChatHistoryDao">

    <sql id="includeChatHistory">
        ch.id,
        ch.history_code,
        ch.user_id,
        COALESCE(ch.robot_code, '') robot_code,
        ch.last_prompt,
        ch.del_flag,
        ch.create_time,
        ch.update_time
    </sql>

    <resultMap id="resultMapChatHistory" type="com.backendsys.modules.ai.chat.entity.ChatHistory">
        <id property="id" column="id" jdbcType="BIGINT" />
        <result property="history_code" column="history_code" />
        <result property="user_id" column="user_id" javaType="java.lang.Long" />
        <result property="robot_code" column="robot_code" />
        <result property="last_prompt" column="last_prompt" />
        <result property="chat_count" column="chat_count" javaType="java.lang.Integer" />
        <result property="del_flag" column="del_flag" javaType="java.lang.Integer" />
        <result property="create_time" column="create_time" />
        <result property="update_time" column="update_time" />
    </resultMap>

    <!-- 查 列表 -->
    <!-- COUNT(c.id) chat_count -->
    <select id="selectChatHistoryList" resultMap="resultMapChatHistory">
        SELECT
            <include refid="includeChatHistory" />,
            SUM(CASE WHEN c.content_type IS NULL OR c.content_type != 'THINK' THEN 1 ELSE 0 END) AS chat_count
        FROM ai_chat_history ch
        LEFT JOIN ai_chat c ON c.history_code = ch.history_code
        <where>
            <if test="user_id != null and user_id != ''">
                AND ch.user_id = #{user_id}
            </if>
            <if test="history_code != null and history_code != ''">
                AND ch.history_code = #{history_code}
            </if>
            <if test="del_flag != null and del_flag != ''">
                AND ch.del_flag = #{del_flag}
            </if>
        </where>
        GROUP BY ch.id, ch.history_code
        ORDER BY ch.update_time DESC
    </select>

</mapper>