<?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.ylx.point.mapper.PointUserActivityTaskCompletionMapper">
    
    <resultMap type="PointUserActivityTaskCompletion" id="PointUserActivityTaskCompletionResult">
        <result property="id"    column="id"    />
        <result property="activityId"    column="activity_id"    />
        <result property="taskId"    column="task_id"    />
        <result property="taskType"    column="task_type"    />
        <result property="openId"    column="open_id"    />
        <result property="completedCount"    column="completed_count"    />
        <result property="lastCompletedTime"    column="last_completed_time"    />
        <result property="createTime"    column="create_time"    />
        <result property="updateTime"    column="update_time"    />
        <result property="completedDate"    column="completed_date"    />
    </resultMap>

    <sql id="selectPointUserActivityTaskCompletionVo">
        select id, activity_id, task_id, task_type, open_id, completed_count, last_completed_time, create_time, update_time, completed_date from point_user_activity_task_completion
    </sql>

    <select id="getPointActivityOverviewByActivityId"
            resultType="com.ylx.point.domain.vo.PointActivityOverviewVO">
        SELECT
            COUNT(DISTINCT utc.open_id) AS totalParticipants,
            COUNT(DISTINCT CASE WHEN utc.completed_count > 0 THEN utc.open_id END) AS totalCompleted,
            COALESCE(SUM(utc.completed_count), 0) AS totalTaskTimes,
            COALESCE(SUM(ul.points), 0) AS totalPoints
        FROM `point_user_activity_task_completion` utc
        LEFT JOIN `point_user_log` ul ON utc.activity_id = ul.activity_id AND ul.op_type = 1 -- 仅统计收入积分
        WHERE utc.activity_id = #{activityId}
    </select>

    <select id="selectCompletedTaskCount" resultType="java.lang.Integer">
        SELECT COUNT(*) FROM point_user_activity_task_completion WHERE open_id = #{openId} AND completed_count > 0 AND task_type != 2
    </select>

    <select id="selectCompletionsByOpenIdAndTaskIds"
            resultType="com.ylx.point.domain.PointUserActivityTaskCompletion">
        <include refid="selectPointUserActivityTaskCompletionVo"/>
        WHERE
            open_id = #{openId}
        AND task_id IN
        <foreach collection="taskIds" item="taskId" open="(" separator="," close=")">
            #{taskId}
        </foreach>
    </select>

</mapper>