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 Microsoft.Extensions.DependencyInjection;
namespace CloudBuilder.Security.Service
{
    public class SecurityPermissionService : ISecurityPermissionService
    {
        private readonly IApplicationService service;

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

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

            SecurityPermissionEntity permission = repository.DetachedEntities.Where(x => x.PermissionName == key).FirstOrDefault();

            if (permission == null) return data;

            data.SecurityPermission = permission;

            IRepository<SecurityPermissionDependentEntity> repositoryDependent = repository.GetRepository<IRepository<SecurityPermissionDependentEntity>>();

            SecurityPermissionDependentEntity[] dpts = repositoryDependent.DetachedEntities.Where(x => x.PermissionName == key).ToArray();
            if (dpts != null && dpts.Length > 0)
            {
                data.SecurityPermissionDependents = dpts;
            }

            return data;
        }

        [PermissionOperate(name: SecurityPermissionPolicy.SecurityPermission, operate: Operate.Find)]
        public SecurityPermissionResultData FindBySearchCriteria(SecurityPermissionSearchCriteria criteria)
        {
            SecurityPermissionResultData data = new SecurityPermissionResultData();
            SecurityPermissionEntity[] list = null;

            int count = 0;

            string sqlWhere = null;

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

            SecurityPermissionEntity entity = SecurityPermissionEntity.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.Permissions = list;
            data.Total = count;
            //data.Sql = sql;
            data.ErrorMessage = err;
            return data;
        }

        [PermissionOperate(name: SecurityPermissionPolicy.SecurityPermission, operate: Operate.Find)]
        public SecurityPermissionResultData FindDependentBySearchCriteria(SecurityPermissionSearchCriteria criteria)
        {
            SecurityPermissionResultData data = new SecurityPermissionResultData();
            SecurityPermissionDependentEntity[] list = null;
            IRepository<SecurityPermissionDependentEntity> repositoryDependent = service.GetRepository<IRepository<SecurityPermissionDependentEntity>>();
            int count = 0;

            string sqlWhere = null;

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

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

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


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

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


        [PermissionOperate(name: SecurityPermissionPolicy.SecurityPermission, operate: Operate.Find)]
        public SecurityPermissionResultData FindDependentsBySearchCriteria(SecurityPermissionSearchCriteria criteria)
        {
            SecurityPermissionResultData data = new SecurityPermissionResultData();
            SecurityPermissionDependentEntity[] list = null;

            int count = 0;

            string sqlWhere = null;

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

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

            IRepository<SecurityPermissionDependentEntity> repositoryDependent = repository.GetRepository<IRepository<SecurityPermissionDependentEntity>>();


            string err = null;
            try
            {
                list = repositoryDependent.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.Dependents = list;
            data.Total = count;
            //data.Sql = sql;
            data.ErrorMessage = err;
            return data;
        }

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

        [PermissionOperate(name: SecurityPermissionPolicy.SecurityPermission, operate: Operate.Insert)]
        [UnitOfWork]
        public SecurityPermissionData Insert(SecurityPermissionData data)
        {
            SecurityPermissionEntity securityPermission = repository.DetachedEntities.Where(x => x.PermissionName == data.SecurityPermission.PermissionName).FirstOrDefault();
            if (securityPermission != null)
            {
                throw new ValidatedException("记录已存在.");
            }

            ValidateHelper.Validate(service, data.SecurityPermission, SecurityPermissionEntity.DB_NAME_SECURITY_PERMISSION);

            securityPermission = new SecurityPermissionEntity();
            ObjectCopyHelper.Copy(data.SecurityPermission, securityPermission);

            repository.InsertNow(securityPermission);

            SaveSecurityPermissionDependents(securityPermission.PermissionName, securityPermission.Dependent, data.SecurityPermissionDependents);

            return FindByKey(data.SecurityPermission.PermissionName);
        }

        [PermissionOperate(name: SecurityPermissionPolicy.SecurityPermission, operate: Operate.Update)]
        [UnitOfWork]
        public SecurityPermissionData Update(SecurityPermissionData data)
        {
            SecurityPermissionEntity securityPermission = repository.DetachedEntities.Where(x => x.PermissionName == data.SecurityPermission.PermissionName).FirstOrDefault();
            if (securityPermission == null)
            {
                throw new ValidatedException("记录不存在.");
            }

            ValidateHelper.Validate(service, data.SecurityPermission, SecurityPermissionEntity.DB_NAME_SECURITY_PERMISSION);

            ObjectCopyHelper.Copy(data.SecurityPermission, securityPermission);

            repository.UpdateNow(securityPermission);

            SaveSecurityPermissionDependents(securityPermission.PermissionName, securityPermission.Dependent, data.SecurityPermissionDependents);

            return FindByKey(data.SecurityPermission.PermissionName);
        }


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

            repository.DeleteNow(SecurityPermission);


            IRepository<SecurityPermissionDependentEntity> repositoryDependent = repository.GetRepository<IRepository<SecurityPermissionDependentEntity>>();

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

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

        private void SaveSecurityPermissionDependents(string permissionName, string dependent, SecurityPermissionDependentEntity[] dependents)
        {
            IRepository<SecurityPermissionDependentEntity> repositoryDependent = repository.GetRepository<IRepository<SecurityPermissionDependentEntity>>();

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

            if (dependents == null || dependents.Length == 0) return;

            foreach (SecurityPermissionDependentEntity dto in dependents)
            {
                ValidateHelper.Validate(service, dto, SecurityPermissionDependentEntity.DB_NAME_SECURITY_PERMISSION_DEPENDENT);

                repositoryDependent.InsertNow(new SecurityPermissionDependentEntity()
                {
                    PermissionName = permissionName,
                    Dependent = dependent,
                    DependentDetailName = dto.DependentDetailName,
                    DependentDetailDescription = dto.DependentDetailDescription
                });
            }

        }
    }
}
