<?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.aiotagro.cattletrade.business.mapper.SysMenuMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.aiotagro.cattletrade.business.entity.SysMenu">
        <id column="id" property="id" />
        <result column="parent_id" property="parentId" />
        <result column="type" property="type" />
        <result column="icon" property="icon" />
        <result column="name" property="name" />
        <result column="sort" property="sort" />
        <result column="route_url" property="routeUrl" />
        <result column="page_url" property="pageUrl" />
        <result column="authority" property="authority" />
        <result column="create_time" property="createTime" />
        <result column="update_time" property="updateTime" />
        <result column="is_delete" property="isDelete" />
    </resultMap>

    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
        id, parent_id, type, icon, name, sort, route_url, page_url, authority, create_time, update_time, is_delete
    </sql>
    <select id="queryMenusByUserId" resultType="com.aiotagro.cattletrade.business.entity.SysMenu">
        SELECT m.*
        FROM sys_menu m
                 LEFT JOIN sys_role_menu rm ON m.id = rm.menu_id
                 LEFT JOIN sys_user u ON rm.role_id = u.role_id
        WHERE u.is_delete = 0
          AND m.is_delete = 0
          AND u.id = #{userId}
    </select>

    <select id="queryListByRoleId" resultType="com.aiotagro.cattletrade.business.entity.SysMenu">
        SELECT m.id, m.parent_id, m.name, m.type, m.icon, m.route_url,
               m.page_url, m.sort, m.authority, m.create_time,
               CASE WHEN rm.menu_id IS NOT NULL THEN 1 ELSE 0 END AS isSelected
        FROM sys_menu m
                 LEFT JOIN sys_role_menu rm ON m.id = rm.menu_id 
                 <if test="roleId != null">
                     AND rm.role_id = #{roleId}
                 </if>
        WHERE m.is_delete = 0
    </select>

    <select id="selectMenusByRoleId" resultType="com.aiotagro.cattletrade.business.entity.SysMenu">
        SELECT DISTINCT m.*
        FROM sys_menu m
        INNER JOIN sys_role_menu rm ON m.id = rm.menu_id
        WHERE rm.role_id = #{roleId}
          AND m.is_delete = 0
        ORDER BY m.sort ASC
    </select>

    <select id="selectMenusByPermissions" resultType="com.aiotagro.cattletrade.business.entity.SysMenu">
        SELECT DISTINCT m.*
        FROM sys_menu m
        WHERE m.is_delete = 0
          AND m.authority IN
        <foreach collection="permissions" item="permission" open="(" separator="," close=")">
            #{permission}
        </foreach>
        ORDER BY m.sort ASC
    </select>

</mapper>
