using AutoMapper;
using Microsoft.Extensions.Localization;
using MS.Common.IDCode;
using MS.Component.Jwt.UserClaim;
using MS.DbContexts;
using MS.Entities;
using MS.Entities.SQLite;
using MS.Models.ViewModel;
using MS.UnitOfWork;
using MS.WebCore.Core;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace MS.Services.SQLite
{
    public class BuidMembershipGroupService : BaseService, IBuidMembershipGroupService
    {
        public BuidMembershipGroupService(IUnitOfWork<MSDbContext> unitOfWork, IMapper mapper, IdWorker idWorker, IClaimsAccessor claimsAccessor, IStringLocalizer localizer, IUnitOfWork<AccountingContext> AccountingContext, IUnitOfWork<SQLiteContext> SQLiteContext, IUnitOfWork<AuthContext> AuthContext) : base(unitOfWork, mapper, idWorker, claimsAccessor, localizer, AccountingContext, SQLiteContext, AuthContext)
        {
        }
        public async Task<ExecuteResult> CreateAsync(BuidMembershipGroupViewModel viewModel)
        {
            ExecuteResult<BuidMembershipGroup> result = new ExecuteResult<BuidMembershipGroup>();
            //检查字段
            if (viewModel.CheckField(ExecuteType.Create, _SQLiteContext) is ExecuteResult checkResult && !checkResult.IsSucceed)
            {
                return result.SetFailMessage(checkResult.Message);
            }
            using (var tran = _SQLiteContext.BeginTransaction())//开启一个事务
            {
                BuidMembershipGroup buidMembership = _mapper.Map<BuidMembershipGroup>(viewModel);
                buidMembership.CurrentBuId = viewModel.CurrentBuId;
                buidMembership.MembershipGroupId = viewModel.MembershipGroupId;
                _SQLiteContext.GetRepository<BuidMembershipGroup>().Insert(buidMembership);
                await _SQLiteContext.SaveChangesAsync();
                await tran.CommitAsync();//提交事务

                result.SetData(buidMembership);//添加成功，把新的实体返回回去
            }
            return result;
        }
    }
}
