using OpenAuth.App.Base;
using OpenAuth.Repository.Domain;
using OpenAuth.Repository;
using SqlSugar;
using OpenAuth.App.Interface;
using Infrastructure;
using OpenAuth.App.BaseApp.Base;

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

        public async Task<List<SysDataItem>> Load(string keyword, bool enabledMark = true)
        {
            var list = await base.Repository.AsQueryable()
                    .Where(a => a.DeleteMark == 0)
                    .WhereIF(enabledMark == true, a => a.EnabledMark == 1)
                    .WhereIF(!string.IsNullOrEmpty(keyword), a => a.ItemName.Contains(keyword) || a.ItemCode.Contains(keyword))
                    .ToListAsync();

            return list;
        }

        public async Task<SysDataItem> GetDataItem(string code)
        {
            var mdeol = await base.Repository.GetFirstAsync(a => a.DeleteMark == 0 && a.ItemCode == code);
            return mdeol;
        }

        public async Task<Response<bool>> SaveClassifyEntity(SysDataItem entity)
        {
            var flag = false;

            if (string.IsNullOrEmpty(entity.ItemId))
            {
                entity.ItemId = Guid.NewGuid().ToString();
                entity.CreateDate = DateTime.Now;
                if (string.IsNullOrEmpty(entity.ParentId))
                {
                    entity.ParentId = "0";
                }
                entity.DeleteMark = 0;
                entity.CreateUserId = base._auth.GetUserId();
                entity.CreateUserName = base._auth.GetUserName();
                flag = await base.Repository.InsertAsync(entity);
            }
            else
            {
                entity.ModifyDate = DateTime.Now;
                entity.ModifyUserId = base._auth.GetUserId();
                entity.ModifyUserName = base._auth.GetUserName();
                flag = await base.Repository.UpdateAsync(entity);
            }

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

        public async Task<Response<bool>> DeleteClassify(string keyValue)
        {
            using (var uow = base.UnitWork.CreateContext())
            {
                await uow.SysDataItem.DeleteByIdAsync(keyValue);
                await uow.SysDataItemDetail.DeleteAsync(a => a.ItemId == keyValue);

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


    }
}
