<?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.system.mapper.SysLoginLogMapper">

    <resultMap id="BaseResultMap" type="org.xyzh.common.dto.system.TbSysLoginLog">
        <id column="id" property="id" jdbcType="VARCHAR"/>
        <result column="user_id" property="userID" jdbcType="VARCHAR"/>
        <result column="username" property="username" jdbcType="VARCHAR"/>
        <result column="ip_address" property="ipAddress" jdbcType="VARCHAR"/>
        <result column="ip_source" property="ipSource" jdbcType="VARCHAR"/>
        <result column="browser" property="browser" jdbcType="VARCHAR"/>
        <result column="os" property="os" jdbcType="VARCHAR"/>
        <result column="password" property="password" jdbcType="VARCHAR"/>
        <result column="login_time" property="loginTime" jdbcType="TIMESTAMP"/>
        <result column="status" property="status" jdbcType="INTEGER"/>
        <result column="error_count" property="errorCount" jdbcType="INTEGER"/>
        <result column="message" property="message" jdbcType="VARCHAR"/>
        <result column="create_time" property="createTime" jdbcType="TIMESTAMP"/>
    </resultMap>

    <!-- 权限过滤：通过用户的部门路径进行权限控制，superadmin可查看所有 -->
    <sql id="Permission_Filter">
        INNER JOIN tb_sys_user u ON ll.user_id = u.id AND u.deleted = 0
        INNER JOIN tb_sys_user_dept_role udr ON u.id = udr.user_id AND udr.deleted = 0
        INNER JOIN tb_sys_dept d ON udr.dept_id = d.dept_id AND d.deleted = 0
        WHERE (
            -- superadmin 可以查看所有登录日志
            EXISTS (
                SELECT 1 FROM (
                    <foreach collection="userDeptRoles" item="currentRole" separator=" UNION ALL ">
                        SELECT #{currentRole.deptID} AS dept_id, #{currentRole.roleID} AS role_id
                    </foreach>
                ) admin_check
                WHERE admin_check.dept_id = 'root_department' 
                AND admin_check.role_id = 'superadmin'
            )
            -- 普通用户按部门路径过滤（本部门及子部门）
            OR EXISTS (
                SELECT 1 FROM (
                    <foreach collection="userDeptRoles" item="currentRole" separator=" UNION ALL ">
                        SELECT #{currentRole.deptPath} AS user_dept_path
                    </foreach>
                ) user_roles
                WHERE d.dept_path LIKE CONCAT(user_roles.user_dept_path, '%')
            )
        )
    </sql>

    <insert id="insertLoginLog" parameterType="org.xyzh.common.dto.system.TbSysLoginLog">
      INSERT INTO tb_sys_login_log (id, user_id, username, ip_address, ip_source, browser, os, password, login_time, status, error_count, message, create_time)
      VALUES (#{id}, #{userID}, #{username}, #{ipAddress}, #{ipSource}, #{browser}, #{os}, #{password}, #{loginTime, jdbcType=TIMESTAMP}, #{status}, #{errorCount}, #{message}, now());
    </insert>

    <!-- 查询登录日志列表（带权限过滤） -->
    <select id="selectLoginLogList" resultMap="BaseResultMap">
        SELECT DISTINCT ll.*
        FROM tb_sys_login_log ll
        <include refid="Permission_Filter"/>
        <if test="loginLog.userID != null and loginLog.userID != ''">
            AND ll.user_id = #{loginLog.userID}
        </if>
        <if test="loginLog.username != null and loginLog.username != ''">
            AND ll.username LIKE CONCAT('%', #{loginLog.username}, '%')
        </if>
        <if test="loginLog.ipAddress != null and loginLog.ipAddress != ''">
            AND ll.ip_address = #{loginLog.ipAddress}
        </if>
        <if test="loginLog.status != null">
            AND ll.status = #{loginLog.status}
        </if>
        <if test="loginLog.browser != null and loginLog.browser != ''">
            AND ll.browser LIKE CONCAT('%', #{loginLog.browser}, '%')
        </if>
        <if test="loginLog.os != null and loginLog.os != ''">
            AND ll.os LIKE CONCAT('%', #{loginLog.os}, '%')
        </if>
        ORDER BY ll.login_time DESC
    </select>

    <!-- 分页查询登录日志列表（带权限过滤） -->
    <select id="selectLoginLogPage" resultMap="BaseResultMap">
        SELECT DISTINCT ll.*
        FROM tb_sys_login_log ll
        <include refid="Permission_Filter"/>
        <if test="loginLog.userID != null and loginLog.userID != ''">
            AND ll.user_id = #{loginLog.userID}
        </if>
        <if test="loginLog.username != null and loginLog.username != ''">
            AND ll.username LIKE CONCAT('%', #{loginLog.username}, '%')
        </if>
        <if test="loginLog.ipAddress != null and loginLog.ipAddress != ''">
            AND ll.ip_address = #{loginLog.ipAddress}
        </if>
        <if test="loginLog.status != null">
            AND ll.status = #{loginLog.status}
        </if>
        <if test="loginLog.browser != null and loginLog.browser != ''">
            AND ll.browser LIKE CONCAT('%', #{loginLog.browser}, '%')
        </if>
        <if test="loginLog.os != null and loginLog.os != ''">
            AND ll.os LIKE CONCAT('%', #{loginLog.os}, '%')
        </if>
        ORDER BY ll.login_time DESC
        LIMIT #{pageParam.pageSize} OFFSET #{pageParam.offset}
    </select>

    <!-- 统计登录日志数量（带权限过滤） -->
    <select id="countLoginLog" resultType="int">
        SELECT COUNT(DISTINCT ll.id)
        FROM tb_sys_login_log ll
        <include refid="Permission_Filter"/>
        <if test="loginLog.userID != null and loginLog.userID != ''">
            AND ll.user_id = #{loginLog.userID}
        </if>
        <if test="loginLog.username != null and loginLog.username != ''">
            AND ll.username LIKE CONCAT('%', #{loginLog.username}, '%')
        </if>
        <if test="loginLog.ipAddress != null and loginLog.ipAddress != ''">
            AND ll.ip_address = #{loginLog.ipAddress}
        </if>
        <if test="loginLog.status != null">
            AND ll.status = #{loginLog.status}
        </if>
        <if test="loginLog.browser != null and loginLog.browser != ''">
            AND ll.browser LIKE CONCAT('%', #{loginLog.browser}, '%')
        </if>
        <if test="loginLog.os != null and loginLog.os != ''">
            AND ll.os LIKE CONCAT('%', #{loginLog.os}, '%')
        </if>
    </select>
</mapper>
