using System;
using System.Collections.Generic;
using Infrastructure;
using OpenAuth.App.Base;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.Interface;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using SqlSugar;

namespace OpenAuth.App
{
    /// <summary>
    /// 分类管理
    /// </summary>
    public class ResourceApp : SqlSugarBaseApp<SysResource, SugarDbContext>
    {
        private RevelanceManagerApp _revelanceApp;

        public ResourceApp(
            ISugarUnitOfWork<SugarDbContext> unitWork,
            ISimpleClient<SysResource> repository,
            RevelanceManagerApp app,
            IAuth auth) : base(unitWork, repository, auth)
        {
            _revelanceApp = app;
        }
        public void Add(AddOrUpdateResReq resource)
        {
            var obj = resource.MapTo<SysResource>();
            //先注释，后边再看具体原因
            //CaculateCascade(obj);
            obj.CreateTime = DateTime.Now;
            var user = _auth.GetCurrentUser().User;
            obj.CreateUserId = user.Id;
            obj.CreateUserName = user.Name;
            obj.Id = Guid.NewGuid().ToString();
            Repository.Insert(obj);
        }

        public void Update(AddOrUpdateResReq obj)
        {
            var user = _auth.GetCurrentUser().User;
            base.Repository.Update(u => new SysResource
            {
                Name = obj.Name,
                Disable = obj.Disable,
                CascadeId = obj.CascadeId,
                AppId = obj.AppId,
                AppName = obj.AppName,
                ParentId = obj.ParentId,
                ParentName = obj.ParentName,
                TypeId = obj.TypeId,
                TypeName = obj.TypeName,
                Description = obj.Description,
                UpdateTime = DateTime.Now,
                UpdateUserId = user.Id,
                UpdateUserName = user.Name
                //todo:要修改的字段赋值
            }, u => u.Id == obj.Id);
        }

        public IEnumerable<SysResource> LoadForRole(string appId, string roleId)
        {
            var elementIds = _revelanceApp.Get(Define.ROLERESOURCE, true, roleId);
            return base.Repository.GetList(u => elementIds.Contains(u.Id) && (appId == null || appId == "" || u.AppId == appId));
        }

        public void Delete(string[] ids)
        {
            Repository.DeleteByIds(ids);
        }
    }
}