using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ewide.Core.Service.Role
{
    public class SysRoleAreaService : ISysRoleAreaService,ITransient
    {
        public readonly IRepository<SysRoleArea> _sysRoleAreaRep;

        public SysRoleAreaService(IRepository<SysRoleArea> sysRolleAreaRep)
        {
            _sysRoleAreaRep = sysRolleAreaRep;
        }

        public  async Task DeleteRoleAreaListByAreaCodeList(List<string> areaCodeList)
        {
            var dataScopes = await _sysRoleAreaRep.DetachedEntities.Where(u => areaCodeList.Contains(u.AreaCode)).ToListAsync();
            dataScopes.ForEach(u =>
            {
                u.Delete();
            });
        }

        public  async Task DeleteRoleAreaListByRoleId(string roleId)
        {
            var dataScopes = await _sysRoleAreaRep.DetachedEntities.Where(u => roleId==u.SysRoleId).ToListAsync();
            dataScopes.ForEach(u =>
            {
                u.Delete();
            });
        }

        public async Task<List<string>> GetRoleAreaCodeList(List<string> roleIdList)
        {
            return await _sysRoleAreaRep.DetachedEntities.Where(u => roleIdList.Contains(u.SysRoleId)).Select(u=>u.AreaCode).Distinct().ToListAsync();
            
        }

        public async Task GrantArea(GrantAreaDataInput input)
        {
            var dataScopes = await _sysRoleAreaRep.Where(u => u.SysRoleId == input.Id).ToListAsync();
            dataScopes.ForEach(u =>
            {
                u.Delete();
            });

            input.GrantAreaCodeList.ForEach(u =>
            {
                new SysRoleArea
                {
                    SysRoleId = input.Id,
                    AreaCode = u
                }.Insert();
            });
        }
    }
}
