<?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.hzs.system.sys.mapper.SysUserCountryMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.hzs.common.domain.system.sys.SysUserCountry">
        <result column="USER_ID" property="userId"/>
        <result column="PK_COUNTRY" property="pkCountry"/>
        <result column="IS_DEFAULT" property="isDefault"/>
    </resultMap>

    <!-- 根据userId查询默认地区 -->
    <select id="queryDefaultUserCountry" resultMap="BaseResultMap">
        select *
        from (select t.*, rownum
              from sys_user_country t
              where t.user_id = #{userId}
              order by t.is_default, t.PK_COUNTRY) t
        where rownum = 1
    </select>

    <!-- 查询用户国家权限 -->
    <select id="queryUserCountry" resultType="com.hzs.common.domain.system.sys.ext.SysUserCountryExt">
        select suc.*, bc.short_name as name, bc.NATIONAL_FLAG1, bc.NATIONAL_FLAG2, bc.pk_transaction
        from SYS_USER_COUNTRY suc
                 inner join BD_COUNTRY bc
                            on suc.pk_country = bc.pk_id
        where suc.user_id = #{userId}
          and bc.del_flag = 0
          and bc.ENABLE_STATE = 0
        order by suc.pk_country
    </select>

    <!-- 校验用户是否有国家权限 -->
    <select id="checkUserCountry" resultType="int">
        select count(user_id)
        from SYS_USER_COUNTRY
        where user_id = #{userId}
          and pk_country = #{pkCountry}
    </select>

    <!-- 批量插入地区数据权限 -->
    <insert id="insertUserCountryBatch">
        INSERT ALL
        <foreach collection="list" item="item" separator=" ">
            into SYS_USER_COUNTRY (
            USER_ID, PK_COUNTRY
            <if test="null != item.isDefault">
                , IS_DEFAULT
            </if>
            )
            values
            (#{item.userId}, #{item.pkCountry}
            <if test="null != item.isDefault">
                , #{item.isDefault}
            </if>
            )
        </foreach>
        SELECT 1 FROM dual
    </insert>

    <!-- 删除用户地区权限 -->
    <delete id="deleteUserCountryByUserId">
        delete
        from SYS_USER_COUNTRY
        where user_id = #{userId}
    </delete>

</mapper>
