<?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.dora.mapper.AiTaskMapper">

    <insert id="insert" parameterType="com.dora.entity.AiTask" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO ai_task (
            task_no, user_id, model_name, task_type, provider_type, provider_task_id, provider_response,
            prompt, image_url, image_base64, aspect_ratio,
            status, progress, progress_message, points_frozen, points_consumed, result_url, 
            error_message, queue_time, start_time, complete_time, expire_time
        )
        VALUES (
            #{taskNo}, #{userId}, #{modelName}, #{taskType}, #{providerType}, #{providerTaskId}, #{providerResponse},
            #{prompt}, #{imageUrl}, #{imageBase64}, #{aspectRatio},
            #{status}, #{progress}, #{progressMessage}, #{pointsFrozen}, #{pointsConsumed}, #{resultUrl}, 
            #{errorMessage}, #{queueTime}, #{startTime}, #{completeTime}, #{expireTime}
        )
    </insert>

    <select id="findByTaskNo" parameterType="string" resultType="com.dora.entity.AiTask">
        SELECT * FROM ai_task WHERE task_no = #{taskNo} AND is_deleted = 0
    </select>

    <update id="update" parameterType="com.dora.entity.AiTask">
        UPDATE ai_task
        <set>
            <if test="status != null">status = #{status},</if>
            <if test="progress != null">progress = #{progress},</if>
            <if test="progressMessage != null">progress_message = #{progressMessage},</if>
            <if test="providerTaskId != null">provider_task_id = #{providerTaskId},</if>
            <if test="providerResponse != null">provider_response = #{providerResponse},</if>
            <if test="pointsConsumed != null">points_consumed = #{pointsConsumed},</if>
            <if test="resultUrl != null">result_url = #{resultUrl},</if>
            <if test="errorMessage != null">error_message = #{errorMessage},</if>
            <if test="queueTime != null">queue_time = #{queueTime},</if>
            <if test="startTime != null">start_time = #{startTime},</if>
            <if test="completeTime != null">complete_time = #{completeTime},</if>
            <if test="expireTime != null">expire_time = #{expireTime},</if>
            update_time = NOW()
        </set>
        WHERE id = #{id}
    </update>

    <select id="findStuckTasks" parameterType="java.time.LocalDateTime" resultType="com.dora.entity.AiTask">
        SELECT *
        FROM ai_task
        WHERE status = 'processing'
          AND update_time &lt; #{timeoutThreshold}
          AND is_deleted = 0
          AND (provider_type IS NULL OR (provider_type != 'runninghub' AND provider_type != 'suchuang'))
        <!-- RunningHub和速创任务有专门的轮询机制，不参与通用超时检查 -->
    </select>

    <select id="findUserTasks" resultType="com.dora.entity.AiTask">
        SELECT *
        FROM ai_task
        WHERE user_id = #{userId}
          <if test="status != null and status != ''">
              AND status = #{status}
          </if>
          AND is_deleted = 0
        ORDER BY create_time DESC
    </select>

    <select id="findUserTasksWithType" resultType="com.dora.entity.AiTask">
        SELECT *
        FROM ai_task
        WHERE user_id = #{userId}
          <if test="status != null and status != ''">
              AND status = #{status}
          </if>
          <if test="taskType != null and taskType != ''">
              AND task_type = #{taskType}
          </if>
          AND is_deleted = 0
        ORDER BY create_time DESC
    </select>

    <select id="findAllAdmin" resultType="com.dora.entity.AiTask">
        SELECT *
        FROM ai_task
        <where>
            is_deleted = 0
            <if test="userId != null">
                AND user_id = #{userId}
            </if>
            <if test="status != null and status != ''">
                AND status = #{status}
            </if>
            <if test="modelName != null and modelName != ''">
                AND model_name = #{modelName}
            </if>
            <if test="taskNo != null and taskNo != ''">
                AND task_no LIKE CONCAT('%', #{taskNo}, '%')
            </if>
        </where>
        ORDER BY id DESC
    </select>

    <!-- 查询指定provider的processing任务 -->
    <select id="findProcessingTasksByProvider" parameterType="string" resultType="com.dora.entity.AiTask">
        SELECT * FROM ai_task
        WHERE status = 'processing'
          AND provider_type = #{providerType}
          AND is_deleted = 0
        ORDER BY update_time ASC
        LIMIT 100
    </select>

    <!-- 查询用户任务并关联广场作品信息 -->
    <select id="findUserTasksWithPlaza" resultMap="aiTaskWithPlazaResultMap">
        SELECT 
            at.*,
            pw.id as pw_id,
            pw.work_no as pw_work_no,
            pw.status as pw_status,
            pw.audit_status as pw_audit_status,
            pw.audit_time as pw_audit_time,
            pw.audit_remark as pw_audit_remark
        FROM ai_task at
        LEFT JOIN plaza_work pw ON at.task_no COLLATE utf8mb4_unicode_ci = pw.task_no COLLATE utf8mb4_unicode_ci AND pw.is_deleted = 0
        WHERE at.user_id = #{userId}
          <if test="status != null and status != ''">
              AND at.status = #{status}
          </if>
          AND at.is_deleted = 0
        ORDER BY at.create_time DESC
    </select>

    <!-- 查询用户任务并关联广场作品信息（支持任务类型筛选） -->
    <select id="findUserTasksWithPlazaAndType" resultMap="aiTaskWithPlazaResultMap">
        SELECT 
            at.*,
            pw.id as pw_id,
            pw.work_no as pw_work_no,
            pw.status as pw_status,
            pw.audit_status as pw_audit_status,
            pw.audit_time as pw_audit_time,
            pw.audit_remark as pw_audit_remark
        FROM ai_task at
        LEFT JOIN plaza_work pw ON at.task_no COLLATE utf8mb4_unicode_ci = pw.task_no COLLATE utf8mb4_unicode_ci AND pw.is_deleted = 0
        WHERE at.user_id = #{userId}
          <if test="status != null and status != ''">
              AND at.status = #{status}
          </if>
          <if test="taskType != null and taskType != ''">
              AND at.task_type = #{taskType}
          </if>
          AND at.is_deleted = 0
        ORDER BY at.create_time DESC
    </select>

    <!-- 结果映射：AI任务与广场作品联合查询 -->
    <resultMap id="aiTaskWithPlazaResultMap" type="com.dora.dto.AiTaskWithPlazaDto">
        <association property="aiTask" javaType="com.dora.entity.AiTask">
            <id property="id" column="id"/>
            <result property="taskNo" column="task_no"/>
            <result property="userId" column="user_id"/>
            <result property="modelName" column="model_name"/>
            <result property="taskType" column="task_type"/>
            <result property="providerType" column="provider_type"/>
            <result property="providerTaskId" column="provider_task_id"/>
            <result property="providerResponse" column="provider_response"/>
            <result property="prompt" column="prompt"/>
            <result property="imageUrl" column="image_url"/>
            <result property="imageBase64" column="image_base64"/>
            <result property="aspectRatio" column="aspect_ratio"/>
            <result property="status" column="status"/>
            <result property="progress" column="progress"/>
            <result property="progressMessage" column="progress_message"/>
            <result property="pointsFrozen" column="points_frozen"/>
            <result property="pointsConsumed" column="points_consumed"/>
            <result property="resultUrl" column="result_url"/>
            <result property="errorMessage" column="error_message"/>
            <result property="queueTime" column="queue_time"/>
            <result property="startTime" column="start_time"/>
            <result property="completeTime" column="complete_time"/>
            <result property="expireTime" column="expire_time"/>
            <result property="createTime" column="create_time"/>
            <result property="updateTime" column="update_time"/>
            <result property="isDeleted" column="is_deleted"/>
        </association>
        <association property="plazaWork" javaType="com.dora.entity.PlazaWork">
            <id property="id" column="pw_id"/>
            <result property="workNo" column="pw_work_no"/>
            <result property="status" column="pw_status"/>
            <result property="auditStatus" column="pw_audit_status"/>
            <result property="auditTime" column="pw_audit_time"/>
            <result property="auditRemark" column="pw_audit_remark"/>
        </association>
    </resultMap>

    <!-- 逻辑删除用户的AI任务 -->
    <update id="deleteByTaskNoAndUserId">
        UPDATE ai_task 
        SET is_deleted = 1, update_time = NOW() 
        WHERE task_no = #{taskNo} AND user_id = #{userId} AND is_deleted = 0
    </update>

    <!-- 查询队列中超时的任务 -->
    <select id="findQueuedTasksBeforeTime" resultType="com.dora.entity.AiTask">
        SELECT * FROM ai_task
        WHERE status = 'queued'
          AND create_time &lt; #{timeoutThreshold}
          AND is_deleted = 0
        ORDER BY create_time ASC
    </select>

    <!-- 通过任务编号查询任务详情（包含作者信息） -->
    <select id="findTaskDetailByTaskNo" resultType="java.util.HashMap">
        SELECT 
            at.id,
            at.task_no,
            at.user_id,
            at.model_name,
            at.task_type,
            at.prompt,
            at.result_url,
            at.image_url,
            at.aspect_ratio,
            at.status,
            at.progress,
            at.error_message,
            at.create_time,
            at.update_time,
            u.username as nickname,
            u.avatar_url
        FROM ai_task at
        LEFT JOIN user u ON at.user_id = u.id
        WHERE at.task_no = #{taskNo} AND at.is_deleted = 0
    </select>

</mapper>
