using BPA.KitChen.GroupMeal.Application.BaseDto;
using BPA.KitChen.GroupMeal.SqlSugar;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Mvc;
using SqlSugar.DistributedSystem.Snowflake;
using SqlSugar;
using BPA.KitChen.GroupMeal.Core.Entity;
using BPA.KitChen.GroupMeal.Application.Service.OneCard.StoredValueCard.Dto.MmenberCard;
using BPA.KitChen.GroupMeal.Application.Service.OneCard.StoredValueCard.Dto.MemberAccountRecord;
using Furion.FriendlyException;

namespace BPA.KitChen.GroupMeal.Application.Service.OneCard.StoredValueCard
{

    [ApiDescriptionSettings("一卡通", Tag = "储值卡管理")]
    public class StoredValueCard : SupperRepository, IDynamicApiController, IStoredValueCard, ITransient
    {
        private readonly SqlSugarScope db;

        public StoredValueCard()
        {
            db = SqlSugarDb.Db; ;   // 推荐操作
        }

        /// <summary>
        /// 获取会员卡
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        [HttpPost("/api/StoredValueCard/GetMmenberCardPage")]
        public async Task<PageUtil> GetMmenberCardPage(MmenberCardPageInputDto inputDto)
        {
            int total = 0;
            var data = db.Queryable<BPA_MemberCard>()
                .WhereIF(!string.IsNullOrEmpty(inputDto.CardNum), x => x.CardNum == inputDto.CardNum)
                .OrderBy(x => x.CreateAt, OrderByType.Desc)
                .Select((a) => new MmenberCardOutDto()
                {
                    CardNum = a.CardNum,
                    CreateAt = a.CreateAt,
                    Id = a.Id,
                    State = a.State,
                    Type = a.Type,
                })
            .ToPageList(inputDto.Current, inputDto.PageSize, ref total);

            var cardIds = data.Select(x => x.Id).ToList();

            var list = db.Queryable<BPA_MemberCardsBindingRecord, BPA_MemberInfo>((a, b) =>
                    new JoinQueryInfos(
                        JoinType.Left, a.MemberInfoId == b.Id))
                .Where((a, b) => cardIds.Contains(a.MemberCardId))
                .Select((a, b) => new MmenberCardOutDto()
                {
                    CreateAt = a.CreateAt,
                    Id = a.MemberCardId,
                    HeadImgUrl = b.HeadImgUrl,
                    MemberInfoId = b.Id,
                    MemberName = b.RealName,
                    Phone = b.Phone
                })
                .ToList();

            var result = new List<MmenberCardOutDto>();
            foreach (var item in data)
            {
                var info = list.FirstOrDefault(x => x.Id == item.Id);
                if (info != null)
                {
                    item.MemberInfoId = info.MemberInfoId;
                    item.MemberName = info.MemberName;
                    item.Phone = info.Phone;
                    item.HeadImgUrl = info.HeadImgUrl;
                }

            }
            return new PageUtil()
            {
                Data = data,
                Total = total
            };
        }


        /// <summary>
        /// 添加会员卡
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        [HttpPost("/api/StoredValueCard/AddMmenberCard")]
        public async Task<bool> AddMmenberCard(MmenberCardInputDto inputDto)
        {
            var worker = new IdWorker(1, 1);
            return await db.Insertable(new BPA_MemberCard()
            {
                State = inputDto.State,
                Type = inputDto.Type,
                CardNum = worker.NextId().ToString(),

            }).CallEntityMethod(m => m.Create()).ExecuteCommandAsync() > 0;
        }


        /// <summary>
        /// 修改会员卡状态
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        [HttpPut("/api/StoredValueCard/UpdateMmenberCardState")]
        public async Task<bool> UpdateMmenberCardState(MmenberCardInputDto inputDto)
        {
            var mmenberCard = db.Queryable<BPA_MemberCard>().First(x => x.Id == inputDto.Id);
            if (mmenberCard == null)
            {
                return false;
            }

            if (mmenberCard.Type != 2 && inputDto.State == 2)
            {
                return false;
            }

            mmenberCard.State = inputDto.State;
            return db.Updateable(mmenberCard).UpdateColumns(it => new { it.State }).ExecuteCommand() > 0;
        }


        /// <summary>
        /// 会员绑定会员卡
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        [HttpPost("/api/StoredValueCard/MemberBindingCards")]
        public async Task<bool> MemberBindingCards(MemberBindingCardsInputDto inputDto)
        {
            var memberInfo = db.Queryable<BPA_MemberInfo>().First(x => x.Id == inputDto.MemberInfoId);
            if (memberInfo == null) return false;
            var card = db.Queryable<BPA_MemberCard>().First(x => x.Id == inputDto.MemberCardId && x.State != 3);
            if (card == null) return false;


            //查询会员账户
            var memberAccount = db.Queryable<BPA_MemberAccount>().First(x => x.MemberInfoId == inputDto.MemberInfoId);
            if (memberAccount == null) return false;


            var memberBindingCards = await db.Queryable<BPA_MemberCardsBindingRecord, BPA_MemberCard>((a, b) =>
                    new JoinQueryInfos(
                        JoinType.Left, a.MemberCardId == b.Id))
                .Where((a, b) => b.Id == inputDto.MemberCardId).ToListAsync();
            if (memberBindingCards.Count > 0)
            {
                throw Oops.Oh($"会员卡已绑定会员");
            }

            return await db.Insertable(new BPA_MemberCardsBindingRecord()
            {
                MemberCardId = inputDto.MemberCardId,
                MemberInfoId = inputDto.MemberInfoId,
                MemberAccountId = memberAccount.Id,

            }).CallEntityMethod(m => m.Create()).ExecuteCommandAsync() > 0;
        }


        /// <summary>
        /// 获取 会员账户  会员卡的  消费充值记录
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        [HttpPost("/api/StoredValueCard/GetMemberAccountAmountPage")]
        public async Task<PageUtil> GetMemberAccountAmountPage(MemberAccountRecordPageInputDto inputDto)
        {
            int total = 0;
            var data = db.Queryable<BPA_MemberAccountRecord, BPA_MemberCard, BPA_MemberInfo>((a, b, c) =>
                    new JoinQueryInfos(
                        JoinType.Left, a.MemberCardId == b.Id,
                        JoinType.Left, a.MemberInfoId == c.Id))
                .WhereIF(!string.IsNullOrEmpty(inputDto.MemberInfoId), (a, b, c) => a.MemberInfoId == inputDto.MemberInfoId)
                .WhereIF(!string.IsNullOrEmpty(inputDto.MemberCardId), (a, b, c) => a.MemberCardId == inputDto.MemberCardId).WhereIF(inputDto.Type.HasValue, (a, b, c) => a.Type == inputDto.Type.Value)
                .WhereIF(inputDto.StartTime.HasValue, (a, b, c) => a.CreateAt.Date >= inputDto.StartTime.Value.Date && a.CreateAt.Date <= inputDto.EndTime.Value.Date.AddDays(1).AddSeconds(-1))
                .OrderBy((a, b, c) => a.CreateAt, OrderByType.Desc)
                .Select((a, b, c) => new MemberAccountRecordOutDto()
                {
                    AfterMoney = a.AfterMoney,
                    BeforeMoney = a.BeforeMoney,
                    CardNum = b.CardNum,
                    CreateAt = a.CreateAt,
                    MemberCardId = a.MemberCardId,
                    MemberInfoId = a.MemberInfoId,
                    MemberName = c.RealName,
                    Money = a.Money,
                    Type = a.Type,
                    MemberPhone = c.Phone,
                    HeadImgUrl = c.HeadImgUrl,

                })
                .ToPageList(inputDto.Current, inputDto.PageSize, ref total);

            return new PageUtil()
            {
                Data = data,
                Total = total
            };
        }


        
    }
}
