/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.wlyy.statistics.dao;

import com.yihu.wlyy.statistics.model.signfamily.Message;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;

public interface MessageDao extends PagingAndSortingRepository<Message, Long>, JpaSpecificationExecutor<Message> {
    @Query("select count(a) from Message a where a.type =1 and a.read= 1 and a.receiver=?1 ")
    int amountUnreadByReceiver(String doctor);

    @Query("select count(a) from Message a where a.read = 0 and over ='0'  and a.receiver=?1 and a.type=3 ")
    int amountUnreadSystemByReceiver(String doctor);


    @Query("select a from Message a where a.type =1 and a.read= 1 and a.receiver=?1 order by a.czrq desc")
    Page<Message> amountUnreadLastByReceiver(String doctor, Pageable pageRequest);

    @Query("select count(a) from Message a where a.type =2 and a.read= 1 and a.receiver=?1 ")
    int amountUnreadHealthByReceiver(String doctor);

    @Query("select a from Message a where (a.type =2 ) and a.read= 1 and a.receiver=?1 order by a.czrq desc")
    Page<Message> amountUnreadHealthLastByReceiver(String doctor, Pageable pageRequest);

    @Modifying
    @Query("update Message a set a.read = 0,a.over='0' where a.id = ?1")
    int read(long msgid);

    @Query("SELECT a FROM Message a WHERE a.sender=?1 AND a.receiver = ?2 and a.signStatus = ?3 and read=1")
    Message findByParams(String sender, String receiver, String signStatus);

    @Query("SELECT a FROM Message a WHERE a.sender=?1 AND a.receiver = ?2 and a.signStatus = ?3 ")
    Message findAllByParams(String sender, String receiver, String signStatus);

    @Query(" from Message a where a.read = 1 and over ='1' and a.sender = ?1 and a.receiver=?2 and a.signStatus='1'")
    Message findByPatient(String patient, String doctor);

    @Query("select count(a) from Message a where a.read = 0 and over ='0'  and a.receiver=?1 and a.type=?2 ")
    int findMessageNum(String doctor, Integer type);


}
