
using DocumentFormat.OpenXml.Spreadsheet;
using Flurl.Util;
using Infrastructure;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.Interface;
using OpenAuth.App.Request;
using OpenAuth.App.Response;
using OpenAuth.App.ServiceApp.MiManager.Resquest;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using SqlSugar;

namespace OpenAuth.App
{
    public class MiParkingApp : SqlSugarBaseApp<MiParking, SugarDbContext>
    {
        public MiParkingApp(
            ISugarUnitOfWork<SugarDbContext> unitWork,
            ISimpleClient<MiParking> repository,
            IAuth auth
            ) : base(unitWork, repository, auth)
        {

        }

        #region 查询
        /// <summary>
        /// 分页
        /// </summary>
        public async Task<Response<PageInfo<List<MiParking>>>> LoadAllPage(PageReq request)
        {         
            RefAsync<int> totalCount = 0;
            var result = new PageInfo<SysRole>();
            var list = await base.Repository.AsQueryable()
                .WhereIF(request.key!=null,r=>r.Name.Contains(request.key)||r.Num.Contains(request.key))
                .ToPageListAsync(request.page, request.limit, totalCount);

            return new Response<PageInfo<List<MiParking>>>
            {
                Result = new PageInfo<List<MiParking>>
                {
                    Items = list,
                    Total = totalCount
                }
            };
        }

        /// <summary>
        /// app 扫码查询停车场信息
        /// </summary>
        /// <param name="parkingid"></param>
        /// <returns></returns>
        public async Task<Response<List<MiParking>>> LoadParkinginfo()
        {
            var user=_auth.GetCurrentUser().User;
            if (user == null)
            {
                throw new Exception("请登录");
            }
            
            var pidlist=base.Repository.ChangeRepository<SugarRepositiry<MiParkingUser>>()
                .AsQueryable().Where(r=>r.UserId == user.Id)
                .Select(r=>r.ParkingId).Distinct().ToList();

            var list = await base.Repository.AsQueryable()
            .WhereIF(user.Id!=-1,p => pidlist.Contains(p.Id)||p.Manager==user.Id.ToString())
            .OrderBy(p => p.Name)
            .ToListAsync();

            return new Response<List<MiParking>>
            {
                Result = list
            };
        }
        #endregion

        public async Task<dynamic> Get(string id)
        {
            var info = await base.Repository.AsQueryable()
                .Where(r => r.Id == id)
                .FirstAsync();

            if (info != null)
            {
                var userids = await base.Repository.ChangeRepository<SugarRepositiry<MiParkingUser>>().AsQueryable().Where(r => r.ParkingId == info.Id)
                    .LeftJoin<SysUser>((r, u) => r.UserId == u.Id)
                    .Select<dynamic>((r, u) => new
                    {
                        u.Id,
                        u.Name,
                        u.Account
                    }).ToListAsync();
                return new
                {
                    info,
                    userids
                };
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 添加
        /// </summary>
        public async Task<Response<bool>> Add(MiParking model)
        {
            model.Id = Guid.NewGuid().ToString();
            var flag = await Repository.InsertAsync(model);

            return new Response<bool>
            {
                Result = flag,
                Message = flag == true ? "success" : "error"
            };
        }

        /// <summary>
        /// 给停车场分配用户
        /// </summary>
        public async Task<Response<bool>> AllocateUser(MiParkingUserReq model)
        {
            List<MiParkingUser> miplist = new List<MiParkingUser>();
            foreach(var item in model.UserId)
            {
                MiParkingUser mu=   new MiParkingUser();
                mu.UserId = item;
                mu.ParkingId = model.ParkingId;
                miplist.Add(mu);
            }
            using (var uow = base.UnitWork.CreateContext())
            {
                var list = uow.MiParkingUser.AsQueryable().Where(r => r.ParkingId == model.ParkingId).ToList();
                if(list.Count > 0)
                {
                    await uow.MiParkingUser.DeleteAsync(list);
                }
                var flag = await uow.MiParkingUser.InsertRangeAsync(miplist);
                var flagres = uow.Commit() && flag;

                return new Response<bool>
                {
                    Result = flag,
                    Message = flag == true ? "success" : "error"
                };
            }
        }



        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        public async Task<Response<bool>> Delete(List<MiParking> models)
        {
             var flag = await Repository.DeleteAsync(models);

             return new Response<bool>
             {
                 Result = flag,
                 Message = flag == true ? "success" : "error"
             };
            
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="obj"></param>
        public async Task<Response<bool>> Update(MiParking model)
        {
            bool flag = await base.Repository.UpdateAsync(model);

            return new Response<bool>
            {
                Result = flag,
                Message = flag == true ? "success" : "error"
            };
        }

        /// <summary>
        /// 事务示例
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<Response<bool>> AssignModule()
        {
            using (var uwo = UnitWork.CreateContext())
            {                
                //await uwo.SysRoleElement.InsertRangeAsync(model.ElementIds.Select(a => new SysRoleElement { RoleId = model.RoleId, ElementId = a }).ToList());

                var flag = uwo.Commit();
                return new Response<bool>
                {
                    Result = flag,
                    Message = flag == true ? "success" : "error"
                };
            }
        }

    }
}