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;
namespace CloudBuilder.Security.Service
{
    public class SecurityGroupService : ISecurityGroupService
    {
        private readonly IApplicationService service;

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

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

            SecurityGroupEntity group = repository.DetachedEntities.Where(x => x.GroupName == key).FirstOrDefault();
            if (group == null) return data;

            data.SecurityGroup = group;


            IRepository<SecurityGroupPermissionViewEntity> repositoryGpv = repository.GetRepository<IRepository<SecurityGroupPermissionViewEntity>>();
            IRepository<SecurityGroupPermissionDependentViewEntity> repositoryGpdv = repository.GetRepository<IRepository<SecurityGroupPermissionDependentViewEntity>>();
            IRepository<SecurityActorGroupViewEntity> repositoryAgv = repository.GetRepository<IRepository<SecurityActorGroupViewEntity>>();

            SecurityGroupPermissionViewEntity[] sgps = repositoryGpv.DetachedEntities.Where(x => x.GroupName == key).ToArray();
            if (sgps != null && sgps.Length > 0)
                data.SecurityGroupPermissionViews = sgps.Select(x => new SecurityGroupPermissionViewDisplayData(x)).ToArray();

            SecurityGroupPermissionDependentViewEntity[] sgpds = repositoryGpdv.DetachedEntities.Where(x => x.GroupName == key).ToArray();
            if (sgpds != null && sgpds.Length > 0)
                data.SecurityGroupPermissionDependentViews = sgpds.Select(x => new SecurityGroupPermissionDependentViewDisplayData(x)).ToArray();


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

            return data;
        }

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


        [PermissionOperate(name: SecurityPermissionPolicy.SecurityGroup, operate: Operate.Find)]
        public SecurityGroupResultData FindBySearchCriteria(SecurityGroupSearchCriteria criteria)
        {
            SecurityGroupResultData data = new SecurityGroupResultData();
            SecurityGroupEntity[] list = null;

            int count = 0;

            string sqlWhere = null;

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

            SecurityGroupEntity entity = SecurityGroupEntity.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.SecurityGroup, operate: Operate.Print)]
        public dynamic PrintBySearchCriteria(SecurityGroupSearchCriteria criteria)
        {
            throw new NotImplementedException();
        }

        [PermissionOperate(name: SecurityPermissionPolicy.SecurityGroup, operate: Operate.Insert)]
        [UnitOfWork]
        public SecurityGroupData Insert(SecurityGroupData data)
        {
            SecurityGroupEntity securityGroup = repository.DetachedEntities.Where(x => x.GroupName == data.SecurityGroup.GroupName).FirstOrDefault();
            if (securityGroup != null)
            {
                throw new ValidatedException("记录已存在.");
            }

            ValidateHelper.Validate(service, data.SecurityGroup, SecurityGroupEntity.DB_NAME_SECURITY_GROUP);

            securityGroup = new SecurityGroupEntity();

            ObjectCopyHelper.Copy(data.SecurityGroup, securityGroup);

            repository.InsertNow(securityGroup);

            SaveSecurityGroupPermission(data);

            SaveSecurityActorGroup(data);

            return FindByKey(data.SecurityGroup.GroupName);
        }

        private void SaveSecurityGroupPermission(SecurityGroupData data)
        {
            IRepository<SecurityGroupPermissionEntity> repositoryGp = repository.GetRepository<IRepository<SecurityGroupPermissionEntity>>();

            SecurityGroupPermissionEntity[] olds = repositoryGp.Entities.Where(x => x.GroupName == data.SecurityGroup.GroupName).ToArray();
            if (olds != null && olds.Length > 0)
            {
                foreach (SecurityGroupPermissionEntity old in olds)
                {
                    repositoryGp.DeleteNow(old);
                }
            }

            if (data.SecurityGroupPermissionViews != null && data.SecurityGroupPermissionViews.Length > 0)
                foreach (SecurityGroupPermissionViewDisplayData dto in data.SecurityGroupPermissionViews)
                {
                    repositoryGp.InsertNow(new SecurityGroupPermissionEntity()
                    {
                        GroupName = data.SecurityGroup.GroupName,
                        PermissionName = dto.PermissionName,
                        Dependent = dto.Dependent,
                        ViewIndc = dto.IsView ? YesNoPolicy.YES : YesNoPolicy.NO,
                        AmendIndc = dto.IsAmend ? YesNoPolicy.YES : YesNoPolicy.NO,
                        DeleteIndc = dto.IsDelete ? YesNoPolicy.YES : YesNoPolicy.NO,
                        CreateIndc = dto.IsCreate ? YesNoPolicy.YES : YesNoPolicy.NO,
                    });
                }
            IRepository<SecurityGroupPermissionDependentEntity> repositoryGpd = repository.GetRepository<IRepository<SecurityGroupPermissionDependentEntity>>();

            SecurityGroupPermissionDependentEntity[] oldds = repositoryGpd.Entities.Where(x => x.GroupName == data.SecurityGroup.GroupName).ToArray();
            if (oldds != null && oldds.Length > 0)
            {
                foreach (SecurityGroupPermissionDependentEntity old in oldds)
                {
                    repositoryGpd.DeleteNow(old);
                }
            }

            if (data.SecurityGroupPermissionDependentViews != null && data.SecurityGroupPermissionDependentViews.Length > 0)
                foreach (SecurityGroupPermissionDependentViewDisplayData dto in data.SecurityGroupPermissionDependentViews)
                {
                    repositoryGpd.InsertNow(new SecurityGroupPermissionDependentEntity()
                    {
                        GroupName = data.SecurityGroup.GroupName,
                        PermissionName = dto.PermissionName,
                        DependentDetailName = dto.DependentDetailName,
                        ViewIndc = dto.IsView ? YesNoPolicy.YES : YesNoPolicy.NO,
                        AmendIndc = dto.IsAmend ? YesNoPolicy.YES : YesNoPolicy.NO,
                        DeleteIndc = dto.IsDelete ? YesNoPolicy.YES : YesNoPolicy.NO,
                        CreateIndc = dto.IsCreate ? YesNoPolicy.YES : YesNoPolicy.NO,
                    });
                }
        }

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

            SecurityActorGroupEntity[] olds = repositoryAg.Entities.Where(x => x.GroupName == data.SecurityGroup.GroupName).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()
                    {
                        GroupName = data.SecurityGroup.GroupName,
                        ActorName = dto.ActorName,
                    });
                }

        }


        [PermissionOperate(name: SecurityPermissionPolicy.SecurityGroup, operate: Operate.Update)]
        [UnitOfWork]
        public SecurityGroupData Update(SecurityGroupData data)
        {
            SecurityGroupEntity securityGroup = repository.DetachedEntities.Where(x => x.GroupName == data.SecurityGroup.GroupName).FirstOrDefault();
            if (securityGroup == null)
            {
                throw new ValidatedException("记录不存在.");
            }

            ValidateHelper.Validate(service, data.SecurityGroup, SecurityGroupEntity.DB_NAME_SECURITY_GROUP);

            ObjectCopyHelper.Copy(data.SecurityGroup, securityGroup);

            repository.UpdateNow(securityGroup);

            SaveSecurityGroupPermission(data);

            SaveSecurityActorGroup(data);

            return FindByKey(data.SecurityGroup.GroupName);
        }


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

            repository.DeleteNow(securityGroup);

            IRepository<SecurityGroupPermissionEntity> repositoryGp = repository.GetRepository<IRepository<SecurityGroupPermissionEntity>>();
            IRepository<SecurityGroupPermissionDependentEntity> repositoryGpd = repository.GetRepository<IRepository<SecurityGroupPermissionDependentEntity>>();

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

            SecurityGroupPermissionDependentEntity[] oldds = repositoryGpd.Entities.Where(x => x.PermissionName == key).ToArray();
            if (oldds != null && oldds.Length > 0)
            {
                foreach (SecurityGroupPermissionDependentEntity old in oldds)
                {
                    repositoryGpd.DeleteNow(old);
                }
            }

            IRepository<SecurityActorGroupEntity> repositoryAg = repository.GetRepository<IRepository<SecurityActorGroupEntity>>();
            SecurityActorGroupEntity[] oldAgs = repositoryAg.Entities.Where(x => x.GroupName == key).ToArray();
            if (oldAgs != null && oldAgs.Length > 0)
            {
                foreach (SecurityActorGroupEntity old in oldAgs)
                {
                    repositoryAg.DeleteNow(old);
                }
            }
        }

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