package com.yihu.wlyy.repository.template;

import com.yihu.wlyy.entity.template.DoctorTeamGuidanceTemplate;
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 java.util.List;

/**
 * Created by Reece on 2017/6/8.
 */
public interface DoctorTeamGuidanceTemplateDao extends PagingAndSortingRepository<DoctorTeamGuidanceTemplate, Long>, JpaSpecificationExecutor<DoctorTeamGuidanceTemplate> {

    //    新增团队模板时团队内标题排重
    @Query("select t from DoctorTeamGuidanceTemplate t where t.del = 1 and t.title = ?1 and t.teamId = ?2 ")
    List<DoctorTeamGuidanceTemplate> distinctByTeamTitle(String title, int teamId);

    //    根据团队ID获取团队内的模板列表（带分页和创建时间倒序）
    @Query("select t from DoctorTeamGuidanceTemplate t where t.del = 1 and t.teamId = ?1 ")
    List<DoctorTeamGuidanceTemplate> findGuidanceByTeamId(int teamId, Pageable request);

    //    由模板编码获取拥有该模板的团队信息
    @Query("select t from DoctorTeamGuidanceTemplate t where t.del = 1 and t.teamTemplateCode = ?1 ")
    List<DoctorTeamGuidanceTemplate> getTeamsByGuidance(String guidanceCode);

    //    根据团队ID及模板编码删除团队所属的团队模板
    @Modifying
    @Query("update DoctorTeamGuidanceTemplate t set t.del = 0 where t.teamId = ?1 and t.teamTemplateCode =?2 ")
    int deleteTeamGuidance(int teamId, String guidanceCode);

    //  根据模板编码更改团队模板对应表
    @Modifying
    @Query("update DoctorTeamGuidanceTemplate t set t.title = ?3 where t.del = 1 and t.teamId = ?1 and t.teamTemplateCode =?2 ")
    int modifyTeamGuidance(int teamId, String guidanceCode, String title);

    //  每给居民发送一次团队指导，使用数量加1
    @Modifying
    @Query("update DoctorTeamGuidanceTemplate t set t.useTimes = t.useTimes+1 where t.del = 1 and t.teamId = ?1 and t.teamTemplateCode =?2 ")
    int countSend(int teamId, String guidanceCode);

    //  批量删除（失效）该模板所在的所有团队关系
    @Modifying
    @Query("update DoctorTeamGuidanceTemplate t set t.useTimes =  0 ,t.del = 0 where t.teamId = ?1 and t.teamTemplateCode =?2 ")
    int deleteByTeam(int teamId, String guidanceCode);

}
