<?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.ga.core.mapper.user.RoleMapper">

    <resultMap id="RoleMap" type="com.ga.core.vo.user.RoleVO"/>

    <select id="selectAll" resultMap="RoleMap">
        SELECT role_id, role_code, role_name, role_desc, role_level, is_system, is_active
        FROM role
        ORDER BY role_level DESC, role_id
    </select>

    <select id="selectById" resultMap="RoleMap">
        SELECT role_id, role_code, role_name, role_desc, role_level, is_system, is_active
        FROM role WHERE role_id = #{roleId}
    </select>

    <insert id="insert" parameterType="com.ga.core.vo.user.RoleVO" useGeneratedKeys="true" keyProperty="roleId">
        INSERT INTO role (role_code, role_name, role_desc, role_level, is_system, is_active)
        VALUES (#{roleCode}, #{roleName}, #{roleDesc}, COALESCE(#{roleLevel},0),
                COALESCE(#{isSystem},'N'), COALESCE(#{isActive},'Y'))
    </insert>

    <update id="update" parameterType="com.ga.core.vo.user.RoleVO">
        UPDATE role SET role_name = #{roleName}, role_desc = #{roleDesc},
                        role_level = #{roleLevel}, is_active = #{isActive}
        WHERE role_id = #{roleId} AND is_system = 'N'
    </update>

    <delete id="deleteById">
        DELETE FROM role WHERE role_id = #{roleId} AND is_system = 'N'
    </delete>

    <select id="selectRolePermissions" resultType="map">
        SELECT menu_id   AS "menuId",
               perm_code AS "permCode",
               is_granted AS "isGranted"
        FROM role_menu_permission WHERE role_id = #{roleId}
    </select>

    <delete id="deleteRolePermissions">
        DELETE FROM role_menu_permission WHERE role_id = #{roleId}
    </delete>

    <insert id="insertRolePermission">
        INSERT INTO role_menu_permission (role_id, menu_id, perm_code, is_granted)
        VALUES (#{roleId}, #{menuId}, #{permCode}, COALESCE(#{isGranted},'Y'))
    </insert>

</mapper>
