using BPA.KitChen.GroupMeal.Application.BaseDto;
using BPA.KitChen.GroupMeal.Application.Service.OneCard.StoredValueCard.Dto;
using BPA.KitChen.GroupMeal.Core.Common.Const;
using BPA.KitChen.GroupMeal.Core.Entity;
using BPA.KitChen.GroupMeal.Core.Enum;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Furion;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BPA.KitChen.GroupMeal.Application.Service.OneCard.PayCardInfo;
using BPA.KitChen.GroupMeal.SqlSugar;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Mapster;
using BPA.KitChen.GroupMeal.Application.Service.OneCard.Member.MemberInfo.Dtos.MemberTag;

namespace BPA.KitChen.GroupMeal.Application.Service.OneCard.Member.MemberInfo
{
    [ApiDescriptionSettings("会员管理", Tag = "会员信息")]
    public class MemberInfoService : SupperRepository, IDynamicApiController, IMemberInfoService, ITransient
    {

        private readonly SqlSugarScope db;

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

        /// <summary>
        /// 查询会员
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        [HttpPost("/api/MemberInfoService/GetMemberPageQuery")]
        public async Task<PageUtil> GetMemberPageQuery(GetMemberInfoQueryInputDto inputDto)
        {

            List<IConditionalModel> conModels = new List<IConditionalModel>();
            if (!string.IsNullOrEmpty(inputDto.NickName))
            {
                conModels.Add(new ConditionalModel() { FieldName = "NickName", ConditionalType = ConditionalType.Like, FieldValue = inputDto.NickName });
            }
            if (!string.IsNullOrEmpty(inputDto.RealName))
            {
                conModels.Add(new ConditionalModel() { FieldName = "RealName", ConditionalType = ConditionalType.Like, FieldValue = inputDto.RealName });
            }
            if (!string.IsNullOrEmpty(inputDto.Status))
            {
                conModels.Add(new ConditionalModel() { FieldName = "Status", ConditionalType = ConditionalType.Equal, FieldValue = inputDto.Status });
            }
            var result = new List<MemberInfoBaseDto>();
            int total = 0;
            //分页查询基础会员表
            var data = db.Queryable<BPA_MemberInfo>().Where(conModels)
                .WhereIF(!string.IsNullOrWhiteSpace(inputDto.Phone), x => x.Phone.Contains(inputDto.Phone))
                .ToPageList(inputDto.Current, inputDto.PageSize, ref total);

            result = data.Adapt<List<MemberInfoBaseDto>>();
            var tatalId = data.Select(x => x.Id).ToList();

            //查询平台数据
            var platformMemberInfos = await db.Queryable<BPA_PlatformMemberInfo>().Where(x => tatalId.Contains(x.MemberInfo_Id)).ToListAsync();

            //查询标签
            var tags = db.Queryable<BPA_MemberTagInfo, BPA_MemberTag>((a, b) => new JoinQueryInfos(
                  JoinType.Left, b.Id == a.MemberTag_Id
              )).Where((a, b) => tatalId.Contains(a.MemberInfo_Id) && a.IsDeleted == 0)
                .OrderBy((a, b) => a.CreateAt,OrderByType.Desc)
                 .Select((a, b) => new MemberTagOutDto()
                 {
                     Id = b.Id,
                     Name = b.Name,
                     Sort = b.Sort,
                     MemberId = a.MemberInfo_Id,
                     PlatformType = a.PlatformType
                 })
                 .ToList();


            foreach (var item in result)
            {
                var tag = tags.Where(x => x.MemberId == item.Id).ToList();
                item.MemberTag = tag.Where(x => x.PlatformType == 0).ToList();

                var re = platformMemberInfos.Where(x => x.MemberInfo_Id == item.Id).ToList();
                if (re.Count > 0)
                {

                    var platformMember = re.Adapt<List<PlatformMemberInfoBaseDto>>();

                    platformMember.ForEach(obj =>
                    {

                        obj.MemberTag = tag.Where(x => x.PlatformType == obj.PlatformType).ToList();

                    });
                    item.PlatformMemberInfos = platformMember;
                }
                else
                {
                    item.PlatformMemberInfos = new List<PlatformMemberInfoBaseDto>();
                }
            }

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

        /// <summary>
        /// 添加会员
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        [HttpPost("/api/MemberInfoService/AddMember")]
        public async Task<bool> AddMember(CreateOrUpdateMemberInfoInputDto inputDto)
        {
            try
            {
                var result = true;
                db.Ado.BeginTran();
                var memberInfo = await db.Queryable<BPA_MemberInfo>().FirstAsync(x => x.Phone == inputDto.Phone);
                if (memberInfo == null)
                {
                    //添加会员信息
                    memberInfo = inputDto.Adapt<BPA_MemberInfo>();
                    await db.Insertable(memberInfo).CallEntityMethod(m => m.Create()).ExecuteCommandAsync();
                }

                inputDto.MemberInfo_Id = memberInfo.Id;
                //添加平台会员
                result = await AddPlatformMember(inputDto);

                //添加会员账户
                result = await AddMemberAccount(memberInfo.Id);

                db.Ado.CommitTran();
                return result;
            }
            catch (Exception e)
            {
                db.Ado.RollbackTran();
                return false;
            }
        }


        /// <summary>
        /// 修改会员信息
        /// </summary>
        /// <returns></returns>
        [HttpPost("/api/MemberInfoService/UpdateMemberInfo")]
        public async Task<bool> UpdateMemberInfo(CreateOrUpdateMemberInfoInputDto inputDto)
        {
            if (inputDto.PlatformType == 0)
            {
                var data = db.Queryable<BPA_MemberInfo>().First(x => x.Id == inputDto.MemberInfo_Id);

                if (data == null)
                {
                    throw Oops.Oh($"会员不存在");
                }
                data.Address = inputDto.Address;
                data.Birthday = inputDto.Birthday;
                data.CardNum = inputDto.CardNum;
                data.City = inputDto.City;
                data.Country = inputDto.Country;
                data.County = inputDto.County;
                data.HeadImgUrl = inputDto.HeadImgUrl;
                data.Level_Id = inputDto.Level_Id;
                data.NickName = inputDto.NickName;
                data.Phone = inputDto.Phone;
                data.Province = inputDto.Province;
                data.RealName = inputDto.RealName;
                data.Sex = inputDto.Sex;
                data.Status = inputDto.Status;
                data.ShowPlatformType = (int)inputDto.ShowPlatformType;
                //添加会员账户
                await AddMemberAccount(data.Id);
                return await db.Updateable(data).CallEntityMethod(m => m.Modify()).ExecuteCommandAsync() > 0;
            }
            else
            {

                var data = db.Queryable<BPA_PlatformMemberInfo>().Where(x => x.MemberInfo_Id == inputDto.MemberInfo_Id && x.PlatformType == inputDto.PlatformType).First();
                if (data == null)
                {
                    throw Oops.Oh($"当前平台会员不存在");
                }
                data.Address = inputDto.Address;
                data.Birthday = inputDto.Birthday;
                data.CardNum = inputDto.CardNum;
                data.City = inputDto.City;
                data.Country = inputDto.Country;
                data.County = inputDto.County;
                data.HeadImgUrl = inputDto.HeadImgUrl;
                data.Level_Id = inputDto.Level_Id;
                data.NickName = inputDto.NickName;
                data.Phone = inputDto.Phone;
                data.Province = inputDto.Province;
                data.RealName = inputDto.RealName;
                data.Sex = inputDto.Sex;
                data.Status = inputDto.Status;
                return await db.Updateable(data).CallEntityMethod(m => m.Modify()).ExecuteCommandAsync() > 0;
            }



        }


        /// <summary>
        /// 获取所有会员标签，获取当前会员的绑定标签
        /// </summary>
        /// <param name="memberInfoId">会员ID</param>
        /// <param name="PlatformType">0:系统平台  1.微信平台   2.支付宝平台 </param>
        /// <returns></returns>
        [HttpGet("/api/MemberInfoService/GetMemberTagAndInfo")]
        public async Task<List<MemberTagAndInfoOutDto>> GetMemberTagAndInfo(string memberInfoId, PlatformType PlatformType)
        {
            var data = await db.Queryable<BPA_MemberTag>()
                .Where(x => x.IsDeleted == 0 && x.PlatformType == (int)PlatformType)
                .Select(x => new MemberTagAndInfoOutDto()
                {
                    Id = x.Id,
                    Name = x.Name
                }).ToListAsync();
            var memberTagInfo = db.Queryable<BPA_MemberTagInfo>()
                .Where(x => x.IsDeleted == 0 && x.MemberInfo_Id == memberInfoId && x.PlatformType == PlatformType).ToList();

            foreach (var item in data)
            {
                var entity = memberTagInfo.FirstOrDefault(x => x.MemberTag_Id == item.Id);

                if (entity != null)
                {
                    item.MemberTagInfoId = entity.Id;
                }
            }

            return data;
        }


        /// <summary>
        /// 根据ID获取会员其他平台的信息
        /// </summary>
        /// <param name="memberId"></param>
        /// <returns></returns>
        [HttpGet("/api/MemberInfoService/GetPlatformMemberList")]
        public async Task<List<PlatformMemberInfoBaseDto>> GetPlatformMemberList(string memberId)
        {
            var data = await db.Queryable<BPA_PlatformMemberInfo>().Where(x => x.MemberInfo_Id == memberId).ToListAsync();
            var platformMember = data.Adapt<List<PlatformMemberInfoBaseDto>>();

            //查询标签
            var tags = db.Queryable<BPA_MemberTagInfo, BPA_MemberTag>((a, b) => new JoinQueryInfos(
                    JoinType.Left, b.Id == a.MemberTag_Id
                )).Where((a, b) => memberId == a.MemberInfo_Id && a.IsDeleted == 0)
                .Select((a, b) => new MemberTagOutDto()
                {
                    Id = b.Id,
                    Name = b.Name,
                    Sort = b.Sort,
                    MemberId = a.MemberInfo_Id,
                    PlatformType = a.PlatformType
                })
                .ToList();
            platformMember.ForEach(obj =>
            {
                obj.MemberTag = tags.Where(x => x.PlatformType == obj.PlatformType).ToList();
            });


            return platformMember.Adapt<List<PlatformMemberInfoBaseDto>>();
        }


        /// <summary>
        /// 获取会员账户信息
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        [HttpPost("/api/MemberInfoService/GetMemberAccountPageList")]
        public async Task<PageUtil> GetMemberAccountPageList(MemberAccountPageInputDto inputDto)
        {
            var total = 0;
            var list = new List<string>();

            if (!string.IsNullOrEmpty(inputDto.CardNum))
            {
                list = db.Queryable<BPA_MemberCardsBindingRecord, BPA_MemberCard>((a, b) =>
                        new JoinQueryInfos(
                            JoinType.Left, a.MemberCardId == b.Id))
                    .Where((a, b) => b.CardNum == inputDto.CardNum)
                    .Select((a, b) => a.MemberInfoId)
                    .ToList();

            }

            var data = db.Queryable<BPA_MemberAccount, BPA_MemberInfo>((a, b) => new JoinQueryInfos(
                    JoinType.Left, a.MemberInfoId == b.Id
                ))
                .WhereIF(!string.IsNullOrEmpty(inputDto.MemberInfoId), (a, b) => a.MemberInfoId == inputDto.MemberInfoId)
                .WhereIF(!string.IsNullOrEmpty(inputDto.MemberInfoId), (a, b) => a.MemberInfoId == inputDto.MemberInfoId)
                .WhereIF(!string.IsNullOrEmpty(inputDto.CardNum), (a, b) => list.Contains(a.MemberInfoId))
                .WhereIF(!string.IsNullOrEmpty(inputDto.Name), (a, b) => b.RealName.Contains(inputDto.Name))
            .Select((a, b) => new MemberAccountOutDto()
            {
                    Id = a.Id,
                    MemberInfoId = b.Id,
                    Money = a.Money,
                    Name = b.RealName,
                    HeadImgUrl = b.HeadImgUrl,
                    MemberCardNum = b.CardNum,
                    MemberPhone = b.Phone,
                }).ToPageList(inputDto.Current, inputDto.PageSize, ref total);

            var cards = db.Queryable<BPA_MemberCardsBindingRecord, BPA_MemberCard>((a, b) => new JoinQueryInfos(
                    JoinType.Left, a.MemberCardId == b.Id))
                .Select((a, b) => new CardDto()
                {
                    MemberInfoId = a.MemberInfoId,
                    CardNum = b.CardNum,
                    CreateAt = b.CreateAt,
                    Id = b.Id,
                    State = b.State,
                    Type = b.Type,
                }).ToList();

            foreach (var item in data)
            {
                var card = cards.Where(x => x.MemberInfoId == item.MemberInfoId).ToList();
                item.Cards = card.Count > 0 ? card : new List<CardDto>();
            }
            return new PageUtil()
            {
                Data = data,
                Total = total
            };
        }


        /// <summary>
        /// 查询会员标签信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("/api/MemberInfoService/GetMemberTag")]
        public PageUtil GetMemberTag(MemberTagQueryDto dto)
        {
            List<IConditionalModel> conModels = new List<IConditionalModel>();

            string groupId = App.User.FindFirst(ClaimConst.GroupId)?.Value;
            if (!string.IsNullOrEmpty(dto.Name))
            {
                conModels.Add(new ConditionalModel() { FieldName = "Name", ConditionalType = ConditionalType.Equal, FieldValue = dto.Name.ToString() });
            }
            if (!string.IsNullOrEmpty(dto.PlatformType))
            {
                conModels.Add(new ConditionalModel() { FieldName = "PlatformType", ConditionalType = ConditionalType.Equal, FieldValue = dto.PlatformType });
            }
            if (!string.IsNullOrEmpty(dto.Status.ToString()))
            {
                conModels.Add(new ConditionalModel() { FieldName = "Status", ConditionalType = ConditionalType.Equal, FieldValue = dto.Status.ToString() });
            }
            int total = new RefAsync<int>();
            var res = db.Queryable<BPA_MemberTag>()
                    .Where(a => a.IsDeleted == 0)
                    .Where(conModels)
                    .WhereIF(dto.CreateAt.HasValue, a => SqlFunc.DateIsSame(a.CreateAt, Convert.ToDateTime(dto.CreateAt), DateType.Day))
                    .OrderBy(x => x.CreateAt, OrderByType.Desc)
                    .Select(t => new MemberTagQueryDto
                    {
                        Id = t.Id,
                        Name = t.Name,
                        Sort = t.Sort,
                        PlatformType = t.PlatformType.ToString(),
                        CreateAt = t.CreateAt,
                        Status = Convert.ToInt32(t.Status),

                    }).ToPageList(dto.Current, dto.PageSize, ref total);
            return new PageUtil()
            {
                Data = res,
                Total = total
            };
        }


        /// <summary>
        /// 修改会员状态
        /// </summary>
        /// <returns></returns>
        [HttpPost("/api/MemberInfoService/UpdateMemberStatus")]
        public async Task<bool> UpdateMemberStatus(MemberInfoBaseDto inputDto)
        {
            if (!System.Enum.IsDefined(typeof(PlatformType), inputDto.PlatformType))
            {
                throw Oops.Oh($"平台错误");
            }

            try
            {
                db.BeginTran();
                var data = db.Queryable<BPA_MemberInfo>().First(x => x.Id == inputDto.Id);
                var data2 = db.Queryable<BPA_PlatformMemberInfo>().Where(x => x.MemberInfo_Id == inputDto.Id).ToList();
                if (data == null)
                {
                    throw Oops.Oh($"会员不存在");
                }
                if (inputDto.PlatformType == 0)
                {
                    data.Status = (CommonStatus)inputDto.Status;
                    db.Updateable(data).CallEntityMethod(m => m.Modify()).ExecuteCommand();
                }
                if (data2.Count > 0)
                {
                    //根据选择平台修改会员状态
                    data2 = data2.Where(x => inputDto.PlatformType == 1 ? (x.PlatformType == 1) : (x.PlatformType == 2 ? (x.PlatformType == 2) : true)).ToList();
                    data2.ForEach(item =>
                    {
                        item.Status = (CommonStatus)inputDto.Status;
                    });
                    db.Updateable(data2).CallEntityMethod(m => m.Modify()).ExecuteCommand();
                }
                db.CommitTran();
                return await Task.FromResult(true);
            }
            catch (Exception ex)
            {
                db.RollbackTran();
                //BPALog.WriteLog(msg + ":" + ex.Message, LogEnum.Error, null, ex);
                throw Oops.Oh(ex.Message);
            }
        }


        /// <summary>
        /// 修改会员标签
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        [HttpPost("/api/MemberInfoService/UpdateMemberTag")]
        public async Task<bool> UpdateMemberTag(UpdateMemberTagInputDto inputDto)
        {

            try
            {
                db.BeginTran();
                //查询当前会员绑定的标签
                var data = db.Queryable<BPA_MemberTagInfo>().Where(x => x.MemberInfo_Id == inputDto.MemberInfo_Id && inputDto.PlatformType == x.PlatformType).ToList();
                data.ForEach(item =>
                {
                    item.IsDeleted = 1;
                });
                //全部删除
                db.Updateable(data).CallEntityMethod(m => m.Modify()).ExecuteCommand();

                //添加会员标签
                foreach (var item in inputDto.Tags)
                {
                    var thisMemberTagInfo = data.Where(x => x.MemberInfo_Id == inputDto.MemberInfo_Id && x.MemberTag_Id == item).FirstOrDefault();

                    if (thisMemberTagInfo != null)
                    {
                        db.Updateable(new BPA_MemberTagInfo() { IsDeleted = 0 }).UpdateColumns(it => new { it.IsDeleted })
                            .Where(x => x.MemberInfo_Id == inputDto.MemberInfo_Id && x.MemberTag_Id == item).ExecuteCommand();
                    }
                    else
                    {
                        db.Insertable(new BPA_MemberTagInfo()
                        {
                            PlatformType = inputDto.PlatformType,
                            MemberInfo_Id = inputDto.MemberInfo_Id,
                            MemberTag_Id = item

                        }).CallEntityMethod(m => m.Create()).ExecuteCommand();
                    }
                }
                db.CommitTran();
                return await Task.FromResult(true);
            }
            catch (Exception ex)
            {
                db.RollbackTran();
                //BPALog.WriteLog(msg + ":" + ex.Message, LogEnum.Error, null, ex);
                throw Oops.Oh(ex.Message);
            }
        }



        /// <summary>
        /// 添加平台会员
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        private async Task<bool> AddPlatformMember(CreateOrUpdateMemberInfoInputDto inputDto)
        {
            var memberInfo = db.Queryable<BPA_PlatformMemberInfo>().First(x =>
                x.MemberInfo_Id == inputDto.MemberInfo_Id && x.PlatformType == inputDto.PlatformType);
            if (memberInfo != null) return false;
            var member = new BPA_PlatformMemberInfo()
            {
                Address = inputDto.Address,
                Birthday = inputDto.Birthday,
                CardNum = inputDto.CardNum,
                City = inputDto.City,
                Country = inputDto.Country,
                County = inputDto.County,
                HeadImgUrl = inputDto.HeadImgUrl,
                Level_Id = inputDto.Level_Id,
                MemberInfo_Id = inputDto.MemberInfo_Id,
                NickName = inputDto.NickName,
                Phone = inputDto.Phone,
                PlatformMemberId = Guid.NewGuid().ToString(),
                PlatformType = inputDto.PlatformType,
                Province = inputDto.Province,
                RealName = inputDto.RealName,
                Sex = inputDto.Sex,
                Status = inputDto.Status,
            };
            return await db.Insertable(member).CallEntityMethod(m => m.Create()).ExecuteCommandAsync() > 0;

        }

        /// <summary>
        /// 添加会员账户
        /// </summary>
        /// <param name="memberId"></param>
        /// <returns></returns>
        private async Task<bool> AddMemberAccount(string memberId)
        {
            var result = true;
            var memberAccount = db.Queryable<BPA_MemberAccount>().First(x => x.MemberInfoId == memberId);
            if (memberAccount == null)
            {
                result = await db.Insertable(new BPA_MemberAccount()
                {
                    MemberInfoId = memberId,
                    Money = 0,

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