package com.ywt.mg.domain.entities;

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

import java.util.List;

public interface DepartmentRepository extends JpaRepository<Department, Integer> {
    @Query(value = "Select * From department Where hospital_id = ? and is_deleted = 0;", nativeQuery = true)
    List<Department> findByHospitalId(Integer hospitalId);

    List<Department> findAllByHospitalId(Integer hospitalId);


    /**
     * 判断同一层级下的科室是否有重复的（自身除外），修改时调用
     *
     * @param hospitalId
     * @param deptId
     * @param deptName
     * @return
     */
    @Query(value = "SELECT COUNT(1) FROM department WHERE hospital_id = ? AND parent_id = ? AND id != ? AND name = ? limit 1;",nativeQuery = true)
    int checkUnique(int hospitalId, int parentId, int deptId, String deptName);

    /**
     * 一级科室：添加科室判断是否会重名
     *
     * @param parentDeptName
     * @return
     */
    @Query(value = "SELECT COUNT(1) FROM department WHERE parent_id = 0  AND name = ? limit 1;",nativeQuery = true)
    int checkParentDeptNameUnion(String parentDeptName);


    /**
     * 一级科室：修改科室判断是否会重名
     *
     * @param parentDeptName
     * @param deptId
     * @return
     */
    @Query(value = "SELECT COUNT(1) FROM department WHERE parent_id = 0  AND name = ? AND  id != ? limit 1;",nativeQuery = true)
    int checkParentDeptNameUnion(String parentDeptName, int deptId);


    /**
     * 二级科室添加：判断该一级科室是否已经添加了这个科室
     *
     * @param deptName
     * @return
     */
    @Query(value = "SELECT COUNT(1) FROM department WHERE parent_id != 0  AND name = ? limit 1;",nativeQuery = true)
    int checkSecendDeptNameUnion(String deptName);


    /**
     * 二级科室修改：判断该一级科室是否已经添加了这个科室
     *
     * @param deptName
     * @return
     */
    @Query(value = "SELECT COUNT(1) FROM department WHERE parent_id != 0  AND name = ? AND  id != ? limit 1;",nativeQuery = true)
    int checkSecendDeptNameUnion(String deptName, int deptId);

    /**
     * 根据医院id和科室名称得到与之匹配的该医院的一级科室列表
     *
     * @param hospitalNameId
     * @param parentDeptName
     * @return
     */
    @Query(value = "SELECT * FROM department WHERE hospital_id = ? AND parent_id = 0  AND name = ? limit 1;",nativeQuery = true)
    List<Department> getParentDeptList(int hospitalNameId, String parentDeptName);



}
