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

namespace MS.Services.membershipGroup
{
    public class membershipGroup : BaseService, ImembershipGroup
    {
        public membershipGroup(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> getGroupIdListAsync(string currentBuId)
        {
            ExecuteResult<MembershipGroup> result = new ExecuteResult<MembershipGroup>();
            Guid _currentBuId = new Guid(currentBuId);
            try
            {
                var shiftsQuery = await _AccountingContext.GetRepository<MembershipGroup>().GetAllAsync(x => x.BuInfoId == _currentBuId &&
                           x.GroupStatus == 1);
                result.SetData(shiftsQuery);
            }
            catch (Exception ex)
            {
                ExecuteResult result_ = new ExecuteResult();
                result_.Message = ex.ToString();
                return result_;
            }
            return result;
        }
        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.Id = Guid.NewGuid().ToString();
                buidMembership.CurrentBuId = viewModel.CurrentBuId;
                buidMembership.MembershipGroupId = viewModel.MembershipGroupId;
                _SQLiteContext.GetRepository<BuidMembershipGroup>().Insert(buidMembership);
                await _SQLiteContext.SaveChangesAsync();
                await tran.CommitAsync();//提交事务

                result.SetData(buidMembership);//添加成功，把新的实体返回回去
            }
            return result;
        }
        public async Task<ExecuteResult> GetmembershipGroupAsync(string currentBuId)
        {
            ExecuteResult<BuidMembershipGroup> result = new ExecuteResult<BuidMembershipGroup>();
            IList<BuidMembershipGroup> shiftsQuery;
            if (currentBuId == "" || currentBuId == null)
            {
                 shiftsQuery = await _SQLiteContext.GetRepository<BuidMembershipGroup>().GetAllAsync();
            }
            else
            {
                 shiftsQuery = await _SQLiteContext.GetRepository<BuidMembershipGroup>().GetAllAsync(x => x.CurrentBuId == currentBuId);
            }
            List<BuidMembershipGroup> buidMembershipGroups = new List<BuidMembershipGroup>();
            foreach (var t in shiftsQuery)
            {
                BuidMembershipGroup buidMembership = new BuidMembershipGroup();

                buidMembership.CurrentBuId = t.CurrentBuId;
                buidMembership.MembershipGroupId = t.MembershipGroupId;
                buidMembershipGroups.Add(buidMembership);
            }
            result.SetData(buidMembershipGroups);
            return result;
        }
        public async Task<ExecuteResult> CreateAsync(List<MembershipGroupListViewModel> viewModel)
        {
            ExecuteResult result = new ExecuteResult();

            using (var tran = _SQLiteContext.BeginTransaction())//开启一个事务
            {
                foreach (var t in viewModel)
                {
                    MembershipGroupList buidMembership = _mapper.Map<MembershipGroupList>(t);
                    buidMembership.Id = Guid.NewGuid().ToString();
                    buidMembership.CurrentBuId = t.CurrentBuId;
                    buidMembership.Phone = t.Phone;
                    buidMembership.UpdateStatus = "0";
                    _SQLiteContext.GetRepository<MembershipGroupList>().Insert(buidMembership);

                }
                await _SQLiteContext.SaveChangesAsync();
                await tran.CommitAsync();//提交事务
            }
            return result;
        }
        public async Task<ExecuteResult> UpdateAsync(string currentBuId)
        {
            ExecuteResult result = new ExecuteResult();
            Guid _currentBuId = new Guid(currentBuId);
            var shiftsQuery = await _SQLiteContext.GetRepository<BuidMembershipGroup>().GetAllAsync(x => x.CurrentBuId == currentBuId);
            var Query = await _SQLiteContext.GetRepository<MembershipGroupList>().GetAllAsync(x => x.CurrentBuId == currentBuId && x.UpdateStatus == "0");
            string MembershipGroupId = shiftsQuery.FirstOrDefault()?.MembershipGroupId;
            var membershipGroup = await _AccountingContext.GetRepository<MembershipGroup>().GetAllAsync(x => x.BuInfoId == _currentBuId &&
                          x.GroupStatus == 1 && x.GroupName == MembershipGroupId);
            Guid? GroupId = membershipGroup.FirstOrDefault()?.Id;
            DateTime datetime = DateTime.Now.AddHours(-24);
            var userInfo = await _AccountingContext.GetRepository<UserInfo>().GetAllAsync(x => x.BuId == currentBuId && x.CreationDate >= datetime);
            //Guid guid = new Guid("347a5bf6-8486-4b9c-b91c-c8a0e82a4bb7");
            //var userInfo = await _AccountingContext.GetRepository<UserInfo>().GetAllAsync(x => x.Id == guid);
            //8ddf0847-b5a9-4a3b-a01a-248e629e4785
            List<string> phoneList = new List<string>();
            phoneList.Add("Phone");
            foreach (var u in userInfo)
            {
                var isUserEmpty = Query.FirstOrDefault(x => x.Phone == u.PhoneNo);
                if (isUserEmpty != null)
                {
                    phoneList.Add(u.PhoneNo);
                    using (var tran = _AccountingContext.BeginTransaction())//开启一个事务
                    {
                        UserInfoMembershipGroups userInfoMembershipGroups = new UserInfoMembershipGroups(); ;
                        userInfoMembershipGroups.UserInfoId = u.Id;
                        userInfoMembershipGroups.MembershipGroupId = (Guid)GroupId;
                        _AccountingContext.GetRepository<UserInfoMembershipGroups>().Insert(userInfoMembershipGroups);
                        await _AccountingContext.SaveChangesAsync();
                        await tran.CommitAsync();//提交事务
                    }
                    isUserEmpty.UpdateStatus = "1";
                    _SQLiteContext.GetRepository<MembershipGroupList>().Update(isUserEmpty);
                    await _SQLiteContext.SaveChangesAsync();//提交
                }
            }

            //foreach (var t in Query)
            //{
            //     userInfo = await _AccountingContext.GetRepository<UserInfo>().GetAllAsync(x => x.BuId == currentBuId && x.PhoneNo == t.Phone);
            //    Guid? userInfoid = userInfo.FirstOrDefault()?.Id;
            //    if (userInfo.Count() > 0)
            //    {
            //        using (var tran = _AccountingContext.BeginTransaction())//开启一个事务
            //        {
            //            UserInfoMembershipGroups userInfoMembershipGroups = new UserInfoMembershipGroups(); ;
            //            userInfoMembershipGroups.UserInfoId = (Guid)userInfoid;
            //            userInfoMembershipGroups.MembershipGroupId = (Guid)GroupId;
            //            _AccountingContext.GetRepository<UserInfoMembershipGroups>().Insert(userInfoMembershipGroups);
            //            await _AccountingContext.SaveChangesAsync();
            //            await tran.CommitAsync();//提交事务
            //        }
            //    }
            //}
            return result;
        }
        public async Task<ExecuteResult> GetmembershipGroupListAsync(string currentBuId)
        {
            ExecuteResult<MembershipGroupList> result = new ExecuteResult<MembershipGroupList>();
            var shiftsQuery = await _SQLiteContext.GetRepository<MembershipGroupList>().GetAllAsync(x => x.CurrentBuId == currentBuId);
            List<MembershipGroupList> buidMembershipGroups = new List<MembershipGroupList>();
            foreach (var t in shiftsQuery)
            {
                MembershipGroupList buidMembership = new MembershipGroupList();

                buidMembership.CurrentBuId = currentBuId;
                buidMembership.Phone = t.Phone;
                buidMembership.UpdateStatus = t.UpdateStatus != "0" ? "已推送":"未推送";
                buidMembershipGroups.Add(buidMembership);
            }
            result.SetData(buidMembershipGroups);
            return result;
        }
    }
}
