using Hncore.Infrastructure.Common;
using Hncore.Infrastructure.DDD;
using Hncore.Infrastructure.WebApi;
using Hncore.Pass.Manage.Domain;
using Hncore.Pass.Manage.Request;
using Hncore.Pass.Manage.Response;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Hncore.Infrastructure.EntitiesExtension;
using Hncore.Pass.Manage.Repository;
using Hncore.Infrastructure.EF;

namespace Hncore.Pass.Manage.Service
{


    /// <summary>
    /// 管理员业务逻辑类
    /// </summary>
    ///
    public class ManagerPermissionService : BaseService
    {
        EfDbContext m_DbContext { get; set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="">管理员标签查询对象</param>

        public ManagerPermissionService(EfDbContext _DbContext,          
            IHttpContextAccessor hca) : base(hca)
        {
            m_DbContext = _DbContext;
        }
        /// <summary>
        /// 获取管理员权限
        /// </summary>
        /// <param name="request">请求对象</param>
        /// <returns>响应列表对象</returns>
        public async Task<List<QueryPermissionResponse>> GetByOperator(QueryByIdRequest param,bool showAll)
        {
            //获取到所拥有的所有权限
            // var meCodes = m_DbContext.Set<ManagerToPermission>().GetQueryable().Where(c => c.DeleteTag == 0 && c.ManagerId == param.Id).Select(c => c.PermissionCode);
            // var search = m_DbContext.Set<Permission>().GetQueryable().Where(c => c.DeleteTag == 0 && c.Systemid == 100 && meCodes.Contains(c.Permissioncode));
            var managerpPrmissions = new List<ManagerToPermission>();
            var manager = await m_DbContext.Set<Manager>().FindByIdAsync(param.Id);
            var permissions = m_DbContext.Set<Permission>().GetQueryable()
                                .Where(c => c.DeleteTag == 0 && c.Systemid == 100)
                                .OrderBy(m => m.Sortorder)
                                .ToList();
            if (manager.IsRoot)
            {
                permissions.ForEach(m => {
                    managerpPrmissions.Add(new ManagerToPermission()
                    {
                        AllowAdd = 1,
                        AllowDel = 1,
                        AllowEdit = 1,
                        AllowView = 1,
                        ManagerId = manager.Id,
                        PermissionCode = m.Permissioncode,
                        TenantId = manager.TenantId,
                    });
                });             
            }              
            else
            {
                managerpPrmissions = m_DbContext.Set<ManagerToPermission>().GetQueryable().Where(c => c.DeleteTag == 0 && c.ManagerId == param.Id).ToList();
            }

            List<QueryPermissionResponse> result = CreatePermissionList(permissions, "0", managerpPrmissions, showAll);

            return result;
        }

        /// <summary>
        /// 组装权限列表
        /// </summary>
        /// <param name="all">所有的权限列表</param>
        /// <param name="parentCode">父级权限编码</param>
        /// <returns>组装好的列表</returns>
        private List<QueryPermissionResponse> CreatePermissionList(List<Permission> all, string parentCode, List<ManagerToPermission> mlist, bool showAll=true)
        {
            var list = all.Where(c => c.Parentcode == parentCode);
            if (list == null || list.Count() <= 0)
                return null;
            List<QueryPermissionResponse> result = new List<QueryPermissionResponse>();
            foreach (var item in list)
            {
                QueryPermissionResponse mdl = ConvertToQueryPermission(item, mlist, showAll);
                if (mdl == null) continue;
                var child = all.Where(c => c.Parentcode == item.Permissioncode);
                if (child != null && child.Count() > 0)
                    mdl.Children = CreatePermissionList(all, item.Permissioncode, mlist, showAll);
                result.Add(mdl);
            }
            return result;
        }
  

        /// <summary>
        /// 实体转换返回数据对象
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        private QueryPermissionResponse ConvertToQueryPermission(Permission item, List<ManagerToPermission> mlist,bool showAll=true)
        {
            var one = mlist.FirstOrDefault(t => t.PermissionCode == item.Permissioncode);
            QueryPermissionResponse mp = new QueryPermissionResponse();
            if (one != null)
            {
                mp.AllowAdd = true;
                mp.AllowDel = true;
                mp.AllowEdit = true;
                mp.AllowView = true;
            }
            if (one == null && !showAll) return null;


            mp.Id = item.Id;
            mp.Permissioncode = item.Permissioncode;
            mp.Permissionlabel = item.Permissionlabel;
            mp.Permissionurl = item.Permissionurl;
            mp.Parentcode = item.Parentcode;

            mp.DeleteTag = item.DeleteTag;
            mp.CreatorId = item.CreatorId;
            mp.CreateTime = item.CreateTime;
            mp.UpdateTime = item.UpdateTime;
            mp.Sortorder = item.Sortorder;
            mp.Icon = item.Icon;
            mp.Iconactivate = item.Iconactivate;
            mp.Systemid = item.Systemid;
            mp.isnew = item.isnew;
            return mp;
        }
    }
}
