package com.ywt.outpatient.domain.entity.center;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

/**
 * created by daiyihua
 */
public interface ArticlesUnionRepository extends JpaRepository<ArticlesUnion, Integer> {

    /**
     * 根据资讯ID和医生ID判断表中有没有这条记录
     *
     * @param artId
     * @param doctorId
     * @return
     */
    @Query(value = "select count(1) from articles_union where art_id = ? and obj_id = ? and type = 1 and deleted = 0", nativeQuery = true)
    int checkExists(int artId, int doctorId);

    /**
     * 根据资讯ID和医生ID得到记录对象
     *
     * @param artId
     * @param doctorId
     * @return
     */
    @Query(value = "select * from articles_union where art_id = ? and obj_id = ? and type =1 and deleted = 0", nativeQuery = true)
    ArticlesUnion getArticlesUnion(int artId, int doctorId);

    /**
     * 根据医生ID得到该医生没有读的资讯数量
     *
     * @param doctorId
     * @return
     */
    @Query(value = "select count(1) from articles_union where obj_id = ? and type = 1 and deleted = 0 and ((status & 16) = 16) ", nativeQuery = true)
    int getArticlesNoReadCount(int doctorId);

    /**
     * 推送医生数
     *
     * @param articleId
     * @return
     */
    @Query(value = "select count(1) from articles_union where art_id = ? and type = 1 and deleted = 0;", nativeQuery = true)
    int getDoctorCount(int articleId);

    /**
     * 根据经销商ID得到其所有资讯的设置记录
     *
     * @param drugProviderId
     * @return
     */
    @Query(value = "select * from articles_union where obj_id = ? and type = 2 and deleted = 0", nativeQuery = true)
    List<ArticlesUnion> getDrugProviderPush(int drugProviderId);

    /**
     * 根据资讯ID得到资讯设置
     *
     * @param artId
     * @return
     */
    @Query(value = "select * from articles_union where art_id = ? and type = 2 and deleted = 0 limit 1;", nativeQuery = true)
    ArticlesUnion getArticlesSetting(int artId);

    /**
     * 获取某个医生所有资讯设置
     * @param doctorId 医生id
     * @return article union list
     */
    @Query(value = "select * from articles_union where obj_id =  ? and type = 1 and deleted = 0 order by status , update_time desc", nativeQuery = true)
    List<ArticlesUnion> getAllByDoctorId(int doctorId);

    /**
     * 获取某个经销商所有设置推送的文章
     * @param merchantId merchant id
     * @return result list
     */
    @Query(value = "select * from articles_union where obj_id = ? and type = 2 and deleted = 0 and ((status & 2) = 2) order by update_time desc", nativeQuery = true)
    List<ArticlesUnion> getAllAvailableArticlesByMerchantId(int merchantId);

    @Query(value = "select * from articles_union where art_id = ? and user_id = ? and type =1 and deleted = 0", nativeQuery = true)
    ArticlesUnion getArticlesUnionByArtIdAndUserId(int artId, int userId);
}
