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.BaseSetUp;
using Mall.Repository.Coffee;
using Mall.Repository.Education;
using Mall.Repository.Finance;
using Newtonsoft.Json;
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 Repository.User.RB_Distributor_InfoRepository distributor_InfoRepository = new Repository.User.RB_Distributor_InfoRepository();

        /// <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_Education_EduSellRepository education_EduSellRepository = new RB_Education_EduSellRepository();
        /// <summary>
        /// 字典
        /// </summary>
        private readonly Rb_DictvalueRepository dictvalueRepository = new Rb_DictvalueRepository();
        /// <summary>
        /// 咖啡劵
        /// </summary>
        private readonly RB_Member_CoffeeCouponsRepository member_CoffeeCouponsRepository = new RB_Member_CoffeeCouponsRepository();
        /// <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>
        /// 活动配置
        /// </summary>
        private readonly RB_Activity_ConfigRepository activity_ConfigRepository = new RB_Activity_ConfigRepository();
        /// <summary>
        /// 活动期数
        /// </summary>
        private readonly RB_Activity_PeriodsRepository activity_PeriodsRepository = new RB_Activity_PeriodsRepository();
        /// <summary>
        /// 活动期数明细
        /// </summary>
        private readonly RB_Activity_PeriodsDetailRepository activity_PeriodsDetailRepository = new RB_Activity_PeriodsDetailRepository();

        /// <summary>
        /// 活动大标题
        /// </summary>
        private readonly RB_Education_ActivityTitleRepository education_ActivityTitleRepository = new RB_Education_ActivityTitleRepository();


        /// <summary>
        /// 活动安排
        /// </summary>
        private readonly RB_Education_ActivityPlanRepository education_ActivityPlanRepository = new RB_Education_ActivityPlanRepository();


        /// <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_V2(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="dmodel"></param>
        /// <returns></returns>
        public List<RB_Education_Activity_Extend> GetActivityList(RB_Education_Activity_Extend query)
        {
            var list = education_ActivityRepository.GetList(query);

            return list;
        }

        /// <summary>
        /// 新增修改商户活动
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetActivityModule(RB_Education_Activity_Extend model)
        {
            bool flag;
            var trans = education_ActivityRepository.DbTransaction;
            try
            {
                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.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), trans);
                    if (flag)
                    {
                        var titleList = education_ActivityTitleRepository.GetActivityTitleList(new RB_Education_ActivityTitle_Extend { ActivityId = model.Id, TenantId = model.TenantId, MallBaseId = model.MallBaseId });
                        if (titleList != null && titleList.Any())
                        {
                            education_ActivityTitleRepository.DeleteBatch(titleList, trans);
                        }
                        var planList = education_ActivityPlanRepository.GetActivityPlanList(new RB_Education_ActivityPlan_Extend { ActivityId = model.Id, TenantId = model.TenantId, MallBaseId = model.MallBaseId });
                        if (planList != null && planList.Any())
                        {
                            education_ActivityPlanRepository.DeleteBatch(planList, trans);
                        }
                    }
                }
                else
                {
                    var newId = education_ActivityRepository.Insert(model, trans);
                    model.Id = newId;
                    flag = newId > 0;
                }


                if (flag && model.ActivityTitleList != null && model.ActivityTitleList.Any())
                {
                    model.ActivityTitleList.ForEach(x => x.TenantId = model.TenantId);
                    model.ActivityTitleList.ForEach(x => x.MallBaseId = model.MallBaseId);
                    model.ActivityTitleList.ForEach(x => x.ActivityId = model.Id);
                    model.ActivityTitleList.ForEach(x => x.Id = 0);
                    model.ActivityTitleList.ForEach(x => x.Status = Common.Enum.DateStateEnum.Normal);
                    foreach (var item in model.ActivityTitleList)
                    {
                        var titleId = education_ActivityTitleRepository.Insert(item, trans);

                        if (item.ActivityPlanList != null && item.ActivityPlanList.Any())
                        {
                            item.ActivityPlanList.ForEach(x => x.Id = 0);
                            item.ActivityPlanList.ForEach(x => x.TenantId = model.TenantId);
                            item.ActivityPlanList.ForEach(x => x.MallBaseId = model.MallBaseId);
                            item.ActivityPlanList.ForEach(x => x.ActivityId = model.Id);
                            item.ActivityPlanList.ForEach(x => x.TitleId = titleId);
                            item.ActivityPlanList.ForEach(x => x.TripPic = (x.TripPicList != null && x.TripPicList.Any()) ? JsonConvert.SerializeObject(x.TripPicList) : "");
                            item.ActivityPlanList.ForEach(x => x.Status = Common.Enum.DateStateEnum.Normal);
                            education_ActivityPlanRepository.InsertBatch(item.ActivityPlanList, trans);
                        }
                    }
                }
                education_ActivityRepository.DBSession.Commit();
                return flag;
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, string.Format("SetActivityModule_Msg:{0}", Common.Plugin.JsonHelper.Serialize(model)));
                education_ActivityRepository.DBSession.Rollback("SetActivityModule");
                return false;
            }
        }



        /// <summary>
        /// 新增修改商户活动
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetActivityPlanModule(RB_Education_Activity_Extend model)
        {
            bool flag = false;
            var trans = education_ActivityTitleRepository.DbTransaction;
            try
            {

                var titleList = education_ActivityTitleRepository.GetActivityTitleList(new RB_Education_ActivityTitle_Extend { ActivityId = model.Id, TenantId = model.TenantId, MallBaseId = model.MallBaseId });
                if (titleList != null && titleList.Any())
                {
                    education_ActivityTitleRepository.DeleteBatch(titleList, trans);
                }
                var planList = education_ActivityPlanRepository.GetActivityPlanList(new RB_Education_ActivityPlan_Extend { ActivityId = model.Id, TenantId = model.TenantId, MallBaseId = model.MallBaseId });
                if (planList != null && planList.Any())
                {
                    education_ActivityPlanRepository.DeleteBatch(planList, trans);
                }

                if (model.ActivityTitleList != null && model.ActivityTitleList.Any())
                {
                    model.ActivityTitleList.ForEach(x => x.TenantId = model.TenantId);
                    model.ActivityTitleList.ForEach(x => x.MallBaseId = model.MallBaseId);
                    model.ActivityTitleList.ForEach(x => x.ActivityId = model.Id);
                    model.ActivityTitleList.ForEach(x => x.Id = 0);
                    model.ActivityTitleList.ForEach(x => x.Status = Common.Enum.DateStateEnum.Normal);
                    foreach (var item in model.ActivityTitleList)
                    {
                        var titleId = education_ActivityTitleRepository.Insert(item, trans);

                        if (item.ActivityPlanList != null && item.ActivityPlanList.Any())
                        {
                            item.ActivityPlanList.ForEach(x => x.Id = 0);
                            item.ActivityPlanList.ForEach(x => x.TenantId = model.TenantId);
                            item.ActivityPlanList.ForEach(x => x.MallBaseId = model.MallBaseId);
                            item.ActivityPlanList.ForEach(x => x.ActivityId = model.Id);
                            item.ActivityPlanList.ForEach(x => x.TitleId = titleId);
                            item.ActivityPlanList.ForEach(x => x.TripPic = (x.TripPicList != null && x.TripPicList.Any()) ? JsonConvert.SerializeObject(x.TripPicList) : "");
                            item.ActivityPlanList.ForEach(x => x.Status = Common.Enum.DateStateEnum.Normal);
                            flag = education_ActivityPlanRepository.InsertBatch(item.ActivityPlanList, trans);
                        }
                    }
                }
                education_ActivityTitleRepository.DBSession.Commit();
                return flag;
            }
            catch
            {
                education_ActivityTitleRepository.DBSession.Rollback("SetActivityPlanModule");
                return false;
            }
        }


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


        #region 活动安排


        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Education_ActivityTitle_Extend> GetActivityTitleList(RB_Education_ActivityTitle_Extend query)
        {
            return education_ActivityTitleRepository.GetActivityTitleList(query);
        }


        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Education_ActivityPlan_Extend> GetActivityPlanList(RB_Education_ActivityPlan_Extend query)
        {
            return education_ActivityPlanRepository.GetActivityPlanList(query);
        }

        #endregion


        #endregion

        #region 活动报名

        /// <summary>
        /// 获取内部+学生的
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Education_EduSell_Extend> GetEducationSellList(RB_Education_EduSell_Extend query)
        {
            var list = education_EduSellRepository.GetEducationStuList(query, true);
            if (list != null && list.Any(x => x.EduSellId > 0))
            {
                string qIds = string.Join(",", list.Where(x => x.EduSellId > 0 && x.Type ==1).Distinct().Select(x => x.EduSellId));
                var employeeList = RB_AccountRepository.GetEmployeeListRepository(new Employee_ViewModel { QIds = qIds }).ToList();
                string qstuIds = string.Join(",", list.Where(x => x.EduSellId > 0 && x.Type == 2).Distinct().Select(x => x.EduSellId));
                var stuList = RB_AccountRepository.GetStudentExt(new RB_Account_ViewModel() { QIds = qstuIds, AccountType = 4 });
                foreach (var item in list)
                {
                    item.employeeModel = new Employee_ViewModel();
                    if (item.Type == 1)
                    {
                        item.employeeModel = employeeList.Where(x => x.Id == item.EduSellId).FirstOrDefault();
                    }
                    else if (item.Type == 2) {
                        var stuModel = stuList.Where(x => x.Id == item.EduSellId).FirstOrDefault();
                        item.employeeModel = new Employee_ViewModel()
                        {
                            Id = stuModel?.Id ?? 0,
                            EmployeeName = stuModel?.AccountName ?? "",
                            UserIcon = stuModel?.UserIcon ?? ""
                        };
                    }
                }
            }
            return list;
        }


        /// <summary>
        /// 获取教育销售的基础信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Education_EduSell_Extend> GetEducationSellBaseInfo(RB_Education_EduSell_Extend query)
        {
            var list = education_EduSellRepository.GetEducationSellBaseInfo(query);
            if (list != null && list.Any(x => x.EduSellId > 0))
            {
                string qIds = string.Join(",", list.Where(x => x.EduSellId > 0).Distinct().Select(x => x.EduSellId));
                var employeeList = RB_AccountRepository.GetEmployeeListRepository(new Employee_ViewModel { QIds = qIds }).ToList();
                if (employeeList != null && employeeList.Any())
                {
                    foreach (var item in list)
                    {
                        item.employeeModel = new Employee_ViewModel();
                        item.employeeModel = employeeList.Where(x => x.Id == item.EduSellId).FirstOrDefault();
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 验证学生是否有正在学习的课程
        /// </summary>
        /// <param name="accountId"></param>
        /// <returns></returns>
        public bool GetEduStuLearning(int accountId)
        {
            return RB_AccountRepository.GetStuLearningCourse(accountId) > 0;
        }

        /// <summary>
        /// 更新教育用户的基础信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetEduSellBaseInfo(RB_Education_EduSell_Extend model)
        {
            bool flag;
            if (model.Id == 0)
            {
                flag = education_EduSellRepository.Insert(model) > 0;
                if (flag) {
                    //绑定成功  直接初始化 免费咖啡劵
                    if (model.Type == 1)
                    {
                        //内部人员  直接初始化  内部人员的咖啡劵信息
                        int FreeNum = Convert.ToInt32(dictvalueRepository.GetList(new Model.Extend.BaseSetUp.RB_Dictvalue_Extend() { MallBaseId = model.MallBaseId ?? 0, DictKey = "Edu_CoffeeCoupons_EmpFree" }).FirstOrDefault()?.Content ?? "0");
                        if (FreeNum > 0)
                        {
                            var cmodel = new Model.Extend.Coffee.RB_Member_CoffeeCoupons_Extend()
                            {
                                Id = 0,
                                CreateDate = DateTime.Now,
                                FreeNum = FreeNum,
                                MallBaseId = model.MallBaseId ?? 0,
                                SurplusBugNum = 0,
                                TotalBuyNum = 0,
                                UpdateDate = DateTime.Now,
                                UserId = model.UserId
                            };
                            member_CoffeeCouponsRepository.Insert(cmodel);
                        }
                    }
                    else if (model.Type == 2)
                    {
                        //学生  要看是否还有正在学习的课程  有的话 可初始化免费的咖啡劵
                        int FreeNum = Convert.ToInt32(dictvalueRepository.GetList(new Model.Extend.BaseSetUp.RB_Dictvalue_Extend() { MallBaseId = model.MallBaseId??0, DictKey = "Edu_CoffeeCoupons_Free" }).FirstOrDefault()?.Content ?? "0");
                        if (FreeNum > 0)
                        {
                            var cmodel = new Model.Extend.Coffee.RB_Member_CoffeeCoupons_Extend()
                            {
                                Id = 0,
                                CreateDate = DateTime.Now,
                                FreeNum = FreeNum,
                                MallBaseId = model.MallBaseId ?? 0,
                                SurplusBugNum = 0,
                                TotalBuyNum = 0,
                                UpdateDate = DateTime.Now,
                                UserId = model.UserId
                            };
                            member_CoffeeCouponsRepository.Insert(cmodel);
                        }
                    }
                }
            }
            else
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Education_EduSell_Extend.EduSellId),model.EduSellId },
                };
                flag = education_EduSellRepository.Update(fileds, new WhereHelper(nameof(RB_Education_EduSell_Extend.Id), model.Id));
            }

            return flag;
        }

        /// <summary>
        /// 获取员工列表【管理者、讲师、助教】
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<Employee_ViewModel> GetEmployeeListModule(Employee_ViewModel query)
        {
            return RB_AccountRepository.GetEmployeeListRepository(query);
        }





        /// <summary>
        /// 判断用户是否有某项功能权限
        /// </summary>
        /// <param name="actionCode">权限编码</param>
        /// <param name="postIds">岗位编号【可以多个】</param>
        /// <returns></returns>
        public bool CheckUserFunctionRepository(string actionCode, string postIds)
        {
            return RB_AccountRepository.CheckUserFunctionRepository(actionCode, postIds);
        }





        /// <summary>
        /// 获取学员账号列表扩展列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Account_ViewModel> GetStudentExt(RB_Account_ViewModel query)
        {
            return RB_AccountRepository.GetStudentExt(query);
        }


        /// <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;
            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;
            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="id"></param>
        /// <returns></returns>
        public Model.Entity.Education.RB_Education_Consult GetConsultEntity(object id)
        {
            return education_ConsultRepository.GetEntity(id);
        }

        /// <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())
            {
                if (list.Any(x => x.EduUserId > 0))
                {
                    string qIds = string.Join(",", list.Where(x => x.EduUserId > 0).Distinct().Select(x => x.EduUserId));
                    var employeeList = RB_AccountRepository.GetEmployeeListRepository(new Employee_ViewModel { QIds = qIds }).ToList();
                    list.ForEach(x => x.EduSellName = x.EduUserId > 0 ? employeeList.Where(y => y.Id == x.EduUserId).FirstOrDefault()?.EmployeeName : "");
                }
                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())
                {
                    var arlist = new Repository.Finance.Rb_Workflow_AuditRelevanceRepository().GetAuditRelevanceList(0, string.Join(",", flist.Select(x => x.FrID)));
                    foreach (var sitem in flist)
                    {
                        sitem.ColorType = 1;
                        if (sitem.Status == FinanceAuditStatus.Pass)
                        {
                            sitem.ColorType = 4;
                        }
                        else if (sitem.Status == FinanceAuditStatus.InReview || sitem.Status == FinanceAuditStatus.CTemporary)
                        {
                            if (sitem.Status == FinanceAuditStatus.CTemporary)
                            {
                                sitem.ColorType = 2;
                            }
                            else
                            {
                                var itemList = arlist.Where(x => x.WorkFlowId == sitem.FrID).ToList();
                                if (itemList != null && itemList.Count > 0)
                                {
                                    var CasierList = itemList.Where(x => x.SpecialNode != 0).ToList();
                                    if (CasierList.Count() == 1 && CasierList.Where(x => x.Stauts == 2).Count() == 1)
                                    {
                                        sitem.ColorType = 3;
                                    }
                                    else if (CasierList.Count() > 1 && CasierList.Where(x => x.Stauts == 2).Count() == CasierList.Count())
                                    {
                                        sitem.ColorType = 3;
                                    }
                                    else if (CasierList.Count() > 0 && itemList.Where(x => x.Stauts == 2).Count() == 0)
                                    {
                                        sitem.ColorType = 1;
                                    }
                                }
                                else
                                {
                                    sitem.ColorType = 1;
                                }
                            }
                        }
                    }
                    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> GetCommerceConsultListRepository_V3(int pageIndex, int pageSize, out long rowsCount, RB_Education_Consult_Extend query)
        {
            var list = education_ConsultRepository.GetCommerceConsultListRepository_V3(pageIndex, pageSize, out rowsCount, query);
            if (list != null && list.Any())
            {
                if (list.Any(x => x.EduUserId > 0))
                {
                    string qIds = string.Join(",", list.Where(x => x.EduUserId > 0).Distinct().Select(x => x.EduUserId));
                    var employeeList = RB_AccountRepository.GetEmployeeListRepository(new Employee_ViewModel { QIds = qIds }).ToList();
                    list.ForEach(x => x.EduSellName = x.EduUserId > 0 ? employeeList.Where(y => y.Id == x.EduUserId).FirstOrDefault()?.EmployeeName : "");
                }
                if (list.Any(x => x.EduStudentId > 0))
                {
                    string qIds = string.Join(",", list.Where(x => x.EduStudentId > 0).Distinct().Select(x => x.EduStudentId));
                    var employeeList = RB_AccountRepository.GetStudentExt(new RB_Account_ViewModel { QIds = qIds }).ToList();
                    list.ForEach(x => x.EduStudentName = x.EduStudentId > 0 ? employeeList.Where(y => y.Id == x.EduStudentId).FirstOrDefault()?.AccountName : "");
                }
                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())
                {
                    var arlist = new Repository.Finance.Rb_Workflow_AuditRelevanceRepository().GetAuditRelevanceList(0, string.Join(",", flist.Select(x => x.FrID)));
                    foreach (var sitem in flist)
                    {
                        sitem.StatusName = EnumHelper.GetEnumName(sitem.Status);
                        sitem.ColorType = 1;
                        if (sitem.Status == FinanceAuditStatus.Pass)
                        {
                            sitem.ColorType = 4;
                        }
                        else if (sitem.Status == FinanceAuditStatus.InReview || sitem.Status == FinanceAuditStatus.CTemporary)
                        {
                            if (sitem.Status == FinanceAuditStatus.CTemporary)
                            {
                                sitem.ColorType = 2;
                            }
                            else
                            {
                                var itemList = arlist.Where(x => x.WorkFlowId == sitem.FrID).ToList();
                                if (itemList != null && itemList.Count > 0)
                                {
                                    var CasierList = itemList.Where(x => x.SpecialNode != 0).ToList();
                                    if (CasierList.Count() == 1 && CasierList.Where(x => x.Stauts == 2).Count() == 1)
                                    {
                                        sitem.ColorType = 3;
                                    }
                                    else if (CasierList.Count() > 1 && CasierList.Where(x => x.Stauts == 2).Count() == CasierList.Count())
                                    {
                                        sitem.ColorType = 3;
                                    }
                                    else if (CasierList.Count() > 0 && itemList.Where(x => x.Stauts == 2).Count() == 0)
                                    {
                                        sitem.ColorType = 1;
                                    }
                                }
                                else
                                {
                                    sitem.ColorType = 1;
                                }
                            }
                        }
                    }
                    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> GetExportCommerceConsultList(RB_Education_Consult_Extend query)
        {
            var list = education_ConsultRepository.GetExportCommerceConsultList(query);
            if (list != null && list.Any())
            {
                if (list.Any(x => x.EduUserId > 0))
                {
                    string qIds = string.Join(",", list.Where(x => x.EduUserId > 0).Distinct().Select(x => x.EduUserId));
                    var employeeList = RB_AccountRepository.GetEmployeeListRepository(new Employee_ViewModel { QIds = qIds }).ToList();
                    list.ForEach(x => x.EduSellName = x.EduUserId > 0 ? employeeList.Where(y => y.Id == x.EduUserId).FirstOrDefault()?.EmployeeName : "");
                }
            }

            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> GetRollCallConsultList(RB_Education_Consult_Extend query)
        {
            var list = education_ConsultRepository.GetExportCommerceConsultList(query);

            return list;
        }

        /// <summary>
        /// 批量更新报名人员的点名状态
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public bool UpdateBatchRollCall(List<RB_Education_Consult_Extend> list)
        {
            bool flag = false;
            foreach (var item in list)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Education_Consult_Extend.IsRollCall),item.IsRollCall}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper{
                         FiledName=nameof(RB_Education_Consult_Extend.Id),
                          FiledValue=item.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                flag = education_ConsultRepository.Update(keyValues, wheres);//更新会员是否点名
            }
            return flag;

        }

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


        /// <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;
            //判断当前人的点数
            if (demodel.PaymentWay == Common.Enum.Goods.OrderPaymentTypeEnum.PayPoint)
            {
                var trans = education_ConsultRepository.DbTransaction;
                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);
            }
            else if (demodel.PaymentWay == Common.Enum.Goods.OrderPaymentTypeEnum.OfflinePay)
            {
                if (demodel.Id > 0)
                {
                    flag = demodel.Id;
                    education_ConsultRepository.Update(demodel);
                }
                else
                {
                    flag = education_ConsultRepository.Insert(demodel);
                }
            }
            if (demodel.UserId > 0 && flag > 0)
            {
                //任务执行 订单记录当前用户的所有上级
                System.Threading.Tasks.Task.Run(() => SaveOrderUserAllParent(demodel.UserId, flag));
            }
            return flag;
        }




        /// <summary>
        /// 订单记录当前用户的所有上级
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="OrderId"></param>
        /// <returns></returns>
        private bool SaveOrderUserAllParent(int UserId, int OrderId)
        {
            if (OrderId <= 0 || UserId <= 0)
            {
                return false;
            }
            try
            {
                string parentIds = member_UserRepository.GetMemberParentIdStr(UserId);
                string distributorIds = "";
                int eduUserId = 0;
                if (!string.IsNullOrEmpty(parentIds))
                {
                    //查询用户是否是分销商
                    var dlist = distributor_InfoRepository.GetListForSingle(new Model.Extend.User.RB_Distributor_Info_Extend() { UserIds = parentIds, AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Audited });
                    List<int> pList = JsonHelper.DeserializeObject<List<int>>("[" + parentIds + "]");
                    foreach (var item in pList)
                    {
                        var dmodel = dlist.Where(x => x.UserId == item).FirstOrDefault();
                        if (dmodel != null)
                        {
                            distributorIds += item + ",";
                        }
                    }
                    if (!string.IsNullOrEmpty(distributorIds))
                    {
                        distributorIds = distributorIds[0..^1];
                    }

                    var userList = member_UserRepository.GetList(new RB_Member_User_Extend { UserIds = parentIds });
                    if (userList != null && userList.Any(x => x.SuperiorId == 0))
                    {
                        int userId = userList.Where(x => x.SuperiorId == 0).FirstOrDefault()?.Id ?? 0;
                        var eduSellModel = GetEducationSellBaseInfo(new RB_Education_EduSell_Extend { UserId = userId }).FirstOrDefault();
                        if (eduSellModel != null && eduSellModel.Id > 0)
                        {
                            eduUserId = eduSellModel.EduSellId;
                        }

                    }
                }

                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Education_Consult_Extend.UserTree),parentIds },
                     { nameof(RB_Education_Consult_Extend.EduUserId),eduUserId },
                    { nameof(RB_Education_Consult_Extend.DistributorTree),distributorIds }
                };
                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;
            }
            catch (Exception)
            {
                return false;
            }
        }



        /// <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;
            }
            decimal PlatformTax = (Math.Round((Convert.ToDecimal(Config.SettlementRate) / 100) * (Convert.ToDecimal(Money)), 2, MidpointRounding.AwayFromZero));//手续费
            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},
                          { nameof(RB_Education_Consult_Extend.Income),(Math.Round((Money-PlatformTax),2,MidpointRounding.AwayFromZero))},
                           { nameof(RB_Education_Consult_Extend.PlatformTax),PlatformTax}
                };
            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 = PlatformTax,
                    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="OrderId"></param>
        /// <param name="Money"></param>
        /// <param name="ActivityId"></param>
        /// <returns></returns>
        public bool UpdateActivityIncome(int OrderId, decimal Money, decimal PlatformTax)
        {
            //判断订单状态是否是待支付  2020-06-16 Add By:W
            var model = education_ConsultRepository.GetEntity(OrderId);
            if (model == null)
            {
                return false;
            }
            if (Money >= model.Money)
            {
                model.OrderStatus = 1;
            }
            //  model.PlatformTax = model.PlatformTax + PlatformTax;

            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Education_Consult_Extend.PaymentTime),System.DateTime.Now},
                     { nameof(RB_Education_Consult_Extend.OrderStatus),model.OrderStatus},
                          { nameof(RB_Education_Consult_Extend.Income),Money},
                            { nameof(RB_Education_Consult_Extend.PlatformTax),PlatformTax}
                };
            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="OrderId"></param>
        /// <param name="Money"></param>
        /// <param name="ActivityId"></param>
        /// <returns></returns>
        public bool UpdateActivityReturn(int OrderId, decimal Money)
        {
            //判断订单状态是否是待支付  2020-06-16 Add By:W
            var model = education_ConsultRepository.GetEntity(OrderId);
            if (model == null)
            {
                return false;
            }
            //model.RefundPrice = model.RefundPrice + Money;
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Education_Consult_Extend.RefundPrice),Money},
                            { nameof(RB_Education_Consult_Extend.RefundTime),System.DateTime.Now}
                };
            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, decimal dPaid)
        {
            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 },
                     {nameof(RB_Education_Consult_Extend.RefundPrice),dPaid },
                };
            }
            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,
                                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, decimal dPaid)
        {
            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 },
                      {nameof(RB_Education_Consult_Extend.RefundPrice),dPaid},
                };
                }
                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,
                                    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;
        }



        /// <summary>
        /// 取消商会活动报名状态
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="Status"></param>
        /// <returns></returns>
        public bool CancelCommerceConsult(int activityId, string cancelRemark, out int IsCancelConfirm, 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 },
                };

                List<WhereHelper> list = new List<WhereHelper>()
                {
                    new WhereHelper(nameof(RB_Education_Consult_Extend.ActivityId), activityId),

                     new WhereHelper(nameof(RB_Education_Consult_Extend.Id), cmodel.Id),

                };
                flag = education_ConsultRepository.Update(fileds, list);

            }
            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="query"></param>
        /// <returns></returns>
        public List<RB_Student> GetStudentListByEnterID(RB_Student query, int EnterID)
        {
            return studentRepository.GetStudentListByEnterID(query, EnterID);
        }




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

        #region 活动提成

        /// <summary>
        /// 创建活动提成
        /// </summary>
        /// <param name="month"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetActivityCommissionInfo(string month, int createBy, UserInfo userInfo)
        {
            int GroupId = 100000;// 暂时固定  并没有授权相关的表（跟到春姐 写死）;
            //首先查询该月是否已创建
            var plist = activity_PeriodsRepository.GetList(new RB_Activity_Periods_ViewModel() { Group_Id = GroupId, Periods = month });
            if (plist.Any())
            {
                return "当月提成已创建";
            }
            string EDate = Convert.ToDateTime(month + "-01").AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");
            //查询小于等于 当前月的所有 款已平 有销售 小程序来的 未发放的订单
            var orderList = education_ConsultRepository.GetActivityCanSendCommissionList(EDate, userInfo.MallBaseId);
            if (orderList.Any())
            {
                //查询配置信息
                var configModel = activity_ConfigRepository.GetList(new RB_Activity_Config_ViewModel() { Group_Id = GroupId }).FirstOrDefault();
                if (configModel == null) { return "配置不存在，请核实后再试"; }
                //查询所有的用户
                string userIds = string.Join(",", orderList.Select(x => x.EduUserId).Distinct());
                var ulist = RB_AccountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = GroupId, QIds = userIds });
                //查询用户是否已参加过活动，参加过得  需要排除
                string dsuserIds = string.Join(",", orderList.Select(x => x.UserId).Distinct());
                var DSUList = activity_PeriodsDetailRepository.GetList(new RB_Activity_PeriodsDetail_ViewModel() { Group_Id = GroupId, DSUserIds = dsuserIds });

                //判断当前订单里  是否有用户重复的， 有重复的  需要备注重复的 ， 并且应发提成=0  (需注意的)   一个用户只能产生一次提成；

                List<RB_Activity_PeriodsDetail_ViewModel> DetailList = new List<RB_Activity_PeriodsDetail_ViewModel>();
                //开始写入提成记录表
                foreach (var item in orderList)
                {
                    bool IsJoin = false;
                    string Remark = "";
                    if (DSUList.Where(x => x.DSUserId == item.UserId).Any())
                    {
                        IsJoin = true;//已经参加过了
                        var dsModel = DSUList.Where(x => x.DSUserId == item.UserId).FirstOrDefault();
                        Remark = "该用户已在 " + dsModel.ActivityTime.ToString("yyyy-MM-dd") + " " + dsModel.ActivityName + " 活动中参与并已发提成";
                    }
                    decimal CommissionMoney = 0;
                    if (IsJoin == false)
                    {
                        //计算提成金额
                        if (configModel.Type == 1)
                        {
                            CommissionMoney = configModel.CommissionMoney * item.PeopleNum;
                        }
                        else
                        {
                            //百分比  根据实收金额来计算  手续费要算
                            CommissionMoney = Math.Round(item.Money * configModel.CommissionMoney / 100, 2, MidpointRounding.AwayFromZero);
                        }
                    }
                    var umodel = ulist.Where(x => x.Id == item.EduUserId).FirstOrDefault();
                    DetailList.Add(new RB_Activity_PeriodsDetail_ViewModel()
                    {
                        Id = 0,
                        ActivityId = item.ActivityId,
                        ActivityName = item.ActivityName,
                        ActivityTime = item.StartTime.Value,
                        CMoney = configModel.CommissionMoney,
                        CType = configModel.Type,
                        CommissionMoney = CommissionMoney,
                        Depart_Id = umodel.Dept_Id,
                        DSUserId = item.UserId,
                        UserId = item.EduUserId,
                        DSUserName = item.LinkMan,
                        Group_Id = GroupId,
                        OrderId = item.Id,
                        PeriodId = 0,
                        Periods = item.StartTime.Value.ToString("yyyy-MM"),
                        Remark = Remark,
                        School_Id = umodel.School_Id,
                        IsJoin = IsJoin
                    });
                }
                //再来排除 当期重复的用户
                if (DetailList.Any())
                {
                    if (DetailList.Where(x => x.IsJoin == false).Select(x => x.DSUserId).Distinct().Count() != DetailList.Where(x => x.IsJoin == false).Count())
                    {
                        List<int> DsUserIdList = DetailList.Where(x => x.IsJoin == false).Select(x => x.DSUserId).Distinct().ToList();
                        foreach (var DsUserId in DsUserIdList)
                        {
                            var dlist = DetailList.Where(x => x.DSUserId == DsUserId && x.IsJoin == false).ToList();
                            if (dlist.Count() > 1)
                            {
                                var ddlist = dlist.OrderByDescending(x => x.CommissionMoney).ThenBy(x => x.ActivityTime).ToList();
                                //第一条保留提成  其他的不提成
                                var ddmodel = ddlist.FirstOrDefault();
                                int Num = 1;
                                foreach (var qitem in ddlist)
                                {
                                    if (Num > 1)
                                    {
                                        decimal cmoney = qitem.CommissionMoney;
                                        qitem.Remark = "该用户当期多次参与活动，提成在 " + ddmodel.ActivityTime.ToString("yyyy-MM-dd") + " " + ddmodel.ActivityName + " 活动中,原提成金额：" + cmoney;
                                        qitem.CommissionMoney = 0;
                                    }
                                    Num++;
                                }
                            }
                        }
                    }
                }

                #region 开始正式写入
                var trans = activity_PeriodsRepository.DbTransaction;
                try
                {
                    //首先创建期数
                    int PeriodsId = activity_PeriodsRepository.Insert(new Model.Entity.Education.RB_Activity_Periods()
                    {
                        Id = 0,
                        CreateBy = createBy,
                        CreateTime = DateTime.Now,
                        Financials = "",
                        Group_Id = GroupId,
                        Name = month + "期提成",
                        Periods = month,
                        SumPrice = 0
                    }, trans);
                    if (PeriodsId > 0)
                    {
                        foreach (var item in DetailList)
                        {
                            item.PeriodId = PeriodsId;
                            activity_PeriodsDetailRepository.Insert(item, trans);
                        }

                        #region 计算累计应发
                        decimal SumPrice = DetailList.Sum(x => x.CommissionMoney);
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Activity_Periods_ViewModel.SumPrice),SumPrice}
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Activity_Periods_ViewModel.Id),
                                  FiledValue=PeriodsId,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        activity_PeriodsRepository.Update(keyValues, wheres, trans);
                        #endregion
                    }
                    activity_PeriodsRepository.DBSession.Commit();

                    #region 更新订单提成
                    foreach (var item in DetailList)
                    {
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Education_Consult_Extend.IsCommission),2},
                            { nameof(RB_Education_Consult_Extend.CommissionPrice),item.CommissionMoney},
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Education_Consult_Extend.Id),
                                  FiledValue=item.OrderId,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        education_ConsultRepository.Update(keyValues, wheres);
                    }
                    #endregion
                }
                catch (Exception ex)
                {
                    LogHelper.Write(ex, "SetActivityCommissionInfo");
                    activity_PeriodsRepository.DBSession.Rollback();
                    return "出错了，请联系管理员";
                }
                #endregion
            }
            else
            {
                return "当月没有可发放提成的订单";
            }

            return "";
        }

        /// <summary>
        /// 获取活动累计的提成
        /// </summary>
        /// <param name="activityId"></param>
        /// <param name="groupId"></param>
        /// <returns></returns>
        public decimal GetActivityCommission(int activityId, int groupId)
        {
            return activity_PeriodsDetailRepository.GetActivityCommission(activityId, groupId);
        }

        #endregion
    }
}
