/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.wlyy.repository.consult;

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;

import com.yihu.wlyy.entity.consult.ConsultCommunication;

public interface ConsultCommunicationDao extends PagingAndSortingRepository<ConsultCommunication, Long>, JpaSpecificationExecutor<ConsultCommunication> {

	ConsultCommunication findByConsult(String consult);

	// 回复数量+1
	@Modifying
	@Query("update ConsultCommunication a set a.amount = a.amount + 1 where a.consult = ?1")
	int increaseAmount(String consult);

	// 未读数量+1
	@Modifying
	@Query("update ConsultCommunication a set a.unread = a.unread + 1 where a.consult = ?1")
	int increaseUnread(String consult);

	// 清空未读数量
	@Modifying
	@Query("update ConsultCommunication a set a.unread = 0 where a.consult = ?1")
	int clearUnRead(String consult);

	// 患者回答过的病友咨询记录
	@Query("SELECT a FROM ConsultCommunication a, ConsultCommunicationReply b WHERE a.patient <> ?1 and a.del = '1' and a.consult = b.consult and b.patient = ?2 GROUP BY a.consult ORDER BY a.czrq DESC")
	Page<ConsultCommunication> findPatienReplied(String patient, String patient2, Pageable pageRequest);

	@Query("SELECT a FROM ConsultCommunication a, ConsultCommunicationReply b WHERE a.patient <> ?1 and a.del = '1' and a.consult = b.consult and b.patient = ?2 and a.id < ?3 GROUP BY a.consult ORDER BY a.czrq DESC")
	Page<ConsultCommunication> findPatienReplied(String patient, String patient2, long id, Pageable pageRequest);
	
	@Query("SELECT a FROM ConsultCommunication a, ConsultCommunicationReply b WHERE a.patient <> ?1 and a.del = '1' and a.consult = b.consult and b.patient = ?2 and a.disease = ?3 GROUP BY a.consult ORDER BY a.czrq DESC")
	Page<ConsultCommunication> findPatienReplied(String patient, String patient2, String disease, Pageable pageRequest);

	@Query("SELECT a FROM ConsultCommunication a, ConsultCommunicationReply b WHERE a.patient <> ?1 and a.del = '1' and a.consult = b.consult and b.patient = ?2 and a.disease = ?3 and a.id < ?3 GROUP BY a.consult ORDER BY a.czrq DESC")
	Page<ConsultCommunication> findPatienReplied(String patient, String patient2, String disease, long id, Pageable pageRequest);
}
