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

namespace Ewide.Core.Service
{
    /// <summary>
    /// 用户数据范围服务
    /// </summary>
    public class SysUserDataScopeService : ISysUserDataScopeService, ITransient
    {
        private readonly IRepository<SysUserDataScope> _sysUserDataScopeRep;  // 用户数据范围表仓储 
        private readonly IRepository<SysUserArea> _sysUserAreaRep;
        private readonly IRepository<SysOrg> _sysOrgRep;
        public SysUserDataScopeService(IRepository<SysUserDataScope> sysUserDataScopeRep, IRepository<SysUserArea> sysUserAreaRep, IRepository<SysOrg> sysOrgRep)
        {
            _sysUserDataScopeRep = sysUserDataScopeRep;
            _sysUserAreaRep = sysUserAreaRep;
            _sysOrgRep = sysOrgRep;
        }

        /// <summary>
        /// 授权用户数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [UnitOfWork]
        public async Task GrantData(UpdateUserInput input)
        {
            var dataScopes = await _sysUserDataScopeRep.Where(u => u.SysUserId == input.Id).ToListAsync();
            dataScopes.ForEach(u =>
            {
                u.Delete();
            });

            input.GrantOrgIdList.ForEach(u =>
            {
                new SysUserDataScope
                {
                    SysUserId = input.Id,
                    SysOrgId = u
                }.Insert();
            });
            var areas = await _sysUserAreaRep.Where(u => u.SysUserId == input.Id).ToListAsync();
            areas.ForEach(u =>
            {
                u.Delete();
            });

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


        }

        /// <summary>
        /// 根据机构Id集合删除对应的用户-数据范围关联信息
        /// </summary>
        /// <param name="orgIdList"></param>
        /// <returns></returns>
        public async Task DeleteUserDataScopeListByOrgIdList(List<string> orgIdList)
        {
            var dataScopes = await _sysUserDataScopeRep.Where(u => orgIdList.Contains(u.SysOrgId)).ToListAsync();
            dataScopes.ForEach(u =>
            {
                u.Delete();
            });
        }

        /// <summary>
        /// 根据用户Id删除对应的用户-数据范围关联信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task DeleteUserDataScopeListByUserId(string userId)
        {
            var dataScopes = await _sysUserDataScopeRep.Where(u => u.SysUserId == userId).ToListAsync();
            dataScopes.ForEach(u =>
            {
                u.Delete();
            });
        }
    }
}
