using Ewide.Core.Service.Role;
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.User
{
    public class SysUserAreaService : ISysUserAreaService,ITransient
    {
        public readonly IRepository<SysUserArea> _sysUserAreaRep;

        public SysUserAreaService(IRepository<SysUserArea> sysUserAreaRep)
        {
            _sysUserAreaRep = sysUserAreaRep;
        }

        public async Task DeleteUserAreaListByAreaCodeList(List<string> areaCodeList)
        {
            var areaList = await _sysUserAreaRep.DetachedEntities.Where(ua => areaCodeList.Contains(ua.AreaCode)).ToListAsync();
            foreach (var area in areaList)
            {
                area.Delete();
            }
        }

        public async Task DeleteUserAreaListByUserId(string userId)
        {
            var areaList = await _sysUserAreaRep.DetachedEntities.Where(ua => ua.SysUserId == userId).ToListAsync();
            foreach (var area in areaList)
            {
                area.Delete();
            }
        }

        public async Task<List<string>> GetUserAreaIdList(string userId)
        {
            return await _sysUserAreaRep.DetachedEntities.Where(ua => ua.SysUserId == userId).Select(ua => ua.AreaCode).ToListAsync();
        }

        public async Task GrantData(UpdateUserInput input)
        {
            var dataScopes = await _sysUserAreaRep.Where(u => u.SysUserId == input.Id).ToListAsync();
            dataScopes.ForEach(u =>
            {
                u.Delete();
            });
            var dbset = _sysUserAreaRep.Entities;
            await _sysUserAreaRep.InsertAsync(input.GrantAreaCodeList.Select(u => new SysUserArea
            {
                SysUserId = input.Id,
                AreaCode = u
            }));
        }
    }
}
