using OpenAuth.App.BaseApp.Base;
using OpenAuth.Repository;
using Models;
using OpenAuth.App.Interface;
using SqlSugar;
using Infrastructure;
using OpenAuth.App.Request;
using OpenAuth.App.BaseApp.DmModuleManager.Response;
using OpenAuth.App.BaseApp.DmModuleManager.Request;

namespace OpenAuth.App.BaseApp.DmModuleManager
{
    public class DmModuleApp : SqlSugarBaseApp<DmModule, SugarDbContext>
    {
        private ISqlSugarClient client;

        #region 构造函数
        public DmModuleApp(ISugarUnitOfWork<SugarDbContext> unitWork, ISimpleClient<DmModule> repository, IAuth auth, ISqlSugarClient sqlSugarClient) : base(unitWork, repository, auth)
        {
            this.client = sqlSugarClient;
        }
        #endregion


        #region 数据查询
        /// <summary>
        /// 分页查询模板信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<Response<PageInfo<List<DmModule>>>> LoadModulePageInfo(PageReq request)
        {
            RefAsync<int> totalNumber = 0;

            var table = await base.Repository.AsQueryable()
                     .WhereIF(!string.IsNullOrEmpty(request.key), u => u.ModuleName.Contains(request.key) || u.Description.Contains(request.key))
                     .OrderByDescending(u => u.CreateTime)
                     .ToPageListAsync(request.page, request.limit, totalNumber);

            return new Response<PageInfo<List<DmModule>>>()
            {
                Result = new PageInfo<List<DmModule>>
                {
                    Items = table,
                    Total = totalNumber
                }
            };
        }

        /// <summary>
        /// 查询所有模板信息
        /// </summary>
        /// <returns></returns>
        public async Task<Response<List<DmModule>>> LoadAll()
        {
            var table = await base.Repository.AsQueryable()
                     .OrderByDescending(u => u.CreateTime)
                     .ToListAsync();

            return new Response<List<DmModule>>()
            {
                Result = table
            };
        }

        /// <summary>
        /// 根据模板id获取字段列表
        /// </summary>
        /// <param name="id">模板id</param>
        /// <returns></returns>
        public async Task<Response<List<DmModulecolumn>>> LoadCloumsById(string id)
        {
            var table = await base.Repository.AsSugarClient().Queryable<DmModulecolumn>()
                .Where(r => r.ModuleId == id)
                .OrderByDescending(r => r.Sort)
                .ToListAsync();

            return new Response<List<DmModulecolumn>>()
            {
                Result = table
            };
        }

        /// <summary>
        /// 根据模板详情信息查询
        /// </summary>
        /// <param name="id">模板id</param>
        /// <returns></returns>
        public async Task<Response<DmDetailRes>> LoadModuleDetailInfo(string id)
        {
            var table = await base.Repository.AsQueryable()
                .Where(r => r.Id == id)
                .Select(r => new DmDetailRes
                {
                    Id = r.Id,
                    ModuleName = r.ModuleName,
                    Description = r.Description,
                    CreateTime = r.CreateTime,
                    CreateUserId = r.CreateUserId,
                    CreateUserName = r.CreateUserName,
                    Cloums = SqlFunc.Subqueryable<DmModulecolumn>().Where(a => a.ModuleId == r.Id).ToList()
                }).FirstAsync();

            return new Response<DmDetailRes>()
            {
                Result = table
            };
        }
        #endregion

        #region 增删改
        /// <summary>
        /// 添加或者修改数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public Response<bool> AddOrUpdate(AddorUpdateModuleReq request)
        {
            //查询当前登录用户信息
            var user = _auth.GetCurrentUser().User;
            using (var uow = base.UnitWork.CreateContext())
            {
                var module = request.Module;
                if (string.IsNullOrEmpty(module.Id))
                {
                    if (uow.DmModule.IsAny(u => u.ModuleName == module.ModuleName))
                    {
                        throw new Exception("模板名称已存在");
                    }
                    module.Id = Guid.NewGuid().ToString();
                    module.CreateTime = DateTime.Now;
                    module.CreateUserId = user.Id.ToString();
                    module.CreateUserName = user.Name;

                    List<DmModulecolumn> cloum = new List<DmModulecolumn>();
                    foreach (var item in request.Cloums)
                    {
                        DmModulecolumn cl = new DmModulecolumn();
                        cl.Id = Guid.NewGuid().ToString();
                        cl.ModuleId = module.Id;
                        cl.Description = item.Description;
                        cl.Name = item.Name;
                        cl.Description = item.Description;
                        cl.Sort = item.Sort;
                        cloum.Add(cl);
                    }

                    uow.DmModule.Insert(module);
                    uow.DmModulecolumn.InsertRange(cloum);
                }
                else
                {
                    //判断模板名称是否重复
                    if (uow.DmModule.IsAny(u => u.ModuleName == module.ModuleName && u.Id != module.Id))
                    {
                        throw new Exception("模板名称已存在");
                    }
                    //更新模板信息
                    uow.DmModule.Update(u => new DmModule
                    {
                        ModuleName = module.ModuleName,
                        Description = module.Description
                    }, u => u.Id == module.Id);

                    //删除模板原有字段
                    uow.DmModulecolumn.Delete(u=>u.ModuleId==module.Id);
                    //添加模板新字段
                    List<DmModulecolumn> cloum = new List<DmModulecolumn>();
                    foreach (var item in request.Cloums)
                    {
                        DmModulecolumn cl = new DmModulecolumn();
                        cl.Id = Guid.NewGuid().ToString();
                        cl.ModuleId = module.Id;
                        cl.Description = item.Description;
                        cl.Name = item.Name;
                        cl.Description = item.Description;
                        cl.Sort = item.Sort;
                        cloum.Add(cl);
                    }
                    uow.DmModulecolumn.InsertRange(cloum);
                }

                var flag = uow.Commit();

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

        /// <summary>
        /// 根据选中id删除模板
        /// </summary>
        /// <param name="ids"></param>
        public Response<bool> DeleteModule(string[] ids)
        {
            using (var uow = base.UnitWork.CreateContext())
            {
                uow.DmModulecolumn.Delete(u => ids.Contains(u.ModuleId));
                uow.DmModule.Delete(u => ids.Contains(u.Id));

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

    }
}
