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

namespace Hncore.Pass.Manage.Controllers
{
    [ApiVersion("1.0")]
    [Route("api/Manage/v{version:apiVersion}/ManageDataDomain/[action]")]
    public class ManageDataDomainController : HncoreControllerBase
    {
        EfDbContext m_DbContext { get; set; }

        public ManageDataDomainController(EfDbContext _DbContext)
        {
            m_DbContext = _DbContext;
        }

        /// <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> Get([FromQuery]int id)
        {
            var projectcodes =await m_DbContext.Set<AuthorityManagerDataDomain>().Where(p => p.ManagerId == id && p.DeleteTag == 0).Select(s => s.ProjectCode).ToArrayAsync();
            var ret = new
            {
                Projectcodes = projectcodes,
                Managerid = id
            };            
            return Success(ret);
        }

        /// <summary>
        /// 绑定项目
        /// </summary>
        /// <param name="request">请求参数对象</param>
        /// <returns>响应结果对象</returns>
        [HttpPost]
        public async Task<ApiResult> BindDataDomain([FromBody]RequestBase<BindDataDomainRequest> request)
        {
            var requestCodes = request.Data.Projectcodes;
            //获取当前管理员关联的小区编码
            var currentProjects = await m_DbContext.Set<AuthorityManagerDataDomain>().Where(p => p.TenantId == request.TenantId && p.DeleteTag == 0 && p.ManagerId == request.Data.Managerid).ToListAsync();

            //添加目前未关联的小区编码
            var addList = new List<AuthorityManagerDataDomain>();
            var currentCodes = currentProjects.Select(s => s.ProjectCode).ToArray();
            foreach (var projectCode in requestCodes.Where(code => !currentCodes.Contains(code)))
            {
                addList.Add(new AuthorityManagerDataDomain()
                {
                    ProjectCode = projectCode,
                    CreatorId = request.OperaterId,
                    TenantId = request.TenantId,
                    ManagerId = request.Data.Managerid,
                    UpdatorId = request.OperaterId,
                });
            }
            await m_DbContext.Set<AuthorityManagerDataDomain>().AddRangeAsync(addList);

            //移除将来未关联的小区编码
            var removeList = new List<AuthorityManagerDataDomain>();
            var removeCodes = currentCodes.Where(code => !requestCodes.Contains(code)).ToArray();
            foreach (var managerDataDomain in currentProjects.Where(m => removeCodes.Contains(m.ProjectCode)))
            {
                managerDataDomain.UpdatorId = request.OperaterId;
                managerDataDomain.DeleteTag = 1;
                removeList.Add(managerDataDomain);
            }
            m_DbContext.Set<AuthorityManagerDataDomain>().UpdateRange(removeList);

            //提交
            await m_DbContext.SaveChangesAsync();
            return Success(request.Data);
        }
    }
}