<?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.SysOperationLogMapper">

    <!-- 基础结果映射 -->
    <resultMap id="BaseResultMap" type="org.xyzh.common.dto.system.TbSysOperationLog">
        <id column="id" property="id" jdbcType="VARCHAR"/>
        <result column="user_id" property="userID" jdbcType="VARCHAR"/>
        <result column="username" property="username" jdbcType="VARCHAR"/>
        <result column="module" property="module" jdbcType="VARCHAR"/>
        <result column="operation" property="operation" jdbcType="VARCHAR"/>
        <result column="method" property="method" jdbcType="VARCHAR"/>
        <result column="request_url" property="requestUrl" jdbcType="VARCHAR"/>
        <result column="request_method" property="requestMethod" jdbcType="VARCHAR"/>
        <result column="request_params" property="requestParams" jdbcType="LONGVARCHAR"/>
        <result column="response_data" property="responseData" jdbcType="LONGVARCHAR"/>
        <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="status" property="status" jdbcType="INTEGER"/>
        <result column="error_message" property="errorMessage" jdbcType="LONGVARCHAR"/>
        <result column="execute_time" property="executeTime" jdbcType="INTEGER"/>
        <result column="create_time" property="createTime" jdbcType="TIMESTAMP"/>
    </resultMap>

    <!-- 基础字段 -->
    <sql id="Base_Column_List">
        id, user_id, username, module, operation, method, request_url, 
        request_method, request_params, response_data, ip_address, ip_source, 
        browser, os, status, error_message, execute_time, create_time
    </sql>

    <!-- 权限过滤：通过用户的部门路径进行权限控制，superadmin可查看所有 -->
    <sql id="Permission_Filter">
        INNER JOIN tb_sys_user u ON ol.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>

    <!-- 通用条件 -->
    <sql id="Where_Clause">
        <if test="operationLog.userID != null and operationLog.userID != ''">
            AND ol.user_id = #{operationLog.userID}
        </if>
        <if test="operationLog.username != null and operationLog.username != ''">
            AND ol.username LIKE CONCAT('%', #{operationLog.username}, '%')
        </if>
        <if test="operationLog.module != null and operationLog.module != ''">
            AND ol.module LIKE CONCAT('%', #{operationLog.module}, '%')
        </if>
        <if test="operationLog.operation != null and operationLog.operation != ''">
            AND ol.operation = #{operationLog.operation}
        </if>
        <if test="operationLog.status != null">
            AND ol.status = #{operationLog.status}
        </if>
        <if test="operationLog.ipAddress != null and operationLog.ipAddress != ''">
            AND ol.ip_address = #{operationLog.ipAddress}
        </if>
        <if test="operationLog.requestUrl != null and operationLog.requestUrl != ''">
            AND ol.request_url LIKE CONCAT('%', #{operationLog.requestUrl}, '%')
        </if>
    </sql>

    <!-- 插入操作日志 -->
    <insert id="insertOperationLog" parameterType="org.xyzh.common.dto.system.TbSysOperationLog">
        INSERT INTO tb_sys_operation_log (
            id, user_id, username, module, operation, method, 
            request_url, request_method, request_params, response_data,
            ip_address, ip_source, browser, os, status, 
            error_message, execute_time, create_time
        ) VALUES (
            #{id}, #{userID}, #{username}, #{module}, #{operation}, #{method},
            #{requestUrl}, #{requestMethod}, #{requestParams}, #{responseData},
            #{ipAddress}, #{ipSource}, #{browser}, #{os}, #{status},
            #{errorMessage}, #{executeTime}, #{createTime, jdbcType=TIMESTAMP}
        )
    </insert>

    <!-- 查询操作日志列表（带权限过滤） -->
    <select id="selectOperationLogList" resultMap="BaseResultMap">
        SELECT DISTINCT ol.*
        FROM tb_sys_operation_log ol
        <include refid="Permission_Filter"/>
        <include refid="Where_Clause"/>
        ORDER BY ol.create_time DESC
    </select>

    <!-- 分页查询操作日志列表（带权限过滤） -->
    <select id="selectOperationLogPage" resultMap="BaseResultMap">
        SELECT DISTINCT ol.*
        FROM tb_sys_operation_log ol
        <include refid="Permission_Filter"/>
        <include refid="Where_Clause"/>
        ORDER BY ol.create_time DESC
        LIMIT #{pageParam.pageSize} OFFSET #{pageParam.offset}
    </select>

    <!-- 统计操作日志数量（带权限过滤） -->
    <select id="countOperationLog" resultType="int">
        SELECT COUNT(DISTINCT ol.id)
        FROM tb_sys_operation_log ol
        <include refid="Permission_Filter"/>
        <include refid="Where_Clause"/>
    </select>

</mapper>
