using CrazyStudio.Core.Common.Tools.Extensions;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XPrintServer.Business.Services.Interface;
using XPrintServer.DataModel;
using XPrintServer.DataModel.Models;

namespace XPrintServer.Business.Services
{
    public class UserMenuInRoleService : SqlSugarRepository<UserMenuInRole>, IBusinessService
    {
        public UserMenuInRoleService(ConnectionConfig config) : base(config)
        {
        }


        public async Task AddOrUpdateUserMenuInRoles(Guid roleId, List<Guid> menuIds)
        {
            if (!roleId.IsNullOrGuidEmpty())
            {
                await DeleteRoleUserMenuInRoles(roleId);
                if (menuIds.Any())
                {
                    List<UserMenuInRole> addList = new List<UserMenuInRole>();
                    DateTime now = DateTime.Now;
                    foreach (var menuId in menuIds)
                    {
                        addList.Add(new UserMenuInRole
                        {
                            RoleId = roleId,
                            CreateTime = now,
                            MenuId = menuId
                        });
                    }
                    await Context.Insertable(addList).SplitTable().ExecuteCommandAsync().ConfigureAwait(false);
                }
            }
        }

        public async Task DeleteRoleUserMenuInRoles(Guid roleId)
        {
            if (!roleId.IsNullOrGuidEmpty())
            {
                var deleteDatas = await Context.Queryable<UserMenuInRole>().Where(r => r.RoleId == roleId).SplitTable().ToListAsync().ConfigureAwait(false);
                await Context.Deleteable(deleteDatas).SplitTable().ExecuteCommandAsync().ConfigureAwait(false);
            }
        }

        public async Task<List<Guid>> SelectRoleUserMenuIdsInRoles(Guid roleId)
        {
            if (!roleId.IsNullOrGuidEmpty())
            {
                var menuIds = await Context.Queryable<UserMenuInRole>().Where(r => r.RoleId == roleId).SplitTable().Select(r => r.MenuId).ToListAsync().ConfigureAwait(false);
                return menuIds;
            }
            return new List<Guid>();
        }
    }
}
