using CrazyStudio.Core.Common.Eitities.Page;
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 MenuService : SqlSugarRepository<Menu>, IBusinessService
    {
        public MenuService(ConnectionConfig config) : base(config)
        {
        }

        public async Task AddOrUpdateMenu(Menu menu)
        {
            if (menu.ParentId.IsNullOrGuidEmpty())
            {
                menu.ParentId = null;
            }

            if (menu.Id.IsNullOrGuidEmpty())
            {
                await Context.Insertable(menu).ExecuteCommandAsync().ConfigureAwait(false);
            }
            else
            {
                await Context.Updateable(menu).ExecuteCommandAsync().ConfigureAwait(false);
            }
        }

        public async Task<PageResult<Menu>> GetMenuList(PageData pageData, bool isCheckActive)
        {
            var menuList = await Context.Queryable<Menu>().WhereIF(isCheckActive, m => m.IsActive)
                .ToPageListAsync(pageData.Page, pageData.PageSize).ConfigureAwait(false);
            return new PageResult<Menu>
            {
                Data = menuList,
                PageSize = pageData.PageSize,
                Total = await Context.Queryable<Menu>().WhereIF(isCheckActive, m => m.IsActive).CountAsync().ConfigureAwait(false)
            };
        }

        public async Task<Menu> GetMenu(Guid Id)
        {
            var menu = await Context.Queryable<Menu>().Where(m => m.Id == Id).FirstAsync().ConfigureAwait(false);
            return menu;
        }
    }
}
