package com.yihu.wlyy.repository.doctor;

import com.yihu.wlyy.entity.doctor.team.admin.AdminTeam;
import com.yihu.wlyy.entity.patient.Patient;
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 org.springframework.data.repository.query.Param;

import java.util.List;

/**
 * 行政团队DAO。
 * 
 * @author Sand
 */
public interface DoctorAdminTeamDao extends
        PagingAndSortingRepository<AdminTeam, Long>,
        JpaSpecificationExecutor<AdminTeam> {
    /**
     * 团队内，全科医生的签约数。
     *
     * @param doctorCode
     * @param teamId
     * @return
     */
    @Query("SELECT count(s) FROM SignFamily s WHERE doctor = :doctorCode AND adminTeamId = :teamId")
    Integer getDoctorSignCount(@Param(value = "doctorCode") String doctorCode,
                               @Param(value = "teamId") long teamId);

    /**
     * 团队内，健康管理师的签约数。
     *
     * @param healthDoctorCode
     * @param teamId
     * @return
     */
    @Query("SELECT count(s) FROM SignFamily s WHERE doctorHealth = :healthDoctorCode AND adminTeamId = :teamId")
    Integer getHealthDoctorSignCount(@Param(value = "healthDoctorCode") String healthDoctorCode,
                                     @Param(value = "teamId") long teamId);

    /**
     * 团队内，健康管理师的签约患者。
     *
     * @param healthDoctorCode
     * @param pageable
     * @return
     */
    @Query("SELECT p FROM SignFamily s, Patient p WHERE s.doctorHealth = :healthDoctorCode AND s.patient = p.code AND" +
            " s.adminTeamId = :teamId")
    Page<Patient> getHealthDoctorSigningPatients(@Param(value = "healthDoctorCode") String healthDoctorCode,
                                                 @Param(value = "teamId") long teamId,
                                                 Pageable pageable);

    /**
     * 患者所签约团队。
     *
     * @param patientCode
     * @return
     */
    @Query("SELECT  t.id, t.name, d1.code, d1.name, d2.code, d2.name\n" +
            "FROM SignFamily f, Doctor d1, Doctor d2, AdminTeam t, AdminTeamMember m \n" +
            "WHERE d1.code = f.doctor AND f.doctorHealth = d2.code AND f.patient = :patientCode AND m.doctorCode = " +
            "d1.code AND m.teamId = t.id")
    Object getPatientSigningTeam(@Param("patientCode") String patientCode);

    @Query("SELECT t.id from AdminTeam t WHERE t.leaderCode = :leaderCode")
    Long findIdByLeaderCode(@Param("leaderCode") String leaderCode);


}
