using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mall.Common.Plugin;
using Mall.Model.Extend.Education;
using Mall.Model.Extend.User;
using Mall.Repository.Education;
using VT.FW.DB;

namespace Mall.Module.Education
{
    public class ActivityModule
    {
        private readonly RB_Education_ActivityRepository education_ActivityRepository = new RB_Education_ActivityRepository();
        private readonly RB_Education_ActivityTypeRepository education_ActivityTypeRepository = new RB_Education_ActivityTypeRepository();
        private readonly RB_Education_ConsultRepository education_ConsultRepository = new RB_Education_ConsultRepository();
        private readonly RB_Education_BaseInfoRepository education_BaseInfoRepository = new RB_Education_BaseInfoRepository();
        private readonly RB_StudentRepository studentRepository = new RB_StudentRepository();
        /// <summary>
        /// 小程序
        /// </summary>
        private readonly Repository.User.RB_MiniProgramRepository miniProgramRepository = new Repository.User.RB_MiniProgramRepository();
        /// <summary>
        /// 会员等级
        /// </summary>
        private readonly Repository.User.RB_Member_GradeRepository member_GradeRepository = new Repository.User.RB_Member_GradeRepository();
        /// <summary>
        /// 点数记录表
        /// </summary>
        private readonly Repository.Point.RB_Member_PointBalanceRepository member_PointBalanceRepository = new Repository.Point.RB_Member_PointBalanceRepository();
        /// <summary>
        /// 用户
        /// </summary>
        private readonly Repository.User.RB_Member_UserRepository member_UserRepository = new Repository.User.RB_Member_UserRepository();
        /// <summary>
        #region 活动分类
        /// <summary>
        /// 获取商会活动类型分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Education_ActivityType_Extend> GetActivityTypePageListRepository(int pageIndex, int pageSize, out long rowsCount, RB_Education_ActivityType_Extend query)
        {
            return education_ActivityTypeRepository.GetActivityTypePageListRepository(pageIndex, pageSize, out rowsCount, query);
        }

        /// <summary>
        /// 获取商会活动类型列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Education_ActivityType_Extend> GetActivityTypeListRepository(RB_Education_ActivityType_Extend query)
        {
            return education_ActivityTypeRepository.GetActivityTypeListRepository(query);
        }


        /// <summary>
        /// 新增修改活动类型
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetActivityTypeModule(RB_Education_ActivityType_Extend model)
        {
            bool flag;
            if (model.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Education_ActivityType_Extend.TypeName),model.TypeName },
                    {nameof(RB_Education_ActivityType_Extend.CoverImage),model.CoverImage },
                    {nameof(RB_Education_ActivityType_Extend.UpdateBy),model.UpdateBy },
                    {nameof(RB_Education_ActivityType_Extend.UpdateDate),model.UpdateDate },
                    {nameof(RB_Education_ActivityType_Extend.LableName),model.LableName },
                    {nameof(RB_Education_ActivityType_Extend.TypeContent),model.TypeContent },

                };
                flag = education_ActivityTypeRepository.Update(fileds, new WhereHelper(nameof(RB_Education_ActivityType_Extend.Id), model.Id));
            }
            else
            {
                var newId = education_ActivityTypeRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
            }
            return flag;
        }

        /// <summary>
        /// 获取活动类型详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public RB_Education_ActivityType_Extend GetActivityTypeModule(object Id)
        {
            return education_ActivityTypeRepository.GetEntity<RB_Education_ActivityType_Extend>(Id);
        }

        /// <summary>
        /// 更新活动类型状态
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="Status"></param>
        /// <returns></returns>
        public bool RemoveActivityTypeModule(int Id, int Status)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Education_ActivityType_Extend.Status),Status },
            };
            bool flag = education_ActivityTypeRepository.Update(fileds, new WhereHelper(nameof(RB_Education_ActivityType_Extend.Id), Id));
            return flag;
        }

        #endregion

        #region 活动
        /// <summary>
        /// 获取商会活动分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <param name="isQuerySignup">是否查询报名名单</param>
        /// <returns></returns>
        public List<RB_Education_Activity_Extend> GetActivityPageListModule(int pageIndex, int pageSize, out long rowsCount, RB_Education_Activity_Extend query, bool isQuerySignup = false)
        {
            var list = education_ActivityRepository.GetCommerceActivityPageListRepository(pageIndex, pageSize, out rowsCount, query);
            if (list != null && isQuerySignup)
            {
                string ids = string.Join(",", list.Select(qitem => qitem.Id));
                List<RB_Education_Consult_Extend> joinList = new List<RB_Education_Consult_Extend>();
                if (!string.IsNullOrEmpty(ids))
                {
                    joinList = education_ConsultRepository.GetCommerceConsultListRepository(new RB_Education_Consult_Extend() { QActivityIds = ids, OrderStatus = 1, EnrollState = 1 });
                }
                foreach (var item in list)
                {
                    item.EducationConsultList = joinList?.Where(qitem => qitem.ActivityId == item.Id)?.ToList() ?? new List<RB_Education_Consult_Extend>();
                }
            }
            return list;
        }

        /// <summary>
        /// 获取当前用户参加商会活动分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Education_Activity_Extend> GetUserActivityPageModule(int pageIndex, int pageSize, out long rowsCount, RB_Education_Activity_Extend query)
        {
            var list = education_ActivityRepository.GetUserCommerceActivityPageRepository(pageIndex, pageSize, out rowsCount, query);

            return list;
        }

        /// <summary>
        /// 新增修改商户活动
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetActivityModule(RB_Education_Activity_Extend model)
        {
            bool flag;
            if (model.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Education_Activity_Extend.ActivityName),model.ActivityName },
                    {nameof(RB_Education_Activity_Extend.StartTime),model.StartTime },
                    {nameof(RB_Education_Activity_Extend.EndTime),model.EndTime },
                    {nameof(RB_Education_Activity_Extend.CoverImg),model.CoverImg },
                    {nameof(RB_Education_Activity_Extend.ActivityType),model.ActivityType },
                    {nameof(RB_Education_Activity_Extend.ActivityInfo),model.ActivityInfo },
                    {nameof(RB_Education_Activity_Extend.UpdateBy),model.UpdateBy },
                    {nameof(RB_Education_Activity_Extend.UpdateDate),model.UpdateDate },
                    {nameof(RB_Education_Activity_Extend.SignStartTime),model.SignStartTime },
                    {nameof(RB_Education_Activity_Extend.SignEndTime),model.SignEndTime },
                    {nameof(RB_Education_Activity_Extend.IsFree),model.IsFree },
                    {nameof(RB_Education_Activity_Extend.Price),model.Price },
                    {nameof(RB_Education_Activity_Extend.IsCancelConfirm),model.IsCancelConfirm },
                    {nameof(RB_Education_Activity_Extend.PointNum),model.PointNum },
                    {nameof(RB_Education_Activity_Extend.AgeLimit),model.AgeLimit },
                    {nameof(RB_Education_Activity_Extend.StartAge),model.StartAge },
                    {nameof(RB_Education_Activity_Extend.EndAge),model.EndAge },
                   // {nameof(RB_Education_Activity_Extend.Label),model.Label },
                    {nameof(RB_Education_Activity_Extend.WoManNum),model.WoManNum },
                      {nameof(RB_Education_Activity_Extend.ManNum),model.ManNum },
                    {nameof(RB_Education_Activity_Extend.Distinguish),model.Distinguish },
                    {nameof(RB_Education_Activity_Extend.LonLat),model.LonLat },
                    {nameof(RB_Education_Activity_Extend.LocationName),model.LocationName },
                    {nameof(RB_Education_Activity_Extend.LnsideLimit),model.LnsideLimit },

                };
                flag = education_ActivityRepository.Update(fileds, new WhereHelper(nameof(RB_Education_Activity_Extend.Id), model.Id));
            }
            else
            {
                var newId = education_ActivityRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
            }

            ////原来的活动详情
            //var oldDetailsList = GetCommerceDetailsListModule(new RB_Commerce_Details_Extend() { ActivityId = model.Id });

            ////以前没有活动详情【直接新增】
            //if (oldDetailsList == null || (oldDetailsList != null && oldDetailsList.Count == 0))
            //{
            //    if (model.CommerceDetailsList != null && model.CommerceDetailsList.Count > 0)
            //    {
            //        foreach (var item in model.CommerceDetailsList)
            //        {
            //            item.ActivityId = model.Id;
            //            detailsRepository.Insert(item);
            //        }
            //    }
            //}
            //else//以前有活动详情
            //{
            //    //现在没有阶梯报价了【直接删除以前的阶梯报价】
            //    if (model.CommerceDetailsList == null || (model.CommerceDetailsList != null && model.CommerceDetailsList.Count == 0))
            //    {
            //        detailsRepository.DeleteCommerceDetailsRepository(model.Id);
            //    }
            //    //找出差异的数据
            //    var deleteList = oldDetailsList.Where(qitem => !model.CommerceDetailsList.Any(oldItem => qitem.ActivityId == oldItem.ActivityId)).ToList();
            //    foreach (var dItem in deleteList)
            //    {
            //        if (dItem.Id > 0)
            //        {
            //            detailsRepository.Delete(dItem.Id);
            //        }
            //    }
            //    foreach (var priceItem in model.CommerceDetailsList)
            //    {
            //        priceItem.ActivityId = model.Id;
            //        if (priceItem.Id == 0)
            //        {
            //            detailsRepository.Insert(priceItem);
            //        }
            //        else
            //        {
            //            detailsRepository.Update(priceItem);
            //        }
            //    }
            //}
            return flag;
        }

        /// <summary>
        /// 获取修改商户活动详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public RB_Education_Activity_Extend GetActivityModule(object Id)
        {
            return education_ActivityRepository.GetEntity<RB_Education_Activity_Extend>(Id);
        }

        /// <summary>
        /// 更新商户活动状态
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="Status"></param>
        /// <returns></returns>
        public bool RemoveActivityModule(int Id, int Status)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Education_Activity_Extend.Status),Status },
            };
            bool flag = education_ActivityRepository.Update(fileds, new WhereHelper(nameof(RB_Education_Activity_Extend.Id), Id));
            return flag;
        }

        #endregion

        #region 活动报名


        /// <summary>
        /// 获取教育用户的基础信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Education_BaseInfo_Extend> GetEducationBaseInfo(RB_Education_BaseInfo_Extend query)
        {
            return education_BaseInfoRepository.GetEducationBaseInfo(query);
        }

        /// <summary>
        /// 更新教育用户的基础信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetEduBaseInfo(RB_Education_BaseInfo_Extend model)
        {
            bool flag = false;
            if (model.Id == 0)
            {
                flag = education_BaseInfoRepository.Insert(model) > 0;
            }
            else
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Education_BaseInfo_Extend.Birthday),model.Birthday },
                    {nameof(RB_Education_BaseInfo_Extend.StudentId),model.StudentId },
                };
                flag = education_BaseInfoRepository.Update(fileds, new WhereHelper(nameof(RB_Education_BaseInfo_Extend.Id), model.Id));
            }
            if (flag && !string.IsNullOrWhiteSpace(model.PhoneNum))
            {
                Dictionary<string, object> keyValuesUser = new Dictionary<string, object>() {
                          { nameof(Model.Entity.User.RB_Member_User.Moblie),model.PhoneNum}
                    };
                List<WhereHelper> wheresUser = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName=nameof(Model.Entity.User.RB_Member_User.Id),
                              FiledValue=model.UserId,
                               OperatorEnum=OperatorEnum.Equal
                        }
                    };
                member_UserRepository.Update(keyValuesUser, wheresUser);
            }
            return flag;
        }


        /// <summary>
        /// 更新教育用户的基础信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdateEduBaseInfoSex(RB_Education_BaseInfo_Extend model)
        {
            bool flag = false;
            if (model.Id == 0)
            {
                flag = education_BaseInfoRepository.Insert(model) > 0;
            }
            else
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Education_BaseInfo_Extend.Sex),model.Sex },
                };
                flag = education_BaseInfoRepository.Update(fileds, new WhereHelper(nameof(RB_Education_BaseInfo_Extend.Id), model.Id));
            }
            return flag;
        }

        /// <summary>
        /// 获取商会活动报名分页列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Education_Consult_Extend> GetCommerceConsultListRepository(RB_Education_Consult_Extend query)
        {
            return education_ConsultRepository.GetCommerceConsultListRepository(query);
        }


        /// <summary>
        /// 获取用户的报名列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Education_Consult_Extend> GetUserJoinActivityPageList(int pageIndex, int pageSize, out long rowsCount, RB_Education_Consult_Extend query)
        {
            return education_ConsultRepository.GetUserJoinActivityPageList(pageIndex, pageSize, out rowsCount, query);
        }

            /// <summary>
            /// 获取活动报名人数
            /// </summary>
            /// <param name="activityId"></param>
            /// <returns></returns>
            public int GetActivityEnrollNum(int activityId, int sex = 0)
        {
            return education_ConsultRepository.GetActivityEnrollNum(activityId, sex);
        }

        /// <summary>
        /// 活动报名
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public int SetActivityEnrollInfo(RB_Education_Consult_Extend demodel, RB_Member_User_Extend umodel)
        {
            int flag = 0;
            //var list = education_ConsultRepository.GetCommerceConsultListRepository(new RB_Education_Consult_Extend() { TenantId = demodel.TenantId, ActivityId = demodel.ActivityId, UserId = demodel.UserId });
            //if (list.Any()) { return "已存在报名信息"; }
            //var model = education_ActivityRepository.GetEntity(demodel.ActivityId);
            //if (model == null || model.Status == Common.Enum.DateStateEnum.Delete) { return "活动不存在"; }
            //if (model.SignStartTime >= DateTime.Now)
            //{
            //    return "报名还未开始，无法报名";
            //}
            //if (model.SignEndTime <= DateTime.Now)
            //{
            //    return "已过了报名时间，无法报名";
            //}

            //var bmodel = education_BaseInfoRepository.GetEducationBaseInfo(new RB_Education_BaseInfo_Extend() { TenantId = demodel.TenantId, UserId = demodel.UserId }).FirstOrDefault();
            //// if (bmodel == null) { return "资料未认证，无法报名"; }
            //if (model.Distinguish == 0)
            //{
            //    if (bmodel == null || bmodel.Sex == 0)
            //    {
            //        return "您的性别保密，无法报名";
            //    }
            //    if (bmodel.Sex == 1)
            //    {
            //        int ManPeopleNum = education_ConsultRepository.GetActivityEnrollNum(demodel.Id, 1);
            //        if (model.ManNum <= ManPeopleNum) { return "已报满，无法报名"; }
            //    }
            //    else if (bmodel.Sex == 2)
            //    {
            //        int WoManPeopleNum = education_ConsultRepository.GetActivityEnrollNum(demodel.Id, 2);
            //        if (model.WoManNum <= WoManPeopleNum) { return "已报满，无法报名"; }
            //    }
            //    else
            //    {
            //        return "性别未维护，无法报名";
            //    }
            //}
            //else
            //{
            //    int ManPeopleNum = education_ConsultRepository.GetActivityEnrollNum(demodel.Id, 0);
            //    if (model.ManNum <= ManPeopleNum) { return "已报满，无法报名"; }
            //}
            //if (model.AgeLimit == 0)
            //{
            //    if (bmodel == null || string.IsNullOrWhiteSpace(bmodel.Birthday))
            //    {
            //        return "您未绑定学员信息无法获取到年龄，无法报名";
            //    }
            //    int Age = Convert.ToInt32(Common.Plugin.StringHelper.GetAge(bmodel.Birthday));
            //    if (model.StartAge > 0 && model.EndAge > 0)
            //    {
            //        if (Age < model.StartAge || Age > model.EndAge)
            //        {
            //            return $"年龄限制在{model.StartAge}-{model.EndAge}岁，无法报名";
            //        }
            //    }
            //    else if (model.StartAge > 0 && model.EndAge == 0)
            //    {
            //        if (Age < model.StartAge)
            //        {
            //            return $"年龄必须大于{model.StartAge}岁，无法报名";
            //        }
            //    }
            //    else if (model.StartAge == 0 && model.EndAge > 0)
            //    {
            //        if (Age > model.EndAge)
            //        {
            //            return $"年龄必须小于{model.EndAge}岁，无法报名";
            //        }

            //    }
            //}

            //demodel.Sex = bmodel.Sex;
            //判断当前人的点数
            if (demodel.PaymentWay == Common.Enum.Goods.OrderPaymentTypeEnum.PayPoint)
            {
                var trans = education_ConsultRepository.DbTransaction;
                //var umodel = member_UserRepository.GetEntity(demodel.UserId);
                //if (umodel == null || umodel.Id == 0)
                //{
                //    return "用户信息不存在";
                //}
                //if (model.PointNum != demodel.TotalPoint)
                //{
                //    if (umodel.PointNum < model.PointNum)
                //    {
                //        return "您的星星值不足，请充值后再试";
                //    }
                //}
                //demodel.OrderSource = umodel.Source;
                //demodel.PaymentTime = System.DateTime.Now;
                //demodel.OrderStatus = 1;
                try
                {
                    flag = education_ConsultRepository.Insert(demodel, trans);

                    if (flag > 0)
                    {
                        if (demodel.TotalPoint > 0)
                        {
                            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(Model.Extend.User.RB_Member_User_Extend.PointNum),umodel.PointNum - demodel.TotalPoint}
                        };
                            List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Member_User_Extend.Id),
                                  FiledValue=umodel.Id,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                            member_UserRepository.Update(keyValues, wheres, trans);
                            member_PointBalanceRepository.Insert(new Model.Entity.User.RB_Member_PointBalance()
                            {
                                Id = 0,
                                UserId = umodel.Id,
                                Type = Common.Enum.MarketingCenter.RecordTypeEnum.Expend,
                                TenantId = umodel.TenantId,
                                OrderId = 0,
                                PlatformType = Common.Enum.User.UserSourceEnum.WeiXin,
                                MallBaseId = umodel.MallBaseId,
                                PonitNum = demodel.TotalPoint,
                                CreateDate = DateTime.Now,
                                Description = "活动报名，使用点数：" + demodel.TotalPoint,
                                Remarks = "活动报名，使用点数：" + demodel.TotalPoint,
                            }, trans);
                        }
                    }
                    education_ConsultRepository.DBSession.Commit();
                }
                catch (Exception ex)
                {
                    LogHelper.Write(ex, "SetActivityEnrollInfo");
                    education_ConsultRepository.DBSession.Rollback("SetActivityEnrollInfo");
                    return 0;

                }
            }
            else if (demodel.PaymentWay == Common.Enum.Goods.OrderPaymentTypeEnum.OnlinePayment)
            {
                flag = education_ConsultRepository.Insert(demodel);
            }
            return flag;
        }

        /// <summary>
        /// 修改会员购买
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdateActivityEnroll(int UserId, int OrderId, string Out_Trade_No, string Transaction_Id, Common.Enum.Goods.OrderPayTypeEnum PayWay, decimal Money, DateTime Time_End)
        {
            var umodel = member_UserRepository.GetEntity(UserId);
            if (umodel == null)
            {
                return false;
            }
            //判断订单状态是否是待支付  2020-06-16 Add By:W
            var model = education_ConsultRepository.GetEntity(OrderId);
            if (model == null)
            {
                return false;
            }
            if (model.OrderStatus != 0)
            {
                return false;
            }
            if (model.Money != Money)
            {
                return false;
            }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Education_Consult_Extend.PaymentTime),Time_End},
                     { nameof(RB_Education_Consult_Extend.OrderStatus),1},
                       { nameof(RB_Education_Consult_Extend.OrderNo),Out_Trade_No},
                         { nameof(RB_Education_Consult_Extend.MerchantsNo),Transaction_Id}
                };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper{
                         FiledName=nameof(RB_Education_Consult_Extend.Id),
                          FiledValue=OrderId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
            bool flag = education_ConsultRepository.Update(keyValues, wheres);//更新会员报名支付状态
            return flag;
        }





        /// <summary>
        /// 客人申请取消
        /// </summary>
        /// <param name="id"></param>
        /// <param name="applyForCancelStatus"></param>
        /// <param name="rejectRemark"></param>
        /// <returns></returns>
        public bool SetCommerceConsultApplyCancel(int id, int applyForCancelStatus, string rejectRemark, string refundid)
        {
            var model = education_ConsultRepository.GetEntity(id);
            if (model == null || model.Status == Common.Enum.DateStateEnum.Delete) { return false; }
            int Status = 0;
            if (applyForCancelStatus == 1)
            {
                Status = 1;
            }
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Education_Consult_Extend.Status),Status },
                 {nameof(RB_Education_Consult_Extend.RefundTime),System.DateTime.Now },
                {nameof(RB_Education_Consult_Extend.ApplyForCancelStatus),applyForCancelStatus },
                {nameof(RB_Education_Consult_Extend.RejectRemark),rejectRemark },
            };
            if (!string.IsNullOrWhiteSpace(refundid))
            {
                fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Education_Consult_Extend.Status),Status },
                     {nameof(RB_Education_Consult_Extend.RefundTime),System.DateTime.Now },
                    {nameof(RB_Education_Consult_Extend.ApplyForCancelStatus),applyForCancelStatus },
                    {nameof(RB_Education_Consult_Extend.RejectRemark),rejectRemark },
                    {nameof(RB_Education_Consult_Extend.RefundOrderNo),refundid },
                };
            }
            List<WhereHelper> list = new List<WhereHelper>()
            {
                new WhereHelper(nameof(RB_Education_Consult_Extend.Id), id),
            };
            bool flag = education_ConsultRepository.Update(fileds, list);
            if (flag)
            {
                if (model.OrderStatus == 1 && model.TotalPoint > 0 && model.PaymentWay == Common.Enum.Goods.OrderPaymentTypeEnum.PayPoint)
                {
                    var umodel = member_UserRepository.GetEntity(model.UserId);
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Member_User_Extend.PointNum),umodel.PointNum + model.TotalPoint}
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                                FiledName=nameof(RB_Member_User_Extend.Id),
                                FiledValue=umodel.Id,
                                OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    member_UserRepository.Update(keyValues, wheres);
                    member_PointBalanceRepository.Insert(new Model.Entity.User.RB_Member_PointBalance()
                    {
                        Id = 0,
                        UserId = umodel.Id,
                        Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income,
                        TenantId = umodel.TenantId,
                        OrderId = 0,
                        PlatformType = Common.Enum.User.UserSourceEnum.WeiXin,
                        MallBaseId = umodel.MallBaseId,
                        PonitNum = model.TotalPoint,
                        CreateDate = DateTime.Now,
                        Description = "取消活动报名，退回使用点数：" + model.TotalPoint,
                        Remarks = "取消活动报名，退回使用点数：" + model.TotalPoint,
                    });
                }
            }
            return flag;
        }


        /// <summary>
        /// 获取小程序信息
        /// </summary>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public RB_MiniProgram_Extend GetMiniProgramExtend(int mallBaseId)
        {
            return miniProgramRepository.GetEntity<RB_MiniProgram_Extend>(mallBaseId);
        }





        /// <summary>
        /// 取消商会活动报名状态
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="Status"></param>
        /// <returns></returns>
        public bool CancelCommerceConsultModule(int activityId, string cancelRemark, out int IsCancelConfirm, int userId, string refundid, RB_Education_Consult_Extend cmodel)
        {
            bool flag;
          //  var cmodel = education_ConsultRepository.GetCommerceConsultListRepository(new RB_Education_Consult_Extend() { ActivityId = activityId, UserId = userId }).FirstOrDefault();
            IsCancelConfirm = cmodel.IsCancelConfirm;
            if (cmodel == null || cmodel.Status == Common.Enum.DateStateEnum.Delete) { return true; }
            if (cmodel.IsCancelConfirm == 1)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Education_Consult_Extend.IsApplyForCancel),1 },
                    {nameof(RB_Education_Consult_Extend.CancelRemark),cancelRemark },
                };
                List<WhereHelper> list = new List<WhereHelper>()
                {
                    new WhereHelper(nameof(RB_Education_Consult_Extend.Id), cmodel.Id)
                };
                flag = education_ConsultRepository.Update(fileds, list);
            }
            else
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Education_Consult_Extend.Status),1 },
                     {nameof(RB_Education_Consult_Extend.RefundTime),System.DateTime.Now },
                };
                if (!string.IsNullOrWhiteSpace(refundid))
                {
                    fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Education_Consult_Extend.Status),1 },
                     {nameof(RB_Education_Consult_Extend.RefundOrderNo),refundid },
                     {nameof(RB_Education_Consult_Extend.RefundTime),System.DateTime.Now },
                };
                }
                List<WhereHelper> list = new List<WhereHelper>()
                {
                    new WhereHelper(nameof(RB_Education_Consult_Extend.ActivityId), activityId),
                    new WhereHelper(nameof(RB_Education_Consult_Extend.UserId), userId),
                     new WhereHelper(nameof(RB_Education_Consult_Extend.Id), cmodel.Id),
                    
                };
                flag = education_ConsultRepository.Update(fileds, list);
                if (flag && cmodel.OrderStatus == 1 && cmodel.TotalPoint > 0 && cmodel.PaymentWay == Common.Enum.Goods.OrderPaymentTypeEnum.PayPoint)
                {
                    //取消退回使用点数
                    var umodel = member_UserRepository.GetEntity(cmodel.UserId);
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Member_User_Extend.PointNum),umodel.PointNum + cmodel.TotalPoint}
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                                FiledName=nameof(RB_Member_User_Extend.Id),
                                FiledValue=umodel.Id,
                                OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    member_UserRepository.Update(keyValues, wheres);
                    member_PointBalanceRepository.Insert(new Model.Entity.User.RB_Member_PointBalance()
                    {
                        Id = 0,
                        UserId = umodel.Id,
                        Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income,
                        TenantId = umodel.TenantId,
                        OrderId = 0,
                        PlatformType = Common.Enum.User.UserSourceEnum.WeiXin,
                        MallBaseId = umodel.MallBaseId,
                        PonitNum = cmodel.TotalPoint,
                        CreateDate = DateTime.Now,
                        Description = "取消活动报名，退回使用点数：" + cmodel.TotalPoint,
                        Remarks = "取消活动报名，退回使用点数：" + cmodel.TotalPoint,
                    });
                }
            }
            return flag;
        }


        #endregion


        #region 教育学生信息
        /// <summary>
        /// 获取学生列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Student> GetStudentList(RB_Student query)
        {
            return studentRepository.GetStudentList(query);
        }




        /// <summary>
        /// 分页列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowCount">总条数</param>
        /// <param name="dmodel">查询条件</param>
        /// <returns></returns>
        public List<RB_Member_User_Extend> GetEduPageList(int pageIndex, int pageSize, out long rowCount, RB_Member_User_Extend dmodel)
        {
            var list = member_UserRepository.GetEduPageList(pageIndex, pageSize, out rowCount, dmodel);
            if (list.Any())
            {
                List<RB_Member_Grade_Extend> gradeList = new List<RB_Member_Grade_Extend>();
                if (list.Where(x => x.MemberGrade > 0).Any())
                {
                    var gradeIds = string.Join(",", list.Where(x => x.MemberGrade > 0).Select(x => x.MemberGrade ?? 0));
                    gradeList = member_GradeRepository.GetList(new RB_Member_Grade_Extend() { GradeIds = gradeIds, TenantId = dmodel.TenantId, MallBaseId = dmodel.MallBaseId });
                }
                foreach (var item in list)
                {
                    if (item.MemberGrade > 0)
                    {
                        item.MemberGradeName = gradeList.Where(x => x.Id == item.MemberGrade).FirstOrDefault()?.Name ?? "";
                    }
                    else
                    {
                        item.MemberGradeName = "普通会员";
                    }
                }
            }
            return list;
        }




        /// <summary>
        /// 分页列表
        /// </summary>
        /// <param name="dmodel">查询条件</param>
        /// <returns></returns>
        public List<RB_Member_User_Extend> GetEduList(RB_Member_User_Extend dmodel)
        {
            var list = member_UserRepository.GetEduList(dmodel);
            if (list.Any())
            {
                List<RB_Member_Grade_Extend> gradeList = new List<RB_Member_Grade_Extend>();
                if (list.Where(x => x.MemberGrade > 0).Any())
                {
                    var gradeIds = string.Join(",", list.Where(x => x.MemberGrade > 0).Select(x => x.MemberGrade ?? 0));
                    gradeList = member_GradeRepository.GetList(new RB_Member_Grade_Extend() { GradeIds = gradeIds, TenantId = dmodel.TenantId, MallBaseId = dmodel.MallBaseId });
                }
                foreach (var item in list)
                {
                    if (item.MemberGrade > 0)
                    {
                        item.MemberGradeName = gradeList.Where(x => x.Id == item.MemberGrade).FirstOrDefault()?.Name ?? "";
                    }
                    else
                    {
                        item.MemberGradeName = "普通会员";
                    }
                }
            }
            return list;
        }

        #endregion

    }
}
