using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mall.Common;
using Mall.Common.Enum.Education;
using Mall.Common.Enum.Finance;
using Mall.Common.Plugin;
using Mall.Model.Extend.Education;
using Mall.Model.Extend.Finance;
using Mall.Model.Extend.User;
using Mall.Repository.Education;
using Mall.Repository.Finance;
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>
        /// 活动总结图片
        /// </summary>
        private readonly RB_Education_ActivitySummaryFileRepository education_ActivitySummaryFileRepository = new RB_Education_ActivitySummaryFileRepository();


        /// <summary>
        /// 活动总结图片分组
        /// </summary>
        private readonly RB_Education_ActivitySummaryGroupRepository education_ActivitySummaryGroupRepository = new RB_Education_ActivitySummaryGroupRepository();

        /// <summary>
        /// 财务单据配置
        /// </summary>
        private readonly RB_Finance_ConfigRepository finance_ConfigRepository = new RB_Finance_ConfigRepository();

        /// <summary>
        /// 财务单据线上支付详情仓储层
        /// </summary>
        private readonly RB_Online_Trade_DetailRepository OnlineTradeDetailRepository = new RB_Online_Trade_DetailRepository();

        /// <summary>
        /// 教育创建人
        /// </summary>
        private readonly RB_AccountRepository RB_AccountRepository = new RB_AccountRepository();


        /// <summary>
        /// 财务单据
        /// </summary>
        private readonly RB_FinanceRepository financeRepository = new RB_FinanceRepository();

        /// <summary>
        /// 交易方式
        /// </summary>
        private readonly RB_TradeWayRepository tradeWayRepository = new RB_TradeWayRepository();

        /// <summary>
        /// 现金账户
        /// </summary>
        private readonly RB_CashAccountRepository cashAccountRepository = new RB_CashAccountRepository();


        /// <summary>
        /// 平台账户仓储层对象
        /// </summary>
        private readonly RB_PlatformAccountRepository platformAccountRepository = new RB_PlatformAccountRepository();

        /// <summary>
        /// 资金池账户仓储层对象
        /// </summary>
        private readonly RB_CashPoolAccountRepository cashPoolAccountRepository = new RB_CashPoolAccountRepository();

        /// <summary>
        /// 财务单据详情
        /// </summary>
        private readonly RB_FinanceDetailRepository RB_FinanceDetailRepository = new RB_FinanceDetailRepository();

        /// <summary>
        /// 费用类型仓储层对象
        /// </summary>
        private readonly RB_CosttypeRepository costtypeRepository = new RB_CosttypeRepository();

        /// <summary>
        /// 财务单据模板
        /// </summary>
        private readonly Repository.Finance.Rb_Workflow_TemplateRepository Finance_TemplateRepository = new Repository.Finance.Rb_Workflow_TemplateRepository();

        /// <summary>
        /// 财务单据凭证仓储层对象
        /// </summary>
        private readonly RB_VoucherRepository voucherRepository = new RB_VoucherRepository();
        /// <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>
        /// <param name="isQuerySignup">是否查询报名名单</param>
        /// <returns></returns>
        public List<RB_Education_Activity_Extend> GetActivityPageListModule_V2(int pageIndex, int pageSize, out long rowsCount, RB_Education_Activity_Extend query, bool isQuerySignup = false)
        {
            var list = education_ActivityRepository.GetCommerceActivityPageListRepository_V2(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;
        }
        /// <summary>
        /// 更新商户总结
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="Status"></param>
        /// <returns></returns>
        public bool UpdateSummaryActivityModule(int Id, string Summary)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Education_Activity_Extend.Summary),Summary },
            };
            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="query"></param>
        /// <returns></returns>
        public List<RB_Education_Consult_Extend> GetCommerceConsultListRepository_V2(RB_Education_Consult_Extend query)
        {
            var list = education_ConsultRepository.GetCommerceConsultListRepository_V2(query);
            if (list.Any() && list.Any())
            {
                List<RB_Finance_Extend> flist = new List<RB_Finance_Extend>();
                string orderIds = string.Join(",", list.Select(x => x.Id));
                flist = financeRepository.GetListJH(new RB_Finance_Extend() { ReFinanceIds2 = orderIds });
                if (flist != null && flist.Any())
                {
                    foreach (var item in list)
                    {
                        item.FinanceList = new List<RB_Finance_Extend>();
                        item.FinanceList = flist.Where(x => x.ReFinanceId2 == item.Id).ToList();
                        if (item.FinanceList == null || !item.FinanceList.Any())
                        {
                            item.FinanceList = new List<RB_Finance_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_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);//更新会员报名支付状态
            if (flag)//状态更新成功生成财务单据 2021-06-21 Add by:W
            {
                var financeConfig = finance_ConfigRepository.GetList(new Model.Entity.Education.RB_Finance_Config { Id = Convert.ToInt32(Config.EduActivityIncomeFinanceId), Type = FinanceConfigTypeEnum.ActivityIncome }).FirstOrDefault();
                if (financeConfig == null)
                {
                    LogHelper.WriteInfo("活动财务配置不存在");
                    financeConfig = new Model.Entity.Education.RB_Finance_Config();
                }


                var miniProgramModel = GetMiniProgramExtend(model.MallBaseId);
                var userInfo = RB_AccountRepository.GetEmployeeListRepository(new Employee_ViewModel { Id = financeConfig.CreateBy, Group_Id = financeConfig.Group_Id }).ToList().FirstOrDefault();
                var OriginalFee = Math.Round((Convert.ToDecimal(Config.SettlementRate) / 100) * (Convert.ToDecimal(model.Money)), 2, MidpointRounding.AwayFromZero);//手续费
                Model.Entity.Finance.RB_Online_Trade_Detail model1 = new Model.Entity.Finance.RB_Online_Trade_Detail();
                #region 财务单据数据组装
                var detailList = new List<object>
                    {
                        new
                        {
                            CostTypeId = financeConfig?.CostTypeId ?? 0,
                            Number = 1,//model.PeopleNum,
                            OriginalMoney = Convert.ToDecimal(model.Money) ,
                            UnitPrice = Convert.ToDecimal(model.Money) ,
                            Remark = "微信昵称："+umodel.Name +"活动id："+ model.ActivityId + "订单号："+Out_Trade_No
                        }
                    };

                var financeObj = new
                {
                    IsPublic = 1,
                    BType = 1,//item.AccountType,
                    AccountId = financeConfig?.ClientID ?? 0,
                    WBMoney = Convert.ToDecimal(model.Money),
                    TradeDate = Time_End,
                    AccountNumber = System.DateTime.Now.AddDays(-1).ToString("yyyyMMdd"),
                    TemplateId = financeConfig?.TempleteId ?? 0,
                    OrderSource = 17,
                    Remark = System.DateTime.Now.ToString("yyyy年MM月dd日") + "自动生成财务单据",
                    detailList,
                    OriginalFee,
                    CreateBy = userInfo.Id,
                    RemitterName = umodel.Name,
                    RB_Branch_Id = userInfo.School_Id,
                    RB_Group_Id = userInfo.Group_Id,
                    RB_Depart_Id = userInfo.Dept_Id,
                    RB_CreateByName = userInfo.EmployeeName,
                    RB_DepartName = userInfo.DeptName,
                    RB_BranchName = userInfo.SchoolName,
                    RB_GroupName = userInfo.GroupName,
                    FinanceType = 2,
                    OtherType = 40,
                    ReFinanceId = model.ActivityId,
                    ReFinanceId2 = model.Id
                };
                #endregion

                string sign = EncryptionHelper.AesEncrypt(JsonHelper.Serialize(financeObj), Config.FinanceKey);
                var resultInfo = new
                {
                    msg = sign,
                };
                string apiResult = Common.Plugin.HttpHelper.HttpPost(Config.ReadConfigKey("IncomeFinanceApi"), JsonHelper.Serialize(resultInfo), "");
                Newtonsoft.Json.Linq.JObject parmsJob = Newtonsoft.Json.Linq.JObject.Parse(apiResult);
                LogHelper.WriteInfo("活动收入财务单据结果：" + JsonHelper.Serialize(parmsJob));
                string resultCode = parmsJob.GetStringValue("resultCode");
                int frid = parmsJob.GetInt("data", 0);
                if (resultCode == "1" && frid > 0)//新增记录
                {

                    model1 = new Model.Entity.Finance.RB_Online_Trade_Detail
                    {
                        ID = 0,
                        Type = 1,
                        OrderSource = 17,
                        OrderId = model.Id,
                        Pay_Order = "",
                        Trade_Order = Out_Trade_No,
                        Third_Order = Transaction_Id,
                        Money = Convert.ToDecimal(model.Money),
                        Pay_Way = 1,
                        Interface_Company = 0,
                        Version = "",
                        Mch_Id = miniProgramModel.WeChatPayMerchants,
                        User_Id = model.UserId.ToString(),
                        Is_follow = 0,
                        AppId = miniProgramModel.MiniAppId,
                        OpenId = umodel.OpenId ?? "",
                        Currency_Type = "CNY",
                        Institution_Type = "",
                        Card_Type = 0,
                        Remarks = "甲鹤活动收入财务单据id：" + frid + "活动报名id:" + model.Id,
                        Pay_Result = 0,
                        Pay_Date = Time_End,
                        Payer_Id = model.UserId,
                        Payer_Type = 0,
                        Data_Source = frid,
                        RB_Group_Id = financeConfig.Group_Id,
                        RB_Branch_Id = financeConfig.School_Id,
                        IsRefund = 0,
                        RefundTrade_Order = "",
                        RefundMoney = 0,
                        RefundStatus = 0,
                        FinanceId = 0,

                    };

                    OnlineTradeDetailRepository.Insert(model1);
                }

            }

            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,
                    });
                }

                else
                {

                    if (!string.IsNullOrWhiteSpace(refundid))
                    {
                        if (flag)//状态更新成功生成财务单据 2021-06-21 Add by:W
                        {
                            var financeConfig = finance_ConfigRepository.GetList(new Model.Entity.Education.RB_Finance_Config { Id = Convert.ToInt32(Config.EduActivityExpendFinanceId), Type = FinanceConfigTypeEnum.ActivityExpenditure }).FirstOrDefault();
                            if (financeConfig == null)
                            {
                                financeConfig = new Model.Entity.Education.RB_Finance_Config();
                            }


                            var miniProgramModel = GetMiniProgramExtend(model.MallBaseId);
                            var userInfo = RB_AccountRepository.GetEmployeeListRepository(new Employee_ViewModel { Id = financeConfig.CreateBy, Group_Id = financeConfig.Group_Id }).ToList().FirstOrDefault();
                            var OriginalFee = Math.Round((Convert.ToDecimal(Config.SettlementRate) / 100) * (Convert.ToDecimal(model.Money)), 2, MidpointRounding.AwayFromZero);//手续费
                            Model.Entity.Finance.RB_Online_Trade_Detail model1 = new Model.Entity.Finance.RB_Online_Trade_Detail();
                            #region 财务单据数据组装
                            var detailList = new List<object>
                    {
                        new
                        {
                            CostTypeId = financeConfig?.CostTypeId ?? 0,
                            Number = 1,//model.PeopleNum,
                            OriginalMoney = Convert.ToDecimal(model.Money) ,
                            UnitPrice = Convert.ToDecimal(model.Money) ,
                            Remark ="活动退款,报名订单号："+model.OrderNo+",活动id："+model.ActivityId
                        }
                    };
                            var umodel = member_UserRepository.GetEntity(model.UserId);
                            var financeObj = new
                            {
                                ClientType = 0,
                                ClientID = 0,
                                IsPublic = 8,
                                CurrencyId = financeConfig.CurrencyId,
                                BType = 1,
                                WBMoney = Convert.ToDecimal(model.Money),
                                PayDate = DateTime.Now.ToString("yyyy-MM-dd"),
                                TemplateId = financeConfig?.TempleteId ?? 0,
                                OrderSource = 17,
                                Remark = System.DateTime.Now.ToString("yyyy年MM月dd日") + "自动生成财务单据",
                                detailList,
                                CreateBy = userInfo.Id,
                                RemitterName = umodel.Name,
                                RB_Branch_Id = userInfo.School_Id,
                                RB_Group_Id = userInfo.Group_Id,
                                RB_Depart_Id = userInfo.Dept_Id,
                                RB_CreateByName = userInfo.EmployeeName,
                                RB_DepartName = userInfo.DeptName,
                                RB_BranchName = userInfo.SchoolName,
                                RB_GroupName = userInfo.GroupName,
                                FinanceType = 2,
                                OtherType = 40,
                                ReFinanceId = model.ActivityId,
                                ReFinanceId2 = model.Id
                            };
                            #endregion

                            string sign = EncryptionHelper.AesEncrypt(JsonHelper.Serialize(financeObj), Config.FinanceKey);
                            var resultInfo = new
                            {
                                msg = sign,
                            };
                            string apiResult = Common.Plugin.HttpHelper.HttpPost(Config.ReadConfigKey("PaymentFinanceApi"), JsonHelper.Serialize(resultInfo), "");
                            Newtonsoft.Json.Linq.JObject parmsJob = Newtonsoft.Json.Linq.JObject.Parse(apiResult);
                            string resultCode = parmsJob.GetStringValue("resultCode");
                            int frid = parmsJob.GetInt("data", 0);
                            if (resultCode == "1" && frid > 0)//新增记录
                            {

                                model1 = new Model.Entity.Finance.RB_Online_Trade_Detail
                                {
                                    ID = 0,
                                    Type = 2,
                                    OrderSource = 17,
                                    OrderId = model.Id,
                                    Pay_Order = "",
                                    Trade_Order = model.OrderNo + 1,
                                    Third_Order = refundid,
                                    Money = Convert.ToDecimal(model.Money),
                                    Pay_Way = 1,
                                    Interface_Company = 0,
                                    Version = "",
                                    Mch_Id = miniProgramModel.WeChatPayMerchants,
                                    User_Id = model.UserId.ToString(),
                                    Is_follow = 0,
                                    AppId = miniProgramModel.MiniAppId,
                                    OpenId = umodel.OpenId ?? "",
                                    Currency_Type = "CNY",
                                    Institution_Type = "",
                                    Card_Type = 0,
                                    Remarks = "甲鹤活动退款财务单据id：" + frid + "活动报名id:" + model.Id,
                                    Pay_Result = 0,
                                    Pay_Date = System.DateTime.Now,
                                    Payer_Id = model.UserId,
                                    Payer_Type = 0,
                                    Data_Source = frid,
                                    RB_Group_Id = financeConfig.Group_Id,
                                    RB_Branch_Id = financeConfig.School_Id,
                                    IsRefund = 0,
                                    RefundTrade_Order = "",
                                    RefundMoney = 0,
                                    RefundStatus = 0,
                                    FinanceId = 0,

                                };

                                OnlineTradeDetailRepository.Insert(model1);
                            }

                        }
                    }
                }
            }
            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)
                {
                    if (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,
                        });
                    }
                    else
                    {

                        if (!string.IsNullOrWhiteSpace(refundid))
                        {
                            if (flag)//状态更新成功生成财务单据 2021-06-21 Add by:W
                            {
                                var financeConfig = finance_ConfigRepository.GetList(new Model.Entity.Education.RB_Finance_Config { Id = Convert.ToInt32(Config.EduActivityExpendFinanceId), Type = FinanceConfigTypeEnum.ActivityExpenditure }).FirstOrDefault();
                                if (financeConfig == null)
                                {
                                    financeConfig = new Model.Entity.Education.RB_Finance_Config();
                                }


                                var miniProgramModel = GetMiniProgramExtend(cmodel.MallBaseId);
                                var userInfo = RB_AccountRepository.GetEmployeeListRepository(new Employee_ViewModel { Id = financeConfig.CreateBy, Group_Id = financeConfig.Group_Id }).ToList().FirstOrDefault();
                                var OriginalFee = Math.Round((Convert.ToDecimal(Config.SettlementRate) / 100) * (Convert.ToDecimal(cmodel.Money)), 2, MidpointRounding.AwayFromZero);//手续费
                                Model.Entity.Finance.RB_Online_Trade_Detail model1 = new Model.Entity.Finance.RB_Online_Trade_Detail();
                                #region 财务单据数据组装
                                var detailList = new List<object>
                    {
                        new
                        {
                            CostTypeId = financeConfig?.CostTypeId ?? 0,
                            Number = 1,//model.PeopleNum,
                            OriginalMoney = Convert.ToDecimal(cmodel.Money) ,
                            UnitPrice = Convert.ToDecimal(cmodel.Money) ,
                             Remark ="活动退款,报名订单号："+cmodel.OrderNo+",活动id："+cmodel.ActivityId
                        }
                    };
                                var umodel = member_UserRepository.GetEntity(cmodel.UserId);
                                var financeObj = new
                                {
                                    ClientType = 0,
                                    ClientID = 0,
                                    IsPublic = 8,
                                    CurrencyId = financeConfig.CurrencyId,
                                    BType = 1,
                                    WBMoney = Convert.ToDecimal(cmodel.Money),
                                    PayDate = DateTime.Now.ToString("yyyy-MM-dd"),
                                    TemplateId = financeConfig?.TempleteId ?? 0,
                                    OrderSource = 17,
                                    Remark = System.DateTime.Now.ToString("yyyy年MM月dd日") + "自动生成财务单据",
                                    detailList,
                                    CreateBy = userInfo.Id,
                                    RemitterName = umodel.Name,
                                    RB_Branch_Id = userInfo.School_Id,
                                    RB_Group_Id = userInfo.Group_Id,
                                    RB_Depart_Id = userInfo.Dept_Id,
                                    RB_CreateByName = userInfo.EmployeeName,
                                    RB_DepartName = userInfo.DeptName,
                                    RB_BranchName = userInfo.SchoolName,
                                    RB_GroupName = userInfo.GroupName,
                                    FinanceType = 2,
                                    OtherType = 40,
                                    ReFinanceId = cmodel.ActivityId,
                                    ReFinanceId2 = cmodel.Id
                                };
                                #endregion

                                string sign = EncryptionHelper.AesEncrypt(JsonHelper.Serialize(financeObj), Config.FinanceKey);
                                var resultInfo = new
                                {
                                    msg = sign,
                                };
                                string apiResult = Common.Plugin.HttpHelper.HttpPost(Config.ReadConfigKey("PaymentFinanceApi"), JsonHelper.Serialize(resultInfo), "");
                                Newtonsoft.Json.Linq.JObject parmsJob = Newtonsoft.Json.Linq.JObject.Parse(apiResult);
                                string resultCode = parmsJob.GetStringValue("resultCode");
                                int frid = parmsJob.GetInt("data", 0);
                                if (resultCode == "1" && frid > 0)//新增记录
                                {

                                    model1 = new Model.Entity.Finance.RB_Online_Trade_Detail
                                    {
                                        ID = 0,
                                        Type = 2,
                                        OrderSource = 17,
                                        OrderId = cmodel.Id,
                                        Pay_Order = "",
                                        Trade_Order = cmodel.OrderNo + 1,
                                        Third_Order = refundid,
                                        Money = Convert.ToDecimal(cmodel.Money),
                                        Pay_Way = 1,
                                        Interface_Company = 0,
                                        Version = "",
                                        Mch_Id = miniProgramModel.WeChatPayMerchants,
                                        User_Id = cmodel.UserId.ToString(),
                                        Is_follow = 0,
                                        AppId = miniProgramModel.MiniAppId,
                                        OpenId = umodel.OpenId ?? "",
                                        Currency_Type = "CNY",
                                        Institution_Type = "",
                                        Card_Type = 0,
                                        Remarks = "甲鹤活动退款财务单据id：" + frid + "活动报名id:" + cmodel.Id,
                                        Pay_Result = 0,
                                        Pay_Date = System.DateTime.Now,
                                        Payer_Id = cmodel.UserId,
                                        Payer_Type = 0,
                                        Data_Source = frid,
                                        RB_Group_Id = financeConfig.Group_Id,
                                        RB_Branch_Id = financeConfig.School_Id,
                                        IsRefund = 0,
                                        RefundTrade_Order = "",
                                        RefundMoney = 0,
                                        RefundStatus = 0,
                                        FinanceId = 0,

                                    };

                                    OnlineTradeDetailRepository.Insert(model1);
                                }

                            }
                        }
                    }

                }
            }
            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




        #region 活动总结

        /// <summary>
        /// 分页列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowCount">总条数</param>
        /// <param name="dmodel">查询条件</param>
        /// <returns></returns>
        public List<RB_Education_ActivitySummaryGroup_Extend> GetActivitySummaryGroupPageList(int pageIndex, int pageSize, out long rowCount, RB_Education_ActivitySummaryGroup_Extend dmodel)
        {
            return education_ActivitySummaryGroupRepository.GetPageList(pageIndex, pageSize, out rowCount, dmodel);
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Education_ActivitySummaryGroup_Extend> GetActivitySummaryGroupList(RB_Education_ActivitySummaryGroup_Extend dmodel)
        {
            return education_ActivitySummaryGroupRepository.GetList(dmodel);
        }




        /// <summary>
        /// 新增分组
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetActivitySummaryGroupInfo(RB_Education_ActivitySummaryGroup_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Education_ActivitySummaryGroup_Extend.Name),demodel.Name},
                    { nameof(RB_Education_ActivitySummaryGroup_Extend.Sort),demodel.Sort},
                    { nameof(RB_Education_ActivitySummaryGroup_Extend.UpdateDate),demodel.UpdateDate},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                     FiledName=nameof(RB_Education_ActivitySummaryGroup_Extend.Id),
                      FiledValue=demodel.Id,
                       OperatorEnum=OperatorEnum.Equal
                    }
                };
                return education_ActivitySummaryGroupRepository.Update(keyValues, wheres);
            }
            else
            {
                return education_ActivitySummaryGroupRepository.Insert(demodel) > 0;
            }
        }



        /// <summary>
        /// 设置素材信息
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetMaterialInfo(RB_Education_ActivitySummaryFile_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Education_ActivitySummaryFile_Extend.Name),demodel.Name},
                    { nameof(RB_Education_ActivitySummaryFile_Extend.UpdateDate),demodel.UpdateDate},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                     FiledName=nameof(RB_Education_ActivitySummaryFile_Extend.Id),
                      FiledValue=demodel.Id,
                       OperatorEnum=OperatorEnum.Equal
                    }
                };
                return education_ActivitySummaryFileRepository.Update(keyValues, wheres);
            }
            else
            {
                return education_ActivitySummaryFileRepository.Insert(demodel) > 0;
            }
        }



        /// <summary>
        /// 删除分组
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="uid"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool DelMaterialGroupInfo(int groupId, string uid, int mallBaseId)
        {
            var gmodel = education_ActivitySummaryGroupRepository.GetEntity(groupId);
            if (gmodel == null)
            {
                return false;
            }

            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Education_ActivitySummaryGroup_Extend.Status),1},
                { nameof(RB_Education_ActivitySummaryGroup_Extend.UpdateDate),DateTime.Now},
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                    FiledName=nameof(RB_Education_ActivitySummaryGroup_Extend.Id),
                    FiledValue=groupId,
                    OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                    FiledName=nameof(RB_Education_ActivitySummaryGroup_Extend.TenantId),
                    FiledValue=Convert.ToInt32(uid),
                    OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                    FiledName=nameof(RB_Education_ActivitySummaryGroup_Extend.MallBaseId),
                    FiledValue=mallBaseId,
                    OperatorEnum=OperatorEnum.Equal
                },
            };
            bool flag = education_ActivitySummaryGroupRepository.Update(keyValues, wheres);
            if (flag)
            {
                //删除分组下所有的素材
                education_ActivitySummaryFileRepository.DelMaterialInfo("", uid, mallBaseId, groupId);
            }
            return flag;
        }

        /// <summary>
        /// 删除素材
        /// </summary>
        /// <param name="materialIds"></param>
        /// <param name="uid"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool DelMaterialInfo(string materialIds, string uid, int mallBaseId)
        {
            bool flag = education_ActivitySummaryFileRepository.DelMaterialInfo(materialIds, uid, mallBaseId);
            return flag;
        }


        /// <summary>
        /// 设置分组转移
        /// </summary>
        /// <param name="materialIds"></param>
        /// <param name="groupId"></param>
        /// <param name="Type"></param>
        /// <param name="uid"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetMaterialInfoTransfer(string materialIds, int groupId, int Type, string uid, int mallBaseId)
        {
            var gmodel = education_ActivitySummaryGroupRepository.GetEntity(groupId);
            if (gmodel == null)
            {
                return false;
            }
            if (gmodel.Status == 1 || gmodel.Type != Type)
            {
                return false;
            }
            return education_ActivitySummaryFileRepository.SetMaterialInfoTransfer(materialIds, groupId, uid, mallBaseId, gmodel.ActivityId);
        }

        /// <summary>
        /// 分页列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowCount">总条数</param>
        /// <param name="dmodel">查询条件</param>
        /// <returns></returns>
        public List<RB_Education_ActivitySummaryFile_Extend> GetActivitySummaryFilePageList(int pageIndex, int pageSize, out long rowCount, RB_Education_ActivitySummaryFile_Extend dmodel)
        {
            return education_ActivitySummaryFileRepository.GetPageList(pageIndex, pageSize, out rowCount, dmodel);
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Education_ActivitySummaryFile_Extend> GetActivitySummaryFileList(RB_Education_ActivitySummaryFile_Extend dmodel)
        {
            return education_ActivitySummaryFileRepository.GetList(dmodel);
        }
        #endregion



        #region 财务单据信息


        public List<RB_Finance_Extend> GetFinanceInfoList(RB_Finance_Extend model)
        {
            var list = financeRepository.GetListSingle(model)?.Where(x => x.Status != FinanceAuditStatus.Delete).ToList();
            List<RB_TradeWay_Extend> tdlist = new List<RB_TradeWay_Extend>();
            List<RB_FinanceDetail_Extend> fdlist = new List<RB_FinanceDetail_Extend>();
            List<Model.Entity.Finance.Rb_Workflow_Auditrecord> walist = new List<Model.Entity.Finance.Rb_Workflow_Auditrecord>();
            List<RB_Costtype_Extend> costlist = new List<RB_Costtype_Extend>();
            List<RB_Finance_Extend> tclist = new List<RB_Finance_Extend>();
            List<RB_Voucher_Extend> volist = new List<RB_Voucher_Extend>();
            if (list.Any())
            {
                string fridStr = string.Join(",", list.Select(x => x.FrID));
                tdlist = GetBankListForFrIdStr(fridStr, model.RB_Group_Id ?? 2);
                fdlist = RB_FinanceDetailRepository.GetList(new RB_FinanceDetail_Extend() { FrIds = fridStr });
                if (fdlist.Any())
                {
                    costlist = costtypeRepository.GetList(new RB_Costtype_Extend() { CostIds = string.Join(",", fdlist.Select(x => x.CostTypeId ?? 0)) });
                }
                walist = Finance_TemplateRepository.GetAgreeOrWaitList(new Model.Entity.Finance.Rb_Workflow_Auditrecord() { AuditStatus = WFRrocessStatus.NotAudit }, fridStr);
                volist = voucherRepository.GetList(new RB_Voucher_Extend() { FrIdStr = fridStr });
            }

            foreach (var item in list)
            {
                item.BankList = new List<RB_TradeWay_Extend>();
                item.BankList = tdlist.Where(x => x.FinanceId == item.FrID).ToList();
                item.CostTypeList = new List<string>();
                var detailList = fdlist.Where(x => x.FinanceId == item.FrID).ToList();
                item.detailList = detailList;
                foreach (var detailitem in detailList)
                {
                    var cmodel = costlist.Where(x => x.ID == detailitem.CostTypeId).FirstOrDefault();
                    item.CostTypeList.Add(cmodel?.Name ?? "");
                }
                #region 判断是否可以操作单据
                item.AuditList = new List<AuditInfo>();
                if (item.Status == FinanceAuditStatus.InReview)
                {
                    var Auditdata = walist.Where(x => x.WorkFlowId == item.FrID).ToList();
                    foreach (var sitem in Auditdata)
                    {
                        AuditInfo auditInfo = new AuditInfo()
                        {
                            AuditEmId = sitem.AuditEmId,
                            AuditDate = null,
                            AuditEmName = sitem.AuditEmIdName
                        };
                        item.AuditList.Add(auditInfo);
                    }
                }
                if (item.Type == WFTempLateClassEnum.IN && item.Status == FinanceAuditStatus.CTemporary)
                {
                    //判断如果是平台的单子  需要把实付清0
                    var bankModel = item.BankList.FirstOrDefault();
                    if (bankModel != null)
                    {
                        if (bankModel.Type == BranchAccountEnum.Platform && (item.PayMoney ?? 0) > 0)
                        {
                            item.PayMoney = 0;
                        }
                    }
                }
                #endregion
                #region 团队编号
                //item.TCIDAndTCNUMList = tclist.Where(x => x.FrID == item.FrID).FirstOrDefault()?.TCIDAndTCNUMList ?? new List<TCIDInfo>();
                #endregion
                #region  凭证
                item.vorcherInos = volist.Where(x => x.FinanceId == item.FrID).ToList();
                #endregion
            }
            return list;
        }




        /// <summary>
        /// 批量获取财务单据的交易方式
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public List<RB_TradeWay_Extend> GetBankListForFrIdStr(string FrIdStr, int GroupId)
        {
            if (string.IsNullOrWhiteSpace(FrIdStr))
            {
                return null;
            }
            List<RB_TradeWay_Extend> list = new List<RB_TradeWay_Extend>();
            var TradeList = tradeWayRepository.GetList(new RB_TradeWay_Extend() { FrIdStr = FrIdStr });
            //获取币种列表
            var CurrencyList = new RB_CurrencyRepository().GetList(new Model.Entity.Finance.RB_Currency() { RB_Group_Id = GroupId });
            //查询四大账户
            var BankList = new RB_BackAccountRepository().GetList(new RB_BackAccount_Extend() { AccountIdStr = string.Join(",", TradeList.Where(x => x.Type == BranchAccountEnum.Bank).Select(x => x.AccountId ?? 0).Distinct()) });
            var CashList = cashAccountRepository.GetList(new RB_CashAccount_Extend() { AccountIdStr = string.Join(",", TradeList.Where(x => x.Type == BranchAccountEnum.Cash).Select(x => x.AccountId ?? 0).Distinct()) });
            var CashPoolList = cashPoolAccountRepository.GetList(new RB_CashPoolAccount_Extend() { AccountIdStr = string.Join(",", TradeList.Where(x => x.Type == BranchAccountEnum.CashPool).Select(x => x.AccountId ?? 0).Distinct()) });
            var PlatformList = platformAccountRepository.GetList(new RB_PlatformAccount_Extend() { AccountIdStr = string.Join(",", TradeList.Where(x => x.Type == BranchAccountEnum.Platform).Select(x => x.AccountId ?? 0).Distinct()) });

            foreach (var TradeModel in TradeList)
            {
                RB_TradeWay_Extend accountInFo = TradeModel.RefMapperTo<RB_TradeWay_Extend>();
                accountInFo.CurrencyName = CurrencyList.Where(x => x.ID == TradeModel.CurrencyId).FirstOrDefault()?.Name ?? "";
                if (TradeModel.Type == Common.Enum.Finance.BranchAccountEnum.Bank)
                {
                    var bank = BankList.Where(x => x.ID == TradeModel.AccountId).FirstOrDefault();
                    if (bank != null)
                    {
                        accountInFo.Alias = bank.Alias;
                        accountInFo.BankNo = bank.BackNo;
                        accountInFo.Type = Common.Enum.Finance.BranchAccountEnum.Bank;
                        accountInFo.AccountTypeId = bank.TypeId;
                        var accountType = new RB_AccountTypeRepository().GetEntity(bank.TypeId.Value);
                        accountInFo.AccountType = accountType?.IsPublic == 0 ? "对私" : "对公";
                    }
                }
                else if (TradeModel.Type == Common.Enum.Finance.BranchAccountEnum.Cash)
                {
                    var cash = CashList.Where(x => x.ID == TradeModel.AccountId).FirstOrDefault();
                    if (cash != null)
                    {
                        accountInFo.Alias = cash.Alias;
                        accountInFo.BankNo = "";
                        accountInFo.Type = Common.Enum.Finance.BranchAccountEnum.Cash;
                        accountInFo.AccountTypeId = cash.TypeId;
                        var accountType = new RB_AccountTypeRepository().GetEntity(cash.TypeId.Value);
                        accountInFo.AccountType = accountType?.IsPublic == 0 ? "对私" : "对公";
                    }
                }
                else if (TradeModel.Type == Common.Enum.Finance.BranchAccountEnum.CashPool)
                {
                    var pool = CashPoolList.Where(x => x.ID == TradeModel.AccountId).FirstOrDefault();
                    if (pool != null)
                    {
                        accountInFo.Alias = pool.Alias;
                        accountInFo.BankNo = "";
                        accountInFo.Type = Common.Enum.Finance.BranchAccountEnum.CashPool;
                        accountInFo.AccountTypeId = pool.TypeId;
                        var accountType = new RB_AccountTypeRepository().GetEntity(pool.TypeId.Value);
                        accountInFo.AccountType = accountType?.IsPublic == 0 ? "对私" : "对公";
                    }
                }
                else if (TradeModel.Type == Common.Enum.Finance.BranchAccountEnum.Platform)
                {
                    var platform = PlatformList.Where(x => x.ID == TradeModel.AccountId).FirstOrDefault();
                    if (platform != null)
                    {
                        accountInFo.Alias = platform.Alias;
                        accountInFo.BankNo = platform.PlatformNo;
                        accountInFo.Type = Common.Enum.Finance.BranchAccountEnum.Platform;
                        accountInFo.AccountTypeId = platform.TypeId;
                        var accountType = new RB_AccountTypeRepository().GetEntity(platform.TypeId.Value);
                        accountInFo.AccountType = accountType?.IsPublic == 0 ? "对私" : "对公";
                    }
                }
                list.Add(accountInFo);
            }
            return list;
        }


        #endregion
    }
}
