using Hncore.Infrastructure.EF;
using Hncore.Pass.Manage.Configs;
using Hncore.Pass.Manage.Domain;
using Hncore.Pass.Manage.Repository;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using System;
using System.Linq;
using System.Linq.Expressions;

namespace Hncore.Pass.Manage.Service
{
    /// <summary>
    /// 父业务逻辑类
    /// </summary>
    ///
    public abstract class BaseService
    {
        /// <summary>
        /// 配置文件数据承载对象
        /// </summary>
        protected readonly AppSettings _appSettings;

        /// <summary>
        /// EF上下文对象
        /// </summary>
        protected readonly EfDbContext _dbCtx;

        /// <summary>
        /// 数据库连接字符串
        /// </summary>
        public string OldDbConString { get { return _appSettings.OldDbConString; } }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="hca">HTTP上下文访问对象</param>
        public BaseService(IHttpContextAccessor hca)
        {
            this._dbCtx= hca.HttpContext.RequestServices.GetService(typeof(EfDbContext)) as EfDbContext;            
            //获取当前应用配置信息承载对象
            var oa=hca.HttpContext.RequestServices.GetService(typeof(IOptionsMonitor<AppSettings>)) as IOptionsMonitor<AppSettings>;
            this._appSettings = oa.CurrentValue;
        }

        /// <summary>
        /// 获取操作员有权操作的项目编码列表(可直接用于EF查询中的Labmda查询条件中)
        /// </summary>
        /// <param name="operaterId">操作员数据库ID</param>
        /// <param name="ownerId">隶属的物业ID</param>
        /// <returns>有权操作的项目编码列表，没有就返回null</returns>
        public IQueryable<int> GetManagerProjectCodeList(int operaterId, int ownerId = 0)
        {
            if (operaterId <= 0)
                return null;

            Expression<Func<AuthorityManagerDataDomain, bool>> expression = c => c.DeleteTag == 0 && c.ManagerId == operaterId;
            if (ownerId > 0)
            {//如果传递了物业ID，需要动态将物业ID追加到Lambda表达式中去
                var p1 = expression.Parameters[0];
                var ownerIdExpression = Expression.PropertyOrField(p1, "OwnerId");
                var m3 = Expression.Equal(ownerIdExpression, Expression.Constant(ownerId));
                var body= Expression.And(expression.Body, m3);
                expression = Expression.Lambda<Func<AuthorityManagerDataDomain, bool>>(body, p1);
            }
            IQueryable<int> list = _dbCtx.Set<AuthorityManagerDataDomain>().GetQueryable().Where(expression).Select(c => c.ProjectCode);
            return list;
        }

    }
}
