using Microsoft.EntityFrameworkCore;
using Performance.EntityModels;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Performance.Repository
{
    public partial class PerforUserRepository : PerforRepository<sys_user>
    {
        /// <summary>
        /// 获取用户 医院 角色 过往科室
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public UserInfoCenter GetUser(int userId)
        {
            var user = context.Set<sys_user>().FirstOrDefault(w => w.IsDelete == 1 && w.ID == userId);
            if (user == null)
                return null;

            var roles = from ur in context.Set<sys_user_role>()
                        join r in context.Set<sys_role>() on ur.RoleID equals r.ID
                        where ur.UserID == user.ID
                        select r;

            var hospitals = from uh in context.Set<sys_user_hospital>()
                            join h in context.Set<sys_hospital>() on uh.HospitalID equals h.ID
                            where uh.UserID == user.ID
                            select h;

            var roleTypes = new int[] { (int)Role.科主任, (int)Role.护士长, (int)Role.特殊科室, (int)Role.行政科室, };

            return new UserInfoCenter
            {
                User = user,
                URole = roles.FirstOrDefault() ?? new sys_role(),
                Hospitals = hospitals.ToList() ?? new List<sys_hospital>(),
                IsSecondAdmin = roleTypes.Contains(roles.FirstOrDefault()?.Type ?? 0),
            };
        }

        /// <summary>
        /// 获取指定RoleType的用户
        /// </summary>
        /// <param name="roleType"></param>
        /// <returns></returns>
        public List<sys_user> GetUsersByRoleType()
        {
            var users = from u in context.Set<sys_user>()
                        join ur in context.Set<sys_user_role>() on u.ID equals ur.UserID
                        join r in context.Set<sys_role>() on ur.RoleID equals r.ID
                        select new { u, r };

            return users.Select(w => w.u).ToList();
        }
    }

}
