using Hncore.Infrastructure.EF;
using Hncore.Infrastructure.Extension;
using Hncore.Infrastructure.WebApi;
using Hncore.Pass.Manage.Domain;
using Hncore.Pass.Manage.Repository;
using Hncore.Pass.Manage.Request;
using Hncore.Pass.Manage.Response;
using Hncore.Pass.Manage.Response.ManagerToPermission;
using Hncore.Pass.Manage.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Hncore.Pass.Manage.Controllers
{

    public class ManagerController : ManageControllerBase
    {
        EfDbContext m_DbContext { get; set; }

        private  ManagerService  _managerService;


        public ManagerController(EfDbContext _DbContext, ManagerService managerService, IHttpContextAccessor hca) : base(hca)
        {
            m_DbContext = _DbContext;
            _managerService = managerService;
        }

        /// <summary>
        /// 创建管理员添加权限
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> Post([FromBody] EditManagerRequest param)
        {
            param.TenantId = this.Request.GetManageUserInfo().TenantId;
            var manager = await Manager.Create(param, m_DbContext.Set<Manager>().GetQueryable());
            await m_DbContext.Set<Manager>().AddAsync(manager);
            await m_DbContext.SaveChangesAsync();
            List<ManagerToPermission> list = new List<ManagerToPermission>();
            foreach (var item in param.Permissions)
            {
                if (item.AllowView == 1)
                {
                    ManagerToPermission mp = new ManagerToPermission();
                    mp.TenantId = param.TenantId;
                    mp.ManagerId = manager.Id;
                    mp.PermissionCode = item.PermissionCode;
                    mp.AllowView = item.AllowView;
                    mp.AllowAdd = item.AllowAdd;
                    mp.AllowEdit = item.AllowEdit;
                    mp.AllowDel = item.AllowDel;
                    mp.CreateTime = DateTime.Now;
                    mp.UpdateTime = DateTime.Now;
                    mp.CreatorId = param.OperaterId;
                    list.Add(mp);
                }
            }
            await m_DbContext.Set<ManagerToPermission>().AddRangeAsync(list);
            await m_DbContext.SaveChangesAsync();
            return Success(new EditManagerResponse().FromEntity(manager));
        }

  
        [HttpPost]
        public async Task<ApiResult> Put([FromBody] EditManagerRequest param)
        {
            param.TenantId = this.Request.GetManageUserInfo().TenantId;
            var manager = await m_DbContext.Set<Manager>().FindByIdAsync(param.Id);
            await manager.Edit(param, m_DbContext.Set<Manager>().GetQueryable());          
            
            List<ManagerToPermission> list = new List<ManagerToPermission>();
            List<ManagerToPermission> listdel   = new List<ManagerToPermission>();
            foreach (var item in param.Permissions)
            {
                if (item.AllowView == 1)
                {
                    ManagerToPermission mp = new ManagerToPermission();
                    mp.TenantId = param.TenantId;
                    mp.ManagerId = manager.Id;
                    mp.PermissionCode = item.PermissionCode;
                    mp.AllowView = item.AllowView;
                    mp.AllowAdd = item.AllowAdd;
                    mp.AllowEdit = item.AllowEdit;
                    mp.AllowDel = item.AllowDel;
                    mp.CreateTime = DateTime.Now;
                    mp.UpdateTime = DateTime.Now;
                    mp.CreatorId = param.OperaterId;
                    list.Add(mp);
                }
            }
            var search = m_DbContext.Set<ManagerToPermission>().GetQueryable().Where(p => p.DeleteTag == 0 && p.ManagerId == param.Id);
            foreach (var item in search)
            {
                listdel.Add(item);
            }
            m_DbContext.Set<ManagerToPermission>().RemoveRange(listdel);       
            await m_DbContext.Set<ManagerToPermission>().AddRangeAsync(list);     
            await m_DbContext.SaveChangesAsync();
            return Success(new EditManagerResponse().FromEntity(manager));
        }

        /// <summary>
        /// 删除管理员
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]

        public async Task<ApiResult> Delete([FromBody] DelManagerRequest  param)
        {
            var manager = await m_DbContext.Set<Manager>().FindByIdAsync(param.Id);
            manager.Delete(param.OperaterId);
            await m_DbContext.SaveChangesAsync();
            return Success(manager);
        }


        /// <summary>
        /// 获取单个管理员
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpGet]
        
        public async Task<ApiResult> GetOne([FromQuery] QueryByIdRequest param)
        {
            return Success(await QueryItemManagerResponse.Query(
                 m_DbContext.Set<Manager>().GetQueryable()
                , m_DbContext.Set<ManagerToPermission>().GetQueryable()
                , m_DbContext.Set<AuthorityManagerDataDomain>().GetQueryable()
                , param)
            );
        }

        /// <summary>
        /// 获取单个管理员,门禁调用 
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpGet,AllowAnonymous]

        public async Task<ApiResult> GetOneManage([FromQuery] QueryByIdRequest param)
        {
            return Success(await m_DbContext.Set<Manager>().GetOneAsync(p=>p.Id==param.Id));
        }



        /// <summary>
        /// 获取列表数据
        /// </summary>
        /// <param name="request">请求参数对象</param>
        /// <returns>响应结果对象</returns>
        [HttpGet]
        public async Task<ApiResult<List<QueryListManagerResponse>>> Get([FromQuery]QueryListManagerRequest request)
        {
            request.TenantId = this.Request.GetManageUserInfo().TenantId;
            request.OperaterId = this.Request.GetManageUserInfo().OperaterId;
            (int total, List<QueryListManagerResponse> list) res = await _managerService.Get(request);
            return SuccessPaged(res.total, res.list, "成功");
        }
        /// <summary>
        /// 超级管理员移交管理员权限
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost,AllowAnonymous]         
        public async Task<ApiResult> TransferPrivilege([FromBody] RequestBase<TransferPrivilegeDTO> param)
        {
            #region 需要后台判断短信验证码防非法操作
            if (!param.Data.Key.Has() || !param.Data.Code.Has()) return Error("短信验证码错误");
            var tmp = RedisHelper.Get<SmsValidDTO>(param.Data.Key);
            if (tmp==null) return Error("短信验证码过期");
            if (!string.Equals(tmp.Code, param.Data.Code)) return Error("短信验证码错误");
            #endregion

            //管理员表操作
            var manager = await m_DbContext.Set<Manager>().FindByIdAsync(param.OperaterId);
            manager.IsRoot = false;
            manager.DeleteTag = 1;
            m_DbContext.Set<Manager>().Update(manager);
            

            var managernew = await m_DbContext.Set<Manager>().FindByIdAsync(param.Data.Id);
            managernew.IsRoot = true;
            m_DbContext.Set<Manager>().Update(managernew);

          

            ///管理员权限表操作
            var search = m_DbContext.Set<ManagerToPermission>().GetQueryable().Where(p => p.DeleteTag == 0 && p.ManagerId == param.OperaterId);
            foreach (var item in search)
            {
                ManagerToPermission mp = new ManagerToPermission();
                mp.TenantId = param.TenantId;
                mp.ManagerId = param.Data.Id;
                mp.PermissionCode = item.PermissionCode;
                mp.AllowView = item.AllowView;
                mp.AllowAdd = item.AllowAdd;
                mp.AllowEdit = item.AllowEdit;
                mp.AllowDel = item.AllowDel;
                mp.CreateTime = DateTime.Now;
                mp.UpdateTime = DateTime.Now;
                mp.CreatorId = param.OperaterId;
                m_DbContext.Set<ManagerToPermission>().Add(mp);
            }
            var del  = m_DbContext.Set<ManagerToPermission>().GetQueryable().Where(p => p.DeleteTag == 0 && p.ManagerId == param.Data.Id).ToList();
            m_DbContext.Set<ManagerToPermission>().RemoveRange(del);
          

         
            //被转移人项目
            var recipientProject = m_DbContext.Set<AuthorityManagerDataDomain>().GetQueryable().Where(p => p.DeleteTag == 0 && p.ManagerId == param.Data.Id);
            //我的项目
            var myProject = m_DbContext.Set<AuthorityManagerDataDomain>().GetQueryable().Where(p => p.DeleteTag == 0 && p.ManagerId == param.OperaterId);
            foreach (var item in recipientProject)
            {
                item.DeleteTag = 1;
                m_DbContext.Set<AuthorityManagerDataDomain>().Update(item);
            }
            foreach (var item in myProject)
            {
                item.DeleteTag = 1;
                m_DbContext.Set<AuthorityManagerDataDomain>().Update(item);
            }

            //物业总项目
            var ownerProject = m_DbContext.Set<etor_property_estate>().GetQueryable().Where(p => p.DeleteTag == 0 && p.owner_id == param.TenantId);
            foreach (var item in ownerProject)
            {
                AuthorityManagerDataDomain mp = new AuthorityManagerDataDomain();
                mp.TenantId = item.owner_id;
                mp.ProjectCode = item.projectcode;
                mp.DeleteTag = 0;
                mp.ManagerId = param.Data.Id;
                mp.UpdateTime = DateTime.Now;
                mp.UpdatorId = param.OperaterId;
                m_DbContext.Set<AuthorityManagerDataDomain>().Add(mp);
            }

            var mymanager = await m_DbContext.Set<Manager>().FindByIdAsync(param.OperaterId);
            mymanager.IsRoot = false;
            manager.DeleteTag = 1;
            m_DbContext.Set<Manager>().Update(mymanager);

           await m_DbContext.SaveChangesAsync();

            return Success(param.Data.Id);
        }

        /// <summary>
        /// 根据管理员获取管理员小区权限
        /// </summary>
        /// <param name="managerId"></param>
        /// <returns></returns>
        [HttpGet,AllowAnonymous]
        public async Task<ApiResult> GetByManageId([FromQuery] int ManagerId)
        {
            var result = await QueryPermissionByManagerIdResponse.GetByManageId(m_DbContext.Set<AuthorityManagerDataDomain>().GetQueryable(), m_DbContext.Set<etor_property_estate>().GetQueryable(), m_DbContext.Set<Manager>().GetQueryable(), ManagerId);
            return  Success(result);
        }

        /// <summary>
        /// 根据当前登录人，查询本物业下边超级管理员手机号
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> GetAdminPhoneByManageId([FromQuery] QueryByIdRequest param)
        { 
            var result = m_DbContext.Set<Manager>().GetQueryable().Where(p => p.IsRoot == true).ToList();

            if (result != null && result.Count() > 0) return  Success<string>(result[0].Phone);
            return Success<string>("");
        }
    }
}