using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Infrastructure;
using OpenAuth.App.Base;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.Interface;
using OpenAuth.App.Request;
using OpenAuth.App.Response;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using SqlSugar;

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

        }
        /// <summary>
        /// 加载列表
        /// </summary>
        public async Task<TableData> Load(QueryCategoryTypeListReq request)
        {
            int totalCount = 0;
            var result = new TableData();
            var objs = base.Repository.AsQueryable()
                .WhereIF(!string.IsNullOrEmpty(request.key), u => u.Id.Contains(request.key) || u.Name.Contains(request.key));

            result.data = await objs.OrderBy(u => u.Name).ToPageListAsync(request.page, request.limit, totalCount);
            result.count = totalCount;

            return result;
        }

        public void Add(AddOrUpdateCategoryTypeReq req)
        {
            var obj = req.MapTo<SysCategoryType>();
            //todo:补充或调整自己需要的字段
            obj.CreateTime = DateTime.Now;
            Repository.Insert(obj);
        }

        public void Update(AddOrUpdateCategoryTypeReq obj)
        {
            var user = _auth.GetCurrentUser().User;
            Repository.Update(u => new SysCategoryType
            {
                Name = obj.Name,
                CreateTime = DateTime.Now
                //todo:补充或调整自己需要的字段
            }, u => u.Id == obj.Id);
        }

        public void Delete(string[] ids)
        {
            using (var uwo = UnitWork.CreateContext())
            {
                uwo.CategoryType.Delete(u => ids.Contains(u.Id));
                uwo.Category.Delete(u => ids.Contains(u.TypeId));
                uwo.Commit();
            }
        }

        public List<SysCategoryType> AllTypes()
        {
            return Repository.GetList();
        }
    }
}