<?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.achievement.mapper.AchievementMapper">

    <!-- 结果映射 -->
    <resultMap id="BaseResultMap" type="org.xyzh.common.dto.usercenter.TbAchievement">
        <id column="id" property="ID" />
        <result column="achievement_id" property="achievementID" />
        <result column="name" property="name" />
        <result column="description" property="description" />
        <result column="icon" property="icon" />
        <result column="type" property="type" />
        <result column="level" property="level" />
        <result column="condition_type" property="conditionType" />
        <result column="condition_value" property="conditionValue" />
        <result column="points" property="points" />
        <result column="order_num" property="orderNum" />
        <result column="creator" property="creator" />
        <result column="updater" property="updater" />
        <result column="create_time" property="createTime" />
        <result column="update_time" property="updateTime" />
        <result column="delete_time" property="deleteTime" />
        <result column="deleted" property="deleted" />
    </resultMap>

    <!-- 字段列表 -->
    <sql id="Base_Column_List">
        id, achievement_id, name, description, icon, type, level, condition_type, 
        condition_value, points, order_num, creator, updater, create_time, update_time, 
        delete_time, deleted
    </sql>

    <!-- 查询条件 -->
    <sql id="Base_Where_Clause">
        <where>
            <if test="filter != null">
                <if test="filter.ID != null and filter.ID != ''">
                    AND id = #{filter.ID}
                </if>
                <if test="filter.achievementID != null and filter.achievementID != ''">
                    AND achievement_id = #{filter.achievementID}
                </if>
                <if test="filter.name != null and filter.name != ''">
                    AND name LIKE CONCAT('%', #{filter.name}, '%')
                </if>
                <if test="filter.type != null">
                    AND type = #{filter.type}
                </if>
                <if test="filter.level != null">
                    AND level = #{filter.level}
                </if>
                <if test="filter.conditionType != null">
                    AND condition_type = #{filter.conditionType}
                </if>
                <if test="filter.points != null">
                    AND points = #{filter.points}
                </if>
                <if test="filter.creator != null and filter.creator != ''">
                    AND creator = #{filter.creator}
                </if>
                <if test="filter.deleted != null">
                    AND deleted = #{filter.deleted}
                </if>
            </if>
        </where>
    </sql>

    <!-- 权限过滤条件（基于dept_path的高效继承） -->
    <sql id="Permission_Filter">
        INNER JOIN tb_resource_permission rp ON a.achievement_id = rp.resource_id 
            AND rp.resource_type = 6 
            AND rp.deleted = 0
            AND rp.can_read = 1
            AND (
                (rp.dept_id IS NULL AND rp.role_id IS NULL)
                <if test="userDeptRoles != null and userDeptRoles.size() > 0">
                    OR EXISTS (
                        SELECT 1 
                        FROM (
                            <foreach collection="userDeptRoles" item="udr" separator=" UNION ALL ">
                                SELECT #{udr.deptID} AS dept_id, #{udr.deptPath} AS dept_path, #{udr.roleID} AS role_id
                            </foreach>
                        ) user_roles
                        LEFT JOIN tb_sys_dept perm_dept ON perm_dept.dept_id = rp.dept_id AND perm_dept.deleted = 0
                        WHERE 
                           (rp.role_id IS NULL AND rp.dept_id IS NOT NULL 
                               AND user_roles.dept_path LIKE CONCAT(perm_dept.dept_path, '%'))
                           OR (rp.dept_id IS NULL AND rp.role_id = user_roles.role_id)
                           OR (rp.dept_id = user_roles.dept_id AND rp.role_id = user_roles.role_id)
                    )
                </if>
            )
    </sql>

    <!-- 查询成就列表 - 添加权限过滤 -->
    <select id="selectAchievements" resultMap="BaseResultMap">
        SELECT DISTINCT a.*
        FROM tb_achievement a
        <include refid="Permission_Filter" />
        WHERE 1=1
            <if test="filter != null">
                <if test="filter.achievementID != null and filter.achievementID != ''">
                    AND a.achievement_id = #{filter.achievementID}
                </if>
                <if test="filter.name != null and filter.name != ''">
                    AND a.name LIKE CONCAT('%', #{filter.name}, '%')
                </if>
                <if test="filter.type != null">
                    AND a.type = #{filter.type}
                </if>
                <if test="filter.level != null">
                    AND a.level = #{filter.level}
                </if>
                <if test="filter.deleted != null">
                    AND a.deleted = #{filter.deleted}
                </if>
            </if>
        ORDER BY a.order_num ASC, a.create_time DESC
    </select>

    <!-- 根据成就ID查询成就信息 -->
    <select id="selectByAchievementId" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_achievement
        WHERE achievement_id = #{achievementId} AND deleted = 0
    </select>

    <!-- 根据类型查询成就列表 - 添加权限过滤 -->
    <select id="selectByType" resultMap="BaseResultMap">
        SELECT DISTINCT a.*
        FROM tb_achievement a
        <include refid="Permission_Filter" />
        WHERE a.type = #{type} AND a.deleted = 0
        ORDER BY a.order_num ASC, a.create_time DESC
    </select>

    <!-- 根据类型和等级查询成就列表 - 添加权限过滤 -->
    <select id="selectByTypeAndLevel" resultMap="BaseResultMap">
        SELECT DISTINCT a.*
        FROM tb_achievement a
        <include refid="Permission_Filter" />
        WHERE a.type = #{type} AND a.level = #{level} AND a.deleted = 0
        ORDER BY a.order_num ASC, a.create_time DESC
    </select>

    <!-- 根据条件类型查询成就列表 -->
    <select id="selectByConditionType" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_achievement
        WHERE condition_type = #{conditionType} AND deleted = 0
        ORDER BY order_num ASC, create_time DESC
    </select>

    <!-- 查询成就排行榜 -->
    <select id="selectAchievementRanking" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_achievement
        WHERE deleted = 0
        ORDER BY points DESC, level DESC, order_num ASC
        <if test="limit != null and limit > 0">
            LIMIT #{limit}
        </if>
    </select>

    <!-- 检查成就名称是否存在 - 添加权限过滤 -->
    <select id="countByName" resultType="int">
        SELECT COUNT(DISTINCT a.id)
        FROM tb_achievement a
        <include refid="Permission_Filter" />
        WHERE a.name = #{name} AND a.deleted = 0
        <if test="excludeId != null and excludeId != ''">
            AND a.id != #{excludeId}
        </if>
    </select>

    <!-- 插入成就 -->
    <insert id="insertAchievement" parameterType="org.xyzh.common.dto.usercenter.TbAchievement">
        INSERT INTO tb_achievement (
            id, achievement_id, name, description, icon, type, level, condition_type,
            condition_value, points, order_num, creator, updater, create_time, update_time,
            delete_time, deleted
        ) VALUES (
            #{ID}, #{achievementID}, #{name}, #{description}, #{icon}, #{type}, #{level}, 
            #{conditionType}, #{conditionValue}, #{points}, #{orderNum}, #{creator}, #{updater}, 
            #{createTime}, #{updateTime}, #{deleteTime}, #{deleted}
        )
    </insert>

    <!-- 更新成就 -->
    <update id="updateAchievement" parameterType="org.xyzh.common.dto.usercenter.TbAchievement">
        UPDATE tb_achievement
        <set>
            <if test="achievementID != null and achievementID != ''">
                achievement_id = #{achievementID},
            </if>
            <if test="name != null and name != ''">
                name = #{name},
            </if>
            <if test="description != null and description != ''">
                description = #{description},
            </if>
            <if test="icon != null and icon != ''">
                icon = #{icon},
            </if>
            <if test="type != null">
                type = #{type},
            </if>
            <if test="level != null">
                level = #{level},
            </if>
            <if test="conditionType != null">
                condition_type = #{conditionType},
            </if>
            <if test="conditionValue != null">
                condition_value = #{conditionValue},
            </if>
            <if test="points != null">
                points = #{points},
            </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>

    <!-- 删除成就 -->
    <delete id="deleteAchievement" parameterType="org.xyzh.common.dto.usercenter.TbAchievement">
        DELETE FROM tb_achievement
        WHERE id = #{ID}
    </delete>

    <!-- 批量插入成就 -->
    <insert id="batchInsertAchievements" parameterType="java.util.List">
        INSERT INTO tb_achievement (
            id, achievement_id, name, description, icon, type, level, condition_type,
            condition_value, points, order_num, creator, updater, create_time, update_time,
            delete_time, deleted
        ) VALUES
        <foreach collection="achievementList" item="item" separator=",">
            (
                #{item.ID}, #{item.achievementID}, #{item.name}, #{item.description}, #{item.icon},
                #{item.type}, #{item.level}, #{item.conditionType}, #{item.conditionValue},
                #{item.points}, #{item.orderNum}, #{item.creator}, #{item.updater},
                #{item.createTime}, #{item.updateTime}, #{item.deleteTime}, #{item.deleted}
            )
        </foreach>
    </insert>

    <!-- 批量删除成就 -->
    <delete id="batchDeleteAchievements">
        DELETE FROM tb_achievement
        WHERE id IN
        <foreach collection="ids" item="id" open="(" separator="," close=")">
            #{id}
        </foreach>
    </delete>

    <!-- 分页查询成就 -->
    <!-- selectAchievementsPage - 添加权限过滤 -->
    <select id="selectAchievementsPage" resultMap="BaseResultMap">
        SELECT DISTINCT a.*
        FROM tb_achievement a
        <include refid="Permission_Filter" />
        WHERE 1=1
            <if test="filter != null">
                <if test="filter.achievementID != null and filter.achievementID != ''">
                    AND a.achievement_id = #{filter.achievementID}
                </if>
                <if test="filter.name != null and filter.name != ''">
                    AND a.name LIKE CONCAT('%', #{filter.name}, '%')
                </if>
                <if test="filter.type != null">
                    AND a.type = #{filter.type}
                </if>
                <if test="filter.level != null">
                    AND a.level = #{filter.level}
                </if>
                <if test="filter.deleted != null">
                    AND a.deleted = #{filter.deleted}
                </if>
            </if>
        ORDER BY a.order_num ASC, a.create_time DESC
        LIMIT #{pageParam.pageSize} OFFSET #{pageParam.offset}
    </select>

    <!-- 统计成就总数 - 添加权限过滤 -->
    <select id="countAchievements" resultType="long">
        SELECT COUNT(DISTINCT a.id)
        FROM tb_achievement a
        <include refid="Permission_Filter" />
        WHERE 1=1
            <if test="filter != null">
                <if test="filter.achievementID != null and filter.achievementID != ''">
                    AND a.achievement_id = #{filter.achievementID}
                </if>
                <if test="filter.name != null and filter.name != ''">
                    AND a.name LIKE CONCAT('%', #{filter.name}, '%')
                </if>
                <if test="filter.type != null">
                    AND a.type = #{filter.type}
                </if>
                <if test="filter.level != null">
                    AND a.level = #{filter.level}
                </if>
                <if test="filter.deleted != null">
                    AND a.deleted = #{filter.deleted}
                </if>
            </if>
    </select>

    <!-- AchievementVO 结果映射（包含用户成就和进度信息） -->
    <resultMap id="AchievementVOResultMap" type="org.xyzh.common.vo.AchievementVO">
        <!-- 成就基本信息 -->
        <id column="id" property="ID" />
        <result column="achievement_id" property="achievementID" />
        <result column="name" property="name" />
        <result column="description" property="description" />
        <result column="icon" property="icon" />
        <result column="type" property="type" />
        <result column="level" property="level" />
        <result column="condition_type" property="conditionType" />
        <result column="condition_value" property="conditionValue" />
        <result column="points" property="points" />
        <result column="order_num" property="orderNum" />
        <result column="creator" property="creator" />
        <result column="updater" property="updater" />
        <result column="create_time" property="createTime" />
        <result column="update_time" property="updateTime" />
        <result column="deleted" property="deleted" />
        
        <!-- 用户信息 -->
        <result column="user_id" property="userID" />
        
        <!-- 用户成就信息 -->
        <result column="user_achievement_id" property="userAchievementID" />
        <result column="obtain_time" property="obtainTime" />
        <result column="obtained" property="obtained" />
        
        <!-- 进度信息 -->
        <result column="progress_id" property="progressID" />
        <result column="current_value" property="currentValue" />
        <result column="target_value" property="targetValue" />
        <result column="progress_percentage" property="progressPercentage" />
        <result column="completed" property="completed" />
        <result column="last_update_time" property="lastUpdateTime" />
    </resultMap>

    <!-- 联表查询用户成就列表（包含进度信息）- 带权限过滤 -->
    <select id="selectUserAchievementsWithProgress" resultMap="AchievementVOResultMap">
        SELECT 
            a.id,
            a.achievement_id,
            a.name,
            a.description,
            a.icon,
            a.type,
            a.level,
            a.condition_type,
            a.condition_value,
            a.points,
            a.order_num,
            a.creator,
            a.updater,
            a.create_time,
            a.update_time,
            a.deleted,
            #{userId} as user_id,
            ua.id as user_achievement_id,
            ua.obtain_time,
            CASE WHEN ua.id IS NOT NULL THEN 1 ELSE 0 END as obtained,
            p.id as progress_id,
            COALESCE(p.current_value, 0) as current_value,
            COALESCE(p.target_value, a.condition_value) as target_value,
            COALESCE(p.progress_percentage, 0) as progress_percentage,
            COALESCE(p.completed, 0) as completed,
            p.last_update_time
        FROM tb_achievement a
        <include refid="Permission_Filter"/>
        LEFT JOIN tb_user_achievement ua ON a.achievement_id = ua.achievement_id AND ua.user_id = #{userId} 
        LEFT JOIN tb_user_achievement_progress p ON a.achievement_id = p.achievement_id AND p.user_id = #{userId}
        WHERE a.deleted = 0
            <if test="type != null">
                AND a.type = #{type}
            </if>
        ORDER BY a.order_num ASC, a.create_time DESC
    </select>

</mapper>
