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

        public async Task<BackstageUser> AddOrGetBackstageUserID(BackstageUser user)
        {
            var dbUser = await Context.Queryable<BackstageUser>().Where(u => u.UserName == user.UserName).SplitTable().FirstAsync();
            if (dbUser == null)
            {
                user.RegisterTime = DateTime.Now;
                user.LoginTime = DateTime.Now;
                user.CreateTime = DateTime.Now;
                await Context.Insertable(user).SplitTable().ExecuteCommandAsync().ConfigureAwait(false);
                //dbUser = Context.Queryable<BackstageUser>().Where(u => u.UserName == user.UserName).First();
                return user;
            }
            else
            {
                dbUser.LoginTime = DateTime.Now;
                await Context.Updateable(user).SplitTable().ExecuteCommandAsync().ConfigureAwait(false);
            }
            return dbUser;
        }
        public async Task<BackstageUser?> GetBackstageUserID(string userName)
        {
            var dbUser = await Context.Queryable<BackstageUser>().Where(u => u.UserName == userName).SplitTable().FirstAsync();
            if (dbUser != null)
            {
                dbUser.LoginTime = DateTime.Now;
                await Context.Updateable(dbUser).SplitTable().ExecuteCommandAsync().ConfigureAwait(false);
            }
            return dbUser;
        }

        public async Task<PageResult<BackstageUser>> GetBackstageUserList(PageData pageData)
        {
            var userList = await Context.Queryable<BackstageUser>().WhereIF(!string.IsNullOrEmpty(pageData.SearchText), bu => bu.UserName.Contains(pageData.SearchText)
                || bu.NickName == null ? false : bu.NickName.Contains(pageData.SearchText)).SplitTable()
                .ToPageListAsync(pageData.Page, pageData.PageSize).ConfigureAwait(false);
            return new PageResult<BackstageUser>
            {
                Data = userList,
                PageSize = pageData.PageSize,
                Total = await Context.Queryable<BackstageUser>().SplitTable().CountAsync().ConfigureAwait(false)
            };
        }
    }
}
