using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Data;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using Hncore.Infrastructure.WebApi;
using Hncore.Pass.Manage.Request;
using Hncore.Infrastructure.EntitiesExtension;
using Hncore.Infrastructure.Extension;

namespace Hncore.Pass.Manage.Response.ManagerToPermission
{
    public class QueryPermissionByManagerIdResponse
    {
        /// <summary>
        /// ID
        /// <summary>
        public  int Id { get; set; }

        /// <summary>
        /// 所属物业ID
        /// <summary>
        public int OwnerId { get; set; }
        
        /// <summary>
        /// 管理员数据库ID
        /// </summary>
        public int ManagerId { get; set; }

        /// <summary>
        /// 项目编码
        /// </summary>
        public int ProjectCode { get; set; }
        /// <summary>
        /// 小区名称
        /// </summary>
        public string ProjectName { get; set; }

        /// <summary>
        /// 管理员与权限对应表
        /// </summary>
        /// <param name="domainQueryable"></param>
        /// <param name="managerId"></param>
        /// <returns></returns>
        public static async Task<List<QueryPermissionByManagerIdResponse>> GetByManageId(
            IQueryable<Domain.AuthorityManagerDataDomain> domainQueryable,
            IQueryable<Domain.etor_property_estate> projects,
            IQueryable<Domain.Manager> manages ,
            int managerId)
        {
            List<QueryPermissionByManagerIdResponse> result = new List<QueryPermissionByManagerIdResponse>();
            var manage = await manages.FirstOrDefaultAsync(p=>p.Id== managerId);
            if (manage.IsRoot)
            {
                result = await projects.Where(p => p.owner_id == manage.TenantId && p.DeleteTag == 0).Select(r => new QueryPermissionByManagerIdResponse()
                {
                    Id = 0,
                    ManagerId = managerId,
                    OwnerId = r.owner_id,
                    ProjectCode = r.projectcode,
                    ProjectName = r.name
                }).ToListAsync();
            }
            else {
                result = await (from domain in domainQueryable.Where(p => p.ManagerId == managerId && p.DeleteTag == 0)
                                join pro in projects
                                on domain.ProjectCode equals pro.projectcode
                                select new QueryPermissionByManagerIdResponse()
                                {
                                    Id = domain.Id,
                                    ManagerId = domain.ManagerId,
                                    OwnerId = domain.TenantId,
                                    ProjectCode = domain.ProjectCode,
                                    ProjectName = pro.name
                                }).ToListAsync();
            }
            return  result;
        }
    }
}
