using CloudBuilder.Core.DatabaseAccessor;
using CloudBuilder.Core.DatabaseAccessor.Entity;
using CloudBuilder.Core.Extensions;
using CloudBuilder.Core.Service;
using CloudBuilder.Security.Data;
using CloudBuilder.Security.Entity;
using CloudBuilder.Security.Policy;
using CloudBuilder.Security.SearchCriteria;
using CloudBuilder.Security.Utility;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Permissions;
namespace CloudBuilder.Security.Service
{
    public class SecurityActorService : ISecurityActorService
    {
        private readonly IApplicationService service;

        private IRepository<SecurityActorEntity> repository;
        public SecurityActorService(IApplicationService service)
        {
            this.service = service;
            repository = service.GetRepository<IRepository<SecurityActorEntity>>();
        }


        [PermissionOperate(name: SecurityPermissionPolicy.SecurityActor, operate: Operate.Find)]
        public SecurityActorData FindByKey(string key)
        {
            SecurityActorData data = new SecurityActorData();
            if (string.IsNullOrEmpty(key)) return data;

            SecurityActorEntity actor = repository.DetachedEntities.Where(x => x.ActorName == key).FirstOrDefault();

            if (actor == null) return data;

            data.SecurityActor = actor;

            IRepository<SecurityActorGroupViewEntity> repositoryAgv = repository.GetRepository<IRepository<SecurityActorGroupViewEntity>>();
            IRepository<SecurityUserActorViewEntity> repositoryUav = repository.GetRepository<IRepository<SecurityUserActorViewEntity>>();

            data.SecurityActorGroups = repositoryAgv.DetachedEntities.Where(x => x.ActorName == key).ToArray();

            data.SecurityUserActors = repositoryUav.DetachedEntities.Where(x => x.ActorName == key).ToArray();

            return data;
        }

        [PermissionOperate(name: SecurityPermissionPolicy.SecurityActor, operate: Operate.Find)]
        public SecurityActorEntity[] FindAll()
        {
            return repository.DetachedEntities.ToArray();
        }

        [AllowAnonymous]
        [HttpPost]
        public SecurityActorEntity[] FindAllByNoPermission()
        {
            return repository.DetachedEntities.ToArray();
        }

        [PermissionOperate(name: SecurityPermissionPolicy.SecurityActor, operate: Operate.Find)]
        public SecurityActorResultData FindBySearchCriteria(SecurityActorSearchCriteria criteria)
        {
            SecurityActorResultData data = new SecurityActorResultData();
            SecurityActorEntity[] list = null;

            int count = 0;

            string sqlWhere = null;

            if (criteria.Filter != null && criteria.Filter.Length > 0)
            {
                sqlWhere = SearchFilter.ComposeWhereClause(criteria.Filter);
            }

            SecurityActorEntity entity = SecurityActorEntity.GetInstance();
            string sql = entity.GetSelectTopFrom(criteria.limit, criteria.page,  criteria.orderby.StringToDbField(), criteria.orderbytag, sqlWhere);

            string err = null;
            try
            {
                list = repository.FromSql(sql).ToArray();
            }
            catch (System.Exception ex)
            {
                err = ex.Message;
            }


            if (list != null && list.Length > 0)
            {
                sql = entity.GetSelectCountFrom(sqlWhere);
                count = (int)repository.ExecuteScalar(sql);
            }

            data.Limit = criteria.limit;
            data.Page = criteria.page;
            data.Datas = list;
            data.Total = count;
            //data.Sql = sql;
            data.ErrorMessage = err;
            return data;
        }

        [PermissionOperate(name: SecurityPermissionPolicy.SecurityActor, operate: Operate.Print)]
        public dynamic PrintBySearchCriteria(SecurityActorSearchCriteria criteria)
        {
            throw new NotImplementedException();
        }

        [PermissionOperate(name: SecurityPermissionPolicy.SecurityActor, operate: Operate.Insert)]
        [UnitOfWork]
        public SecurityActorData Insert(SecurityActorData data)
        {
            SecurityActorEntity securityActor = repository.DetachedEntities.Where(x => x.ActorName == data.SecurityActor.ActorName).FirstOrDefault();
            if (securityActor != null)
            {
                throw new ValidatedException("记录已存在.");
            }

            ValidateHelper.Validate(service, data.SecurityActor, SecurityActorEntity.DB_NAME_SECURITY_ACTOR);

            securityActor = new SecurityActorEntity();

            ObjectCopyHelper.Copy(data.SecurityActor, securityActor);

            repository.InsertNow(securityActor);

            SaveSecurityActorGroup(data);

            SaveSecurityUserActor(data);

            return FindByKey(data.SecurityActor.ActorName);
        }

        [PermissionOperate(name: SecurityPermissionPolicy.SecurityActor, operate: Operate.Update)]
        [UnitOfWork]
        public SecurityActorData Update(SecurityActorData data)
        {
            SecurityActorEntity securityActor = repository.DetachedEntities.Where(x => x.ActorName == data.SecurityActor.ActorName).FirstOrDefault();
            if (securityActor == null)
            {
                throw new ValidatedException("记录不存在.");
            }

            ValidateHelper.Validate(service, data.SecurityActor, SecurityActorEntity.DB_NAME_SECURITY_ACTOR);

            ObjectCopyHelper.Copy(data.SecurityActor, securityActor);

            repository.UpdateNow(securityActor);

            SaveSecurityActorGroup(data);

            SaveSecurityUserActor(data);

            return FindByKey(data.SecurityActor.ActorName);
        }

        private void SaveSecurityUserActor(SecurityActorData data)
        {
            IRepository<SecurityUserActorEntity> repositoryUa = repository.GetRepository<IRepository<SecurityUserActorEntity>>();

            SecurityUserActorEntity[] olds = repositoryUa.Entities.Where(x => x.ActorName == data.SecurityActor.ActorName).ToArray();
            if (olds != null && olds.Length > 0)
            {
                foreach (SecurityUserActorEntity old in olds)
                {
                    repositoryUa.DeleteNow(old);
                }
            }

            if (data.SecurityUserActors != null && data.SecurityUserActors.Length > 0)
                foreach (SecurityUserActorViewEntity dto in data.SecurityUserActors)
                {
                    repositoryUa.InsertNow(new SecurityUserActorEntity()
                    {
                        UserName = dto.UserName,
                        ActorName = data.SecurityActor.ActorName,
                    });
                }

        }

        private void SaveSecurityActorGroup(SecurityActorData data)
        {
            IRepository<SecurityActorGroupEntity> repositoryAg = repository.GetRepository<IRepository<SecurityActorGroupEntity>>();

            SecurityActorGroupEntity[] olds = repositoryAg.Entities.Where(x => x.ActorName == data.SecurityActor.ActorName).ToArray();
            if (olds != null && olds.Length > 0)
            {
                foreach (SecurityActorGroupEntity old in olds)
                {
                    repositoryAg.DeleteNow(old);
                }
            }

            if (data.SecurityActorGroups != null && data.SecurityActorGroups.Length > 0)
                foreach (SecurityActorGroupViewEntity dto in data.SecurityActorGroups)
                {
                    repositoryAg.InsertNow(new SecurityActorGroupEntity()
                    {
                        ActorName = data.SecurityActor.ActorName,
                        GroupName = dto.GroupName,
                    });
                }

        }


        [PermissionOperate(name: SecurityPermissionPolicy.SecurityActor, operate: Operate.Delete)]
        [UnitOfWork]
        public void Delete(string key)
        {
            SecurityActorEntity securityActor = repository.DetachedEntities.Where(x => x.ActorName == key).FirstOrDefault();
            if (securityActor == null)
            {
                throw new ValidatedException("记录不存在.");
            }

            repository.DeleteNow(securityActor);

            IRepository<SecurityActorGroupEntity> repositoryAg = repository.GetRepository<IRepository<SecurityActorGroupEntity>>();

            SecurityActorGroupEntity[] olds = repositoryAg.Entities.Where(x => x.ActorName == key).ToArray();
            if (olds != null && olds.Length > 0)
            {
                foreach (SecurityActorGroupEntity old in olds)
                {
                    repositoryAg.DeleteNow(old);
                }
            }
        }

        [PermissionOperate(name: SecurityPermissionPolicy.SecurityActor, operate: Operate.Delete)]
        [UnitOfWork]
        public void Deletes(string[] keys)
        {
            foreach (string key in keys)
            {
                Delete(key);
            }
        }
    }
}
