<?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.goldenwater.system.mapper.SysNoticeReadMapper">
    <resultMap type="SysNoticeRead" id="SysNoticeReadResult">
        <id property="readId" column="read_id"/>
        <result property="noticeId" column="notice_id"/>
        <result property="userId" column="user_id"/>
        <result property="readTime" column="read_time"/>
    </resultMap>
    <insert id="insertNoticeRead" parameterType="SysNoticeRead">
        MERGE INTO sys_notice_read t
        USING (SELECT #{noticeId} AS notice_id, #{userId} AS user_id, SYSDATE AS read_time FROM DUAL) s
        ON (t.notice_id = s.notice_id AND t.user_id = s.user_id)
        WHEN NOT MATCHED THEN INSERT (notice_id, user_id, read_time) VALUES (s.notice_id, s.user_id, s.read_time)
    </insert>
    <select id="selectUnreadCount" resultType="int">select count(*) from sys_notice n where n.status = '0' and not exists (select 1 from sys_notice_read r where r.notice_id = n.notice_id and r.user_id = #{userId})</select>
    <select id="selectIsRead" resultType="int">select count(*) from sys_notice_read where notice_id = #{noticeId} and user_id = #{userId}</select>
    <select id="selectNoticeListWithReadStatus" resultType="SysNotice">
        SELECT * FROM (
        select n.notice_id as noticeId, n.notice_title as noticeTitle, n.notice_type as noticeType, n.status, n.create_by as createBy, n.create_time as createTime,
        case when r.notice_id is not null then true else false end as isRead
        from sys_notice n left join sys_notice_read r on r.notice_id = n.notice_id and r.user_id = #{userId}
        where n.status = '0' order by n.notice_id desc
        ) _t LIMIT #{limit}
    </select>
    <insert id="insertNoticeReadBatch">
        <foreach collection="noticeIds" item="noticeId" separator=";">
            MERGE INTO sys_notice_read t
            USING (SELECT #{noticeId} AS notice_id, #{userId} AS user_id, SYSDATE AS read_time FROM DUAL) s
            ON (t.notice_id = s.notice_id AND t.user_id = s.user_id)
            WHEN NOT MATCHED THEN INSERT (notice_id, user_id, read_time) VALUES (s.notice_id, s.user_id, s.read_time)
        </foreach>
    </insert>
    <delete id="deleteByNoticeIds">delete from sys_notice_read where notice_id in <foreach collection="noticeIds" item="noticeId" open="(" separator="," close=")">#{noticeId}</foreach></delete>
</mapper>
