using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Mall.Module.Education;
using Mall.Common.API;
using Newtonsoft.Json;
using Mall.Model.Extend.Education;
using Newtonsoft.Json.Linq;
using Mall.Common.Plugin;
using Mall.Model.Extend.User;
using Mall.Model.Extend.Product;
using Mall.Common.Enum.Goods;
using Mall.Model.Entity.Education;
using Mall.Common.Enum.User;
using Mall.Model.Extend.Finance;
using Mall.Common.Enum.Finance;
using Mall.Common;
using Mall.Common.Enum.Education;
using Microsoft.AspNetCore.Authorization;
using Dnc.Api.Throttle;

namespace Mall.WebApi.Controllers.Education
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class EducationController : BaseController
    {
        private readonly IHttpContextAccessor _accessor;
        private readonly EducationModule educationModule = new EducationModule();
        private readonly Module.User.UserModule UserModule = new Module.User.UserModule();
        private readonly DynamicModule dynamicModule = new DynamicModule();
        private readonly ActivityModule activityModule = new ActivityModule();

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="accessor"></param>
        public EducationController(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }



        #region 课程管理
        /// <summary>
        /// 商品后台分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetGoodsPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            JObject parameters = JObject.Parse(RequestParm.msg.ToString());
            RB_Goods_Extend demodel = new RB_Goods_Extend()
            {
                Name = parameters.GetStringValue("Name"),
                GoodsStatus = parameters.GetInt("GoodsStatus"),
                CategoryIds = parameters.GetStringValue("CategoryIds"),
                Id = parameters.GetInt("Id"),
                StartTime = parameters.GetStringValue("StartTime"),
                EndTime = parameters.GetStringValue("EndTime"),
                OrderBy = parameters.GetInt("OrderBy")
            };

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = educationModule.GetProductGoodsPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.Sort,
                x.CoverImage,
                CategoryList = x.CategoryList.Select(y => new { y.Id, y.CategoryName }),
                x.SellingPrice,
                x.GoodsBuyNum,
                x.SalesNum,
                x.GoodsStatus,
                x.TenantId,
                x.MallBaseId,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 商品导出
        /// </summary>
        [HttpPost]
        public FileContentResult GetProductGoodsListToExcel()
        {
            var parms = RequestParm;
            RB_Goods_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Extend>(parms.msg.ToString());
            string ExcelName = "课程列表" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            ExcelDataSource header = new ExcelDataSource()
            {
                ExcelRows = new List<ExcelColumn>(30) {
                    new ExcelColumn(value: "序号") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "课程名称") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "原价") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "成本价") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "课程详情") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "课程封面图") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "课程封面视频") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "售价") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "赠送积分") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "赠送积分类型") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "可抵扣积分") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "可抵扣积分类型") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "允许多件累计折扣") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "自定义分享图片") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "自定义分享标题") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "排序") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "是否单独区域购买") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "区域限购详情") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "关联讲师") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER }
                }
            };

            slist.Add(header);

            try
            {
                demodel.TenantId = parms.TenantId;
                demodel.MallBaseId = parms.MallBaseId;
                var list = educationModule.GetProductGoodsPageListToExcel(1, 10000, out long count, demodel);
                #region 组装数据
                int Num = 0;
                foreach (var item in list)
                {
                    Num++;
                    string AreaList = "";
                    if (item.IsAreaBuy == 1)
                    {
                        AreaList = JsonConvert.SerializeObject(item.AreaList.Select(x => new
                        {
                            x.Id,
                            x.GoodsId,
                            x.AreaId,
                            x.AreaName,
                            x.AreaType
                        }));
                    }

                    ExcelDataSource datarow = new ExcelDataSource()
                    {
                        ExcelRows = new List<ExcelColumn>(30) {
                            new ExcelColumn(value:Num.ToString()){ },
                            new ExcelColumn(value:item.Name){ },
                            new ExcelColumn(value:(item.OriginalPrice??0).ToString()){ },
                            new ExcelColumn(value:(item.CostPrice??0).ToString()){ },
                            new ExcelColumn(value:item.GoodsDetails){ },
                            new ExcelColumn(value:item.CoverImage){ },
                            new ExcelColumn(value:item.VideoAddress){ },
                            new ExcelColumn(value:(item.SellingPrice??0).ToString()){ },
                            new ExcelColumn(value:(item.IntegralPresent??0).ToString()){ },
                            new ExcelColumn(value:(item.IntegralPresentType??0).ToString()){ },
                            new ExcelColumn(value:(item.PointsDeduction??0).ToString()){ },
                            new ExcelColumn(value:(item.PointsDeductionType??0).ToString()){ },
                            new ExcelColumn(value:(item.IsMultipleDeduction??0).ToString()){ },
                            new ExcelColumn(value:item.CustomShareImage ??""){ },
                            new ExcelColumn(value:item.CustomShareTitles ??""){ },
                            new ExcelColumn(value:(item.Sort??0).ToString()){ },
                            new ExcelColumn(value:(item.IsAreaBuy??0).ToString()){ },
                            new ExcelColumn(value:AreaList.ToString()){ },
                            new ExcelColumn(value:item.TeacherName){ }
                        }
                        ,
                        ColumnHight = 30
                    };
                    slist.Add(datarow);
                }
                #endregion

                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);

                return File(byteData, "application/octet-stream", ExcelName);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, string.Format("GetFileFromWebApi_requestData: {0}", JsonHelper.Serialize(RequestParm)));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }

        }

        /// <summary>
        /// 获取商品详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetGoodsInfo()
        {
            var req = RequestParm;
            JObject prams = JObject.Parse(req.msg.ToString());
            int GoodsId = prams.GetInt("GoodsId", 0);
            if (GoodsId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            var model = educationModule.GetProductGoodsInfo(GoodsId, req.TenantId, req.MallBaseId);
            var MarketingLogo = new MarketingLogoItem();
            if (!string.IsNullOrEmpty(model?.MarketingLogo))
            {
                try
                {
                    MarketingLogo = JsonHelper.DeserializeObject<MarketingLogoItem>(model?.MarketingLogo);
                }
                catch
                {
                    MarketingLogo = new MarketingLogoItem();
                }
            }
            return ApiResult.Success("", new
            {
                model?.Id,
                model?.Name,
                model?.CarouselImageList,
                model?.VideoAddress,
                model?.CustomShareTitles,
                model?.CustomShareImage,
                model?.GoodsStatus,
                model?.Sort,
                model?.SellingPrice,
                model?.OriginalPrice,
                model?.CostPrice,
                model?.IsAreaBuy,
                model?.IntegralPresent,
                model?.IntegralPresentType,
                model?.PointsDeduction,
                model?.PointsDeductionType,
                model?.IsMultipleDeduction,
                model?.GoodsDetails,
                model?.SeparateDistribution,
                model?.SeparateDistributionType,
                model?.SeparateDistributionMoneyType,
                model?.EnjoyMember,
                model?.SeparateSetMember,
                model?.SupplierId,
                model?.Commission,
                model?.IsLiveGoods,
                model?.SalesNum,
                CategoryList = model?.CategoryList.Select(x => new
                {
                    x.Id,
                    x.CategoryId,
                    x.CategoryName
                }),
                AreaList = model?.AreaList.Select(x => new
                {
                    x.Id,
                    x.AreaId,
                    x.AreaName,
                    x.AreaType
                }),
                DistributionCommissionList = model?.DistributionCommissionList.Select(x => new
                {
                    x.Id,
                    x.DistributorGrade,
                    x.OneCommission,
                    x.SpecificationSort,
                    x.ThreeCommission,
                    x.TwoCommission
                }),
                DistributionCommissionTreeList = model?.DistributionCommissionTreeList.Select(x => new
                {
                    x.Id,
                    x.SpecificationSort,
                    x.AttrList,
                    GradeCommissionList = x.GradeCommissionList.Select(y => new
                    {
                        y.DistributorGrade,
                        y.OneCommission,
                        y.ThreeCommission,
                        y.TwoCommission
                    })
                }),
                MemberPriceList = model?.MemberPriceList.Select(x => new
                {
                    x.Id,
                    x.MemberGrade,
                    x.MemberPrice,
                    x.SpecificationSort
                }),
                MemberPriceTreeList = model?.MemberPriceTreeList.Select(x => new
                {
                    x.Id,
                    x.SpecificationSort,
                    x.AttrList,
                    GradePriceList = x.GradePriceList.Select(y => new
                    {
                        y.MemberGrade,
                        y.MemberPrice
                    })
                }),
                model?.Advertising,
                model?.SubName,
                MarketingLogo,
                model?.IntegralComment,
                model?.IntegralCommentType,
                model?.GoodsPageType,
                GoodsPageTypeName = model?.GoodsPageType.GetEnumName() ?? "",
                TeacherList = model?.TeacherList.Select(x => new
                {
                    x.TeacherId,
                    x.Name,
                    x.TeacherLogo
                }),
                CourseList = model?.CourseList.Select(x => new
                {
                    x.Id,
                    x.Sort,
                    x.SortName,
                    x.Name,
                    x.Type,
                    TypeName = x.Type.GetEnumName(),
                    x.IsTrySee,
                    x.Number,
                    x.IsCache,
                    x.FilePath,
                    x.PathType,
                    x.VideoImage,
                    x.VideoTime,
                    x.IsImageOK,
                    ImageList = !string.IsNullOrEmpty(x.Image) && x.Image != "[]" ? JsonConvert.DeserializeObject<List<CourseImageModel>>(x.Image) : new List<CourseImageModel>()
                }),
                CourseLableList = !string.IsNullOrEmpty(model?.CourseLable) && model?.CourseLable != "[]" ? JsonConvert.DeserializeObject<List<string>>(model?.CourseLable) : new List<string>()
            });
        }

        /// <summary>
        /// 获取课程附件类型枚举
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetGoodsCourseTypeEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(GoodsCourseTypeEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 新增修改商品信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetGoodsInfo()
        {
            var parms = RequestParm;
            JObject jObj = JObject.Parse(RequestParm.msg.ToString());
            RB_Goods_Extend demodel = new RB_Goods_Extend()
            {
                Advertising = jObj.GetStringValue("Advertising"),
                Commission = jObj.GetDecimal("Commission"),
                CostPrice = jObj.GetDecimal("CostPrice"),
                CustomShareImage = jObj.GetStringValue("CustomShareImage"),
                CustomShareTitles = jObj.GetStringValue("CustomShareTitles"),
                EnjoyMember = jObj.GetInt("EnjoyMember"),
                GoodsDetails = jObj.GetStringValue("GoodsDetails"),
                GoodsPageType = (GoodsPageTypeEnum)jObj.GetInt("GoodsPageType"),
                GoodsStatus = jObj.GetInt("GoodsStatus"),
                Id = jObj.GetInt("Id"),
                IntegralComment = jObj.GetInt("IntegralComment"),
                IntegralCommentType = jObj.GetInt("IntegralCommentType"),
                IntegralPresent = jObj.GetInt("IntegralPresent"),
                IntegralPresentType = jObj.GetInt("IntegralPresentType"),
                IsAreaBuy = jObj.GetInt("IsAreaBuy"),
                IsLiveGoods = jObj.GetInt("IsLiveGoods"),
                Name = jObj.GetStringValue("Name"),
                OriginalPrice = jObj.GetDecimal("OriginalPrice"),
                PointsDeduction = jObj.GetDecimal("PointsDeduction"),
                PointsDeductionType = jObj.GetInt("PointsDeductionType"),
                SalesNum = jObj.GetInt("SalesNum"),
                SellingPrice = jObj.GetDecimal("SellingPrice"),
                SeparateDistribution = jObj.GetInt("SeparateDistribution"),
                SeparateDistributionMoneyType = jObj.GetInt("SeparateDistributionMoneyType"),
                SeparateDistributionType = jObj.GetInt("SeparateDistributionType"),
                SeparateSetMember = jObj.GetInt("SeparateSetMember"),
                Sort = jObj.GetInt("Sort"),
                SubName = jObj.GetStringValue("SubName"),
                SupplierId = jObj.GetInt("SupplierId"),
                UseDay = jObj.GetInt("UseDay"),
                VideoAddress = jObj.GetStringValue("VideoAddress"),
            };
            demodel.TeacherList = JsonHelper.DeserializeObject<List<RB_Goods_WK_Teacher_Extend>>(jObj.GetStringValue("TeacherList"));
            demodel.MemberPriceTreeList = JsonHelper.DeserializeObject<List<RB_Goods_MemberPrice_Extend>>(jObj.GetStringValue("MemberPriceTreeList"));
            demodel.MemberPriceList = JsonHelper.DeserializeObject<List<RB_Goods_MemberPrice_Extend>>(jObj.GetStringValue("MemberPriceList"));
            demodel.DistributionCommissionTreeList = JsonHelper.DeserializeObject<List<RB_Goods_DistributionCommission_Extend>>(jObj.GetStringValue("DistributionCommissionTreeList"));
            demodel.DistributionCommissionList = JsonHelper.DeserializeObject<List<RB_Goods_DistributionCommission_Extend>>(jObj.GetStringValue("DistributionCommissionList"));
            demodel.CourseList = JsonHelper.DeserializeObject<List<RB_Goods_WK_Course_Extend>>(jObj.GetStringValue("CourseList"));
            demodel.CourseLableList = JsonHelper.DeserializeObject<List<string>>(jObj.GetStringValue("CourseLableList"));
            demodel.CategoryList = JsonHelper.DeserializeObject<List<RB_Goods_Category_Extend>>(jObj.GetStringValue("CategoryList"));
            demodel.CarouselImageList = JsonHelper.DeserializeObject<List<RB_ImageCommonModel>>(jObj.GetStringValue("CarouselImageList"));
            demodel.AreaList = JsonHelper.DeserializeObject<List<RB_Goods_Area_Extend>>(jObj.GetStringValue("AreaList"));
            var marketingLogo = JsonHelper.DeserializeObject<MarketingLogoItem>(jObj.GetStringValue("MarketingLogo"));
            demodel.MarketingLogo = JsonHelper.Serialize(marketingLogo);

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;

            if (string.IsNullOrEmpty(demodel.Name))
            {
                return ApiResult.ParamIsNull("请输入商品名称");
            }
            if (demodel.CarouselImageList == null || !demodel.CarouselImageList.Any())
            {
                return ApiResult.ParamIsNull("请添加商品轮播图");
            }
            demodel.CarouselImage = JsonConvert.SerializeObject(demodel.CarouselImageList.Select(x => x.Path));
            if ((demodel.SellingPrice ?? 0) < 0)
            {
                return ApiResult.ParamIsNull("请输入售价");
            }
            if ((demodel.OriginalPrice ?? 0) < 0)
            {
                return ApiResult.ParamIsNull("请输入原价");
            }
            #region 教师验证
            if (demodel.TeacherList == null || !demodel.TeacherList.Any())
            {
                return ApiResult.ParamIsNull("请选择讲师列表");
            }
            foreach (var item in demodel.TeacherList)
            {
                if ((item.TeacherId ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("讲师列表数据有误");
                }
            }
            #endregion

            #region 课程验证
            if (demodel.CourseList == null || !demodel.CourseList.Any())
            {
                return ApiResult.ParamIsNull("请选择课程列表");
            }
            foreach (var item in demodel.CourseList)
            {
                if (item.Sort <= 0)
                {
                    return ApiResult.ParamIsNull();
                }
                if (string.IsNullOrEmpty(item.SortName))
                {
                    return ApiResult.ParamIsNull("请传递章节名称");
                }
                if (string.IsNullOrEmpty(item.Name))
                {
                    return ApiResult.ParamIsNull("请传递课程名称");
                }
                if (item.Type <= 0)
                {
                    return ApiResult.ParamIsNull("请传递课程附件类型");
                }
                item.IsTrySee ??= 1;
                item.Number ??= 1;
                item.IsCache ??= 2;
                if (string.IsNullOrEmpty(item.FilePath))
                {
                    return ApiResult.ParamIsNull("请传递附件");
                }
                if (item.Type == GoodsCourseTypeEnum.Video)
                {
                    if (string.IsNullOrEmpty(item.VideoImage))
                    {
                        return ApiResult.ParamIsNull("请传递视频封面图");
                    }
                    if ((item.VideoTime ?? 0) < 0)
                    {
                        return ApiResult.ParamIsNull("请传递视频时长");
                    }
                }
            }

            #endregion

            demodel.IsCustomSpecification ??= 2;
            demodel.DefaultSpecificationName = "默认";
            demodel.InventoryNum ??= 0;
            List<Model.Extend.User.RB_Distributor_Grade_Extend> DGradeList = null;
            List<Model.Extend.User.RB_Member_Grade_Extend> MGradeList = null;

            #region 默认值
            demodel.VideoAddress ??= "";
            demodel.CustomShareTitles ??= "";
            demodel.CustomShareImage ??= "";
            demodel.GoodsStatus ??= 2;
            demodel.Sort ??= 0;
            demodel.CostPrice ??= 0;
            demodel.IsGoodsNegotiable ??= 2;
            demodel.SalesNum ??= 0;
            demodel.GoodsNumbers ??= "";
            demodel.GoodsWeight ??= 0;
            demodel.IsDefaultService ??= 1;
            if (demodel.IsDefaultService == 2)
            {
                if (demodel.ServiceList == null || !demodel.ServiceList.Any())
                {
                    return ApiResult.ParamIsNull("请选择商品服务");
                }
                demodel.GoodsService = JsonConvert.SerializeObject(demodel.ServiceList.Select(x => x.Id));
            }
            else
            {
                demodel.GoodsService = "[]";
            }
            demodel.FreightId ??= 0;
            demodel.FormsId ??= 0;
            demodel.LimitBuyGoodsNum ??= -1;
            demodel.LimitBuyOrderNum ??= -1;
            demodel.FullNumPinkage ??= 0;
            demodel.FullMoneyPinkage ??= 0;

            demodel.IsAreaBuy ??= 2;
            if (demodel.IsAreaBuy == 1)
            {
                if (demodel.AreaList == null || !demodel.AreaList.Any())
                {
                    return ApiResult.ParamIsNull("请选择区域");
                }
            }
            demodel.IntegralPresent ??= 0;
            demodel.IntegralPresentType ??= 1;
            demodel.PointsDeduction ??= 0;
            demodel.PointsDeductionType ??= 1;
            demodel.IsMultipleDeduction ??= 2;

            demodel.Status = 0;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            #endregion
            demodel.SeparateDistribution ??= 2;
            demodel.SeparateDistributionType ??= 1;
            if (demodel.SeparateDistribution == 1)
            {
                //获取所有分销商等级
                if (DGradeList == null)
                {
                    DGradeList = educationModule.GetDistributorGradeList(new Model.Extend.User.RB_Distributor_Grade_Extend() { Enabled = 1, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    DGradeList.Add(new Model.Extend.User.RB_Distributor_Grade_Extend()
                    {
                        Grade = 0,
                        Name = "默认等级",
                        Id = 0
                    });
                }
                if (demodel.SeparateDistributionType == 1)
                {
                    if (demodel.DistributionCommissionList == null || !demodel.DistributionCommissionList.Any())
                    {
                        return ApiResult.ParamIsNull("请传递分销佣金列表");
                    }
                    //转换
                    List<RB_Goods_DistributionCommission_Extend> Rlist = new List<RB_Goods_DistributionCommission_Extend>();
                    foreach (var item in demodel.DistributionCommissionList)
                    {
                        if (item.GradeCommissionList == null || !item.GradeCommissionList.Any())
                        {
                            return ApiResult.ParamIsNull("请传递分销佣金列表");
                        }
                        foreach (var qitem in item.GradeCommissionList)
                        {
                            Rlist.Add(new RB_Goods_DistributionCommission_Extend()
                            {
                                DistributorGrade = qitem.DistributorGrade,
                                Id = 0,
                                SpecificationSort = item.SpecificationSort,
                                OneCommission = qitem.OneCommission,
                                TwoCommission = qitem.TwoCommission,
                                ThreeCommission = qitem.ThreeCommission
                            });
                        }
                    }
                    if (Rlist.Any())
                    {
                        demodel.DistributionCommissionList = Rlist;
                    }
                    //普通设置  直接根据等级验证数量
                    if (DGradeList.Count() != demodel.DistributionCommissionList.Count())
                    {
                        return ApiResult.ParamIsNull("分销佣金列表数量不正确");
                    }
                    foreach (var item in DGradeList)
                    {
                        var defaultModel = demodel.DistributionCommissionList.Where(x => x.DistributorGrade == item.Id).FirstOrDefault();
                        if (defaultModel == null)
                        {
                            return ApiResult.ParamIsNull("分销佣金" + item.Name + "不存在");
                        }
                        defaultModel.OneCommission ??= 0;
                        defaultModel.TwoCommission ??= 0;
                        defaultModel.ThreeCommission ??= 0;
                        defaultModel.SpecificationSort = "";
                    }
                }
                else
                {
                    if (demodel.IsCustomSpecification != 1)
                    {
                        return ApiResult.ParamIsNull("无法开启详细设置");
                    }
                }
            }
            demodel.SeparateDistributionMoneyType ??= 1;
            demodel.EnjoyMember ??= 2;
            demodel.SeparateSetMember ??= 2;
            if (demodel.EnjoyMember == 1 && demodel.SeparateSetMember == 1)
            {
                //获取所有会员等级
                if (MGradeList == null)
                {
                    MGradeList = educationModule.GetMemberGradeList(new Model.Extend.User.RB_Member_Grade_Extend() { Enabled = 1, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }
                if (!MGradeList.Any())
                {
                    return ApiResult.ParamIsNull("单独设置会员价需先添加会员等级");
                }
                if (demodel.IsCustomSpecification == 2)
                {
                    if (demodel.MemberPriceList == null || !demodel.MemberPriceList.Any())
                    {
                        return ApiResult.ParamIsNull("请传递会员价格列表");
                    }
                    //转换
                    List<RB_Goods_MemberPrice_Extend> Rlist = new List<RB_Goods_MemberPrice_Extend>();
                    foreach (var item in demodel.MemberPriceList)
                    {
                        if (item.GradePriceList == null || !item.GradePriceList.Any())
                        {
                            return ApiResult.ParamIsNull("请传递会员价格列表");
                        }
                        foreach (var qitem in item.GradePriceList)
                        {
                            Rlist.Add(new RB_Goods_MemberPrice_Extend()
                            {
                                MemberGrade = qitem.MemberGrade,
                                Id = 0,
                                SpecificationSort = item.SpecificationSort,
                                MemberPrice = qitem.MemberPrice
                            });
                        }
                    }
                    if (Rlist.Any())
                    {
                        demodel.MemberPriceList = Rlist;
                    }
                    if (MGradeList.Count() != demodel.MemberPriceList.Count())
                    {
                        return ApiResult.ParamIsNull("会员价格列表数量不正确");
                    }
                    foreach (var item in MGradeList)
                    {
                        var defaultModel = demodel.MemberPriceList.Where(x => x.MemberGrade == item.Id).FirstOrDefault();
                        if (defaultModel == null)
                        {
                            return ApiResult.ParamIsNull("会员价格" + item.Name + "不存在");
                        }
                        defaultModel.MemberPrice ??= 0;
                        defaultModel.SpecificationSort = "";
                    }
                }
            }
            demodel.IsQuickBuy ??= 2;
            demodel.IsSellWell ??= 2;
            demodel.GoodsType ??= Common.Enum.Goods.OrderTypeEnum.KCGoods;
            demodel.GoodsStatus ??= 2;

            demodel.IsProxy ??= 2;
            demodel.ProxyType ??= 1;
            demodel.ProxyRises ??= 0;
            demodel.ProxyMoney ??= 0;
            demodel.IsProcurement = 2;//新增时

            demodel.PresentFXGrade ??= 0;//赠送粉象等级
            demodel.PresentFXMonth ??= 0;

            demodel.Advertising ??= "";//广告词
            demodel.SubName ??= "";//副标题
            demodel.IsLiveGoods ??= 2;//是否直播商品  1是  2否
            demodel.SendArea ??= "";//发货地
            demodel.GoodsClassify = 2;
            demodel.IntegralComment ??= 0;//评论反积分
            demodel.IntegralCommentType ??= 1;
            demodel.GoodsPageType ??= GoodsPageTypeEnum.All;
            demodel.CourseScore ??= 0;
            demodel.CourseLableList ??= new List<string>();
            demodel.CourseLable = JsonConvert.SerializeObject(demodel.CourseLableList);

            bool flag = educationModule.SetProductGoodsInfo(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 删除商品
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelGoodsInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int GoodsId = parms.GetInt("GoodsId", 0);
            if (GoodsId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            bool flag = educationModule.DelProcudtGoodsInfo(GoodsId, req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 上下架商品
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetGoodsStatusInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int GoodsId = parms.GetInt("GoodsId", 0);
            if (GoodsId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            bool flag = educationModule.SetGoodsStatusInfo(GoodsId, req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 批量上下架商品
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetGoodsBatchStatusInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            string GoodsIds = parms.GetStringValue("GoodsIds");
            int Type = parms.GetInt("Type", 1);//类型 1上架  2下架
            if (string.IsNullOrEmpty(GoodsIds))
            {
                return ApiResult.ParamIsNull();
            }

            bool flag = educationModule.SetGoodsBatchStatusInfo(GoodsIds, Type, req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }
        #endregion

        #region 教师信息
        [HttpPost]
        public ApiResult GetTeacherPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_Education_Teacher_Extend demodel = JsonConvert.DeserializeObject<RB_Education_Teacher_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            //demodel.TeacherStatus = -1;
            var list = educationModule.GetTeacherPageListRepository(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ID,
                x.TeacherLogo,
                x.Name,
                Score = x.Score == 0 ? "暂无" : x.Score.ToString(),
                x.OrderNum,
                x.GoodsList,
                x.GoodsNum,
                CreateDateStr = x.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                x.TeacherStatus,
                x.Telephone,
                x.Major,
                x.WorkYears,
                x.Nationality,
                x.ForeignersUrl,
                x.LableName,
                LableNameList = string.IsNullOrWhiteSpace(x.LableName) ? new List<string>() : JsonConvert.DeserializeObject<List<string>>(x.LableName),
                GoodCourseList = string.IsNullOrWhiteSpace(x.GoodCourse) ? new List<string>() : JsonConvert.DeserializeObject<List<string>>(x.GoodCourse)
            });
            return ApiResult.Success("", pagelist);
        }


        /// <summary>
        /// 上下架教师状态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult EnableTeacherInfo()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            string idInfo = parmsJob.GetStringValue("Ids");
            int teacherStatus = parmsJob.GetInt("TeacherStatus", 0);
            if (string.IsNullOrWhiteSpace(idInfo))
            {
                return ApiResult.Failed("请传递参数");
            }
            if (teacherStatus == 0)
            {
                return ApiResult.Failed("请选择您要操作的类型");
            }
            bool flag = educationModule.EnableTeacherInfo(idInfo.Split(",").ToList(), teacherStatus, UserInfo.TenantId, parms.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }



        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetTeacherModel()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Education_Teacher_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            query.TeacherStatus = -1;
            var oldLogisticsModel = educationModule.GetTeacherModel(query);
            if (oldLogisticsModel == null)
            {
                oldLogisticsModel = new RB_Education_Teacher_Extend();
            }
            if (!string.IsNullOrWhiteSpace(oldLogisticsModel.LableName))
            {
                oldLogisticsModel.LableNameList = JsonConvert.DeserializeObject<List<string>>(oldLogisticsModel.LableName);
            }
            if (!string.IsNullOrWhiteSpace(oldLogisticsModel.GoodCourse))
            {
                oldLogisticsModel.GoodCourseList = JsonConvert.DeserializeObject<List<string>>(oldLogisticsModel.GoodCourse);
            }
            return ApiResult.Success("", oldLogisticsModel);
        }


        /// <summary>
        /// 获取全部教师
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetTeacherList()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Education_Teacher_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            query.TeacherStatus = 1;
            var list = educationModule.GetTeacherList(query);
            var result = list.Select(x => new { x.ID, x.Name, x.TeacherLogo, x.Score });
            return ApiResult.Success("", result);
        }


        /// <summary>
        /// 保存教师信息
        /// </summary>
        /// <returns></returns>
        public ApiResult AddOrUpdateTeacher()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Education_Teacher_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            if (query == null)
            {
                return ApiResult.Failed("请传入教师信息");
            }
            else
            {
                if (string.IsNullOrWhiteSpace(query.Name))
                {
                    return ApiResult.Failed("请输入教师名称");
                }
                if (string.IsNullOrWhiteSpace(query.TeacherLogo))
                {
                    return ApiResult.Failed("请上传教师头像");
                }
                if (string.IsNullOrWhiteSpace(query.Telephone))
                {
                    return ApiResult.Failed("请输入联系电话");
                }
                if (string.IsNullOrWhiteSpace(query.Introduction))
                {
                    return ApiResult.Failed("请输入简介");
                }
                if (query.GoodCourseList == null || !query.GoodCourseList.Any())
                {
                    return ApiResult.Failed("请输入擅长课程");
                }
                if (query.ID == 0)
                {
                    query.CreateDate = System.DateTime.Now;
                }
                query.UpdateDate = System.DateTime.Now;
                if (query.LableNameList != null && query.LableNameList.Any())
                {
                    query.LableName = JsonConvert.SerializeObject(query.LableNameList);
                }
                else
                {
                    query.LableName = "";
                }
                if (query.GoodCourseList != null && query.GoodCourseList.Any())
                {
                    query.GoodCourse = JsonConvert.SerializeObject(query.GoodCourseList);
                }
                else
                {
                    query.GoodCourse = "";
                }
                bool result = educationModule.AddOrUpdateTeacher(query);
                if (result)
                {
                    return ApiResult.Success("教师信息保存成功");
                }
                else
                {
                    return ApiResult.Failed("教师信息保存失败");
                }
            }
        }
        #endregion



        #region 课程卡

        [HttpPost]
        public ApiResult GetDiscountCouponPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_Education_Coupon_Extend demodel = JsonConvert.DeserializeObject<RB_Education_Coupon_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = educationModule.GetDiscountCouponPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ID,
                x.Name,
                x.HeXiao,
                x.CouponIco,
                UseTypeStr = Mall.Common.Plugin.EnumHelper.GetEnumName(x.UseType),
                StartDate = x.StartDate.HasValue ? x.StartDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                CreateDate = x.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                x.IndateType,
                x.IndateDay,
                EndDate = x.EndDate.HasValue ? x.EndDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.TotalNum,
                ResidueNum = x.ReceiveNum,
                x.PickupCenter,
                x.SmallShopName,
                x.SmallShopId,
                x.IsZanYangUse
            });
            return ApiResult.Success("", pagelist);
        }


        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDiscountCouponDetail()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Education_Coupon_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var oldLogisticsModel = educationModule.GetDiscountCouponList(query).FirstOrDefault();
            if (oldLogisticsModel == null)
            {
                oldLogisticsModel = new RB_Education_Coupon_Extend
                {
                    IndateType = Common.Enum.MarketingCenter.IndateTypeEnum.DayHorizon
                };
            }
            return ApiResult.Success("", oldLogisticsModel);
        }


        /// <summary>
        /// 保存课程卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult AddOrUpdateDiscountCoupon()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Education_Coupon_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            if (query == null)
            {
                return ApiResult.Failed("请传入课程卡信息");
            }
            else
            {
                if (string.IsNullOrWhiteSpace(query.Name))
                {
                    return ApiResult.Failed("请输入课程卡名称");
                }
                if (query.IndateType == Common.Enum.MarketingCenter.IndateTypeEnum.DayHorizon)
                {
                    if (query.IndateDay == 0)
                    {
                        return ApiResult.Failed("请输入有效期天数");
                    }
                }
                else
                {
                    if (!query.StartDate.HasValue || !query.EndDate.HasValue)
                    {
                        return ApiResult.Failed("开始日期或结束日期必填");
                    }
                    if (query.StartDate > query.EndDate)
                    {
                        return ApiResult.Failed("开始日期必须小于结束日期");
                    }
                }
                if (query.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Category || query.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Product)
                {
                    if (query.ProductList == null || !query.ProductList.Any())
                    {
                        return ApiResult.Failed(query.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Category ? "请选择商品类别" : "请选择商品");
                    }
                }
                if (query.TotalNum == 0)
                {
                    return ApiResult.Failed("请输入可发放数量");
                }

                if (string.IsNullOrWhiteSpace(query.Describe))
                {
                    return ApiResult.Failed("请输入课程卡描述");
                }
                if (query.ID == 0)
                {
                    query.CreateDate = System.DateTime.Now;
                }

                query.UpdateDate = System.DateTime.Now;
                bool result = educationModule.AddOrUpdateDiscountCoupon(query);
                if (result)
                {
                    return ApiResult.Success("课程卡信息保存成功");
                }
                else
                {
                    return ApiResult.Failed("课程卡信息保存失败");
                }
            }
        }

        /// <summary>
        /// 删除课程卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelDiscountCoupon()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            int Id = parmsJob.GetInt("Id", 0);
            if (Id <= 0)
            {
                return ApiResult.Failed("请传递参数");
            }
            bool flag = educationModule.DelDiscountCoupon(Id, UserInfo.TenantId, parms.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 加入领劵中心
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult UpdatePickupType()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            int Id = parmsJob.GetInt("Id", 0);
            if (Id <= 0)
            {
                return ApiResult.Failed("请传递参数");
            }
            bool flag = educationModule.UpdatePickupType(Id, UserInfo.TenantId, parms.MallBaseId);
            if (flag)
            {
                return ApiResult.Success("操作成功");
            }
            else
            {
                return ApiResult.Failed("操作失败");
            }
        }


        /// <summary>
        /// 发放课程卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GrantCoupon()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Education_Coupon_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            if (query == null)
            {
                return ApiResult.Failed("请传入课程卡信息");
            }
            else
            {
                var oldLogisticsModel = educationModule.GetDiscountCouponList(query).FirstOrDefault();
                if (oldLogisticsModel == null || oldLogisticsModel.ID == 0)
                {
                    return ApiResult.Failed("课程卡信息不存在，请核实后再操作");
                }
                if (string.IsNullOrWhiteSpace(query.UserIds))
                {
                    return ApiResult.Failed("请选择发放对象");
                }

                //获取领取课程卡用户的信息判断是否属于当前店铺
                var memberList = new List<RB_Member_User_Extend>();
                if (oldLogisticsModel.SmallShopId > 0)
                {
                    memberList = UserModule.GetMemberUserList(new RB_Member_User_Extend { TenantId = UserInfo.TenantId, MallBaseId = parms.MallBaseId, UserIds = query.UserIds });

                    var notSmallShopList = memberList.Where(x => x.SmallShopId != oldLogisticsModel.SmallShopId);
                    if (notSmallShopList != null && notSmallShopList.Any())
                    {
                        return ApiResult.Failed(string.Join(",", notSmallShopList.Select(x => x.Name) + "不属于当前店铺"));
                    }
                }
                List<RB_Education_MemberCoupon_Extend> list = new List<RB_Education_MemberCoupon_Extend>();
                for (int i = 0; i < query.GrantNum; i++)
                {
                    foreach (var item in query.UserIds.Split(","))
                    {
                        if (!string.IsNullOrWhiteSpace(item))
                        {
                            RB_Education_MemberCoupon_Extend memberCoupon = new RB_Education_MemberCoupon_Extend
                            {
                                Id = 0,
                                UserId = Convert.ToInt32(item),
                                Description = oldLogisticsModel.Describe,
                                CreateDate = System.DateTime.Now,
                                TenantId = oldLogisticsModel.TenantId,
                                MallBaseId = oldLogisticsModel.MallBaseId,
                                Remarks = "",
                                CouponId = oldLogisticsModel.ID,
                                Name = oldLogisticsModel.Name,
                                UseType = oldLogisticsModel.UseType,
                                HeXiao = oldLogisticsModel.HeXiao,
                                UseHeXiao = 0
                            };
                            if (oldLogisticsModel.IndateType == Common.Enum.MarketingCenter.IndateTypeEnum.DayHorizon)
                            {
                                memberCoupon.StartDate = System.DateTime.Now;
                                memberCoupon.EndDate = memberCoupon.StartDate.Value.AddDays(oldLogisticsModel.IndateDay);
                            }
                            else
                            {
                                memberCoupon.StartDate = oldLogisticsModel.StartDate;
                                memberCoupon.EndDate = oldLogisticsModel.EndDate;
                            }
                            list.Add(memberCoupon);
                        }
                    }
                }
                if (oldLogisticsModel.TotalNum != -1)
                {
                    if (oldLogisticsModel.TotalNum < list.Count())
                    {
                        return ApiResult.Failed("课程卡剩余" + oldLogisticsModel.TotalNum + "张");
                    }
                }
                bool result = educationModule.GrantCoupon(list, oldLogisticsModel);
                if (result)
                {
                    return ApiResult.Success("课程卡信息保存成功");
                }
                else
                {
                    return ApiResult.Failed("课程卡信息保存失败");
                }
            }
        }




        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAllDiscountCouponList()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Education_Coupon_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var oldLogisticsModel = educationModule.GetAllDiscountCouponList(query);
            return ApiResult.Success("", oldLogisticsModel);
        }




        /// <summary>
        /// 我的课程卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCouponPageListByMemberId()
        {
            var req = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_Education_Coupon_Extend demodel = JsonConvert.DeserializeObject<RB_Education_Coupon_Extend>(req.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = req.MallBaseId;
            var list = educationModule.GetMemberDisCouponList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Name,
                x.Describe,
                x.CouponIco,
                x.HeXiao,
                x.UseHeXiao,
                x.ID,
                x.MemberCouponId,
                CreateDate = x.CreateDate.ToString("yyyy-MM-dd HH:ss:mm"),
                StartDate = x.StartDate.HasValue ? x.StartDate.Value.ToString("yyyy-MM-dd HH:ss:mm") : "",
                EndDate = x.EndDate.HasValue ? x.EndDate.Value.ToString("yyyy-MM-dd HH:ss:mm") : "",
                UseTypeStr = ((int)x.UseType == 3 || (int)x.UseType == 4) ? x.UseType.GetEnumName() : (x.ProductList != null && x.ProductList.Any() ? string.Join("、", x.ProductList.Select(x => x.Relevance)) : ""),
                x.UseType,
                x.ProductList,
                x.PickupCenter,
                x.UseState,
                x.GetType
            });
            return ApiResult.Success("", pagelist);
        }





        /// <summary>
        /// 删除用户课程卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelMemberCoupon()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            int Id = parmsJob.GetInt("MemberCouponId", 0);
            if (Id <= 0)
            {
                return ApiResult.Failed("请传递参数");
            }
            bool flag = educationModule.DelMemberCoupon(Id, UserInfo.TenantId, parms.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        #endregion


        #region 自动发放课程卡
        /// <summary>
        /// 自动发放课程卡列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSelfMotionPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_Education_CSelfMotion_Extend demodel = JsonConvert.DeserializeObject<RB_Education_CSelfMotion_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = educationModule.GetSelfMotionPageLis(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ID,
                x.GrantNum,
                x.DiscountCouponName,
                TriggerTypeStr = Mall.Common.Plugin.EnumHelper.GetEnumName(x.TriggerType)

            });
            return ApiResult.Success("", pagelist);
        }


        /// <summary>
        /// 获取自动发放课程卡详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GettRepositoryList()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Education_CSelfMotion_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var oldLogisticsModel = educationModule.GettRepositoryList(query).FirstOrDefault();
            if (oldLogisticsModel == null)
            {
                oldLogisticsModel = new RB_Education_CSelfMotion_Extend();
            }
            else
            {
                if (oldLogisticsModel.IsAll == 1)
                {
                    oldLogisticsModel.UserList = new List<RB_Education_CSelfMotionMember_Extend>();
                    oldLogisticsModel.UserList = educationModule.GetSelfMotionMemberList(new RB_Education_CSelfMotionMember_Extend { TenantId = oldLogisticsModel.TenantId, MallBaseId = oldLogisticsModel.MallBaseId, SelfMotionId = oldLogisticsModel.ID });
                }

            }
            return ApiResult.Success("", oldLogisticsModel);
        }


        /// <summary>
        /// 保存自动发放课程卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult AddOrUpdateSelfMotion()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Education_CSelfMotion_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            if (query == null)
            {
                return ApiResult.Failed("请传入自动发放课程卡信息");
            }
            else
            {
                if (query.ID == 0)
                {
                    query.CreateDate = System.DateTime.Now;
                }
                if (query.IsAll == 1 && (query.UserList == null || !query.UserList.Any()))
                {
                    return ApiResult.Failed("请选择领取人信息");
                }
                query.UpdateDate = System.DateTime.Now;
                bool result = educationModule.AddOrUpdateSelfMotion(query);
                if (result)
                {
                    return ApiResult.Success("自动发放课程卡保存成功");
                }
                else
                {
                    return ApiResult.Failed("自动发放课程卡保存失败");
                }
            }
        }

        /// <summary>
        /// 删除自动发放课程卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelDiscountSelfMotion()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            int Id = parmsJob.GetInt("Id", 0);
            if (Id <= 0)
            {
                return ApiResult.Failed("请传递参数");
            }
            bool flag = educationModule.DelDiscountSelfMotion(Id, UserInfo.TenantId, parms.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }



        /// <summary>
        /// 获取触发事件枚举
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetTriggerTypeEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(Common.Enum.MarketingCenter.TriggerTypeEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }


        #endregion

        #region 资讯管理

        /// <summary>
        /// 资讯列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetArticlePageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_Education_Article_Extend demodel = JsonConvert.DeserializeObject<RB_Education_Article_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = educationModule.GetArticlePageListRepository(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ID,
                x.Name,
                CreateDateStr = x.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                x.ArticleStatus,
                x.IsComment,
                x.CommentNum,
                x.BrowseNum,
                x.FictitiousBrowseNum,
                x.ArticlePic,
                x.TeacherName,
                x.TeacherLogo,
                x.Major
            });
            return ApiResult.Success("", pagelist);
        }


        /// <summary>
        /// 上下架资讯状态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult EnableArticleInfo()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            string idInfo = parmsJob.GetStringValue("Ids");
            int articleStatus = parmsJob.GetInt("ArticleStatus", 0);
            if (string.IsNullOrWhiteSpace(idInfo))
            {
                return ApiResult.Failed("请传递参数");
            }
            if (articleStatus == 0)
            {
                return ApiResult.Failed("请选择您要操作的类型");
            }
            bool flag = educationModule.EnableArticleInfo(idInfo.Split(",").ToList(), articleStatus, UserInfo.TenantId, parms.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 删除资讯
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelArticleInfo()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            string idInfo = parmsJob.GetStringValue("Ids");
            if (string.IsNullOrWhiteSpace(idInfo))
            {
                return ApiResult.Failed("请传递参数");
            }

            bool flag = educationModule.DelArticleInfo(idInfo.Split(",").ToList(), UserInfo.TenantId, parms.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        public ApiResult GetArticleModel()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Education_Article_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            query.ArticleStatus = -1;
            var oldLogisticsModel = educationModule.GetArticleInfo(query);
            if (oldLogisticsModel == null)
            {
                oldLogisticsModel = new RB_Education_Article_Extend();
            }
            if (!string.IsNullOrWhiteSpace(oldLogisticsModel.LableName))
            {
                oldLogisticsModel.LableNameList = JsonConvert.DeserializeObject<List<string>>(oldLogisticsModel.LableName);
            }
            return ApiResult.Success("", oldLogisticsModel);
        }



        /// <summary>
        /// 保存资讯信息
        /// </summary>
        /// <returns></returns>
        public ApiResult AddOrUpdateArticle()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Education_Article_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            if (query == null)
            {
                return ApiResult.Failed("请传入资讯信息");
            }
            else
            {
                if (string.IsNullOrWhiteSpace(query.Name))
                {
                    return ApiResult.Failed("请输入资讯标题");
                }
                if (query.LableNameList == null || !query.LableNameList.Any())
                {
                    return ApiResult.Failed("请输入标签");
                }
                if (query.ID == 0)
                {
                    query.CreateDate = System.DateTime.Now;
                }
                query.UpdateDate = System.DateTime.Now;
                if (query.LableNameList != null && query.LableNameList.Any())
                {
                    query.LableName = JsonConvert.SerializeObject(query.LableNameList);
                }

                bool result = educationModule.AddOrUpdateArticle(query);
                if (result)
                {
                    return ApiResult.Success("资讯信息保存成功");
                }
                else
                {
                    return ApiResult.Failed("资讯信息保存失败");
                }
            }
        }
        #endregion

        #region 咨询评价
        /// <summary>
        /// 获取商品评论分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetArticleCommentPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Education_ArticleComment_Extend demodel = JsonConvert.DeserializeObject<RB_Education_ArticleComment_Extend>(parms.msg.ToString());

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = educationModule.GetArticleCommentPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ID,
                x.UserId,
                x.UserName,
                x.ArticleId,
                x.ArticleName,
                x.CommentScore,
                x.CommentGrade,
                CommentGradeName = x.CommentGrade.GetEnumName(),
                x.CommentImgList,
                x.Content,
                x.Reply,
                x.Is_Top,
                x.Is_Show,
                x.Is_Anonymity,
                x.PlatformSource,
                x.TenantId,
                x.MallBaseId,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
            });
            return ApiResult.Success("", pagelist);
        }


        /// <summary>
        /// 管理新增评论
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetArticleCommentInfo()
        {
            var req = RequestParm;
            RB_Education_ArticleComment_Extend demodel = JsonConvert.DeserializeObject<RB_Education_ArticleComment_Extend>(req.msg.ToString());
            if (string.IsNullOrEmpty(demodel.UserName))
            {
                return ApiResult.ParamIsNull("请输入用户名称");
            }
            if (!demodel.CreateDate.HasValue)
            {
                return ApiResult.ParamIsNull("请输入评论时间");
            }
            if (demodel.ArticleId <= 0)
            {
                return ApiResult.ParamIsNull("请选择咨询文章");
            }
            if (string.IsNullOrEmpty(demodel.Content))
            {
                return ApiResult.ParamIsNull("请输入评价内容");
            }
            if (!demodel.CommentScore.HasValue)
            {
                return ApiResult.ParamIsNull("请选择评分");
            }
            demodel.CommentGrade ??= Common.Enum.Goods.GoodsCommentTypeEnum.Praise;
            demodel.CommentScore ??= 5;
            if (demodel.CommentScore == 3 || demodel.CommentScore == 2)
            {
                demodel.CommentGrade = Common.Enum.Goods.GoodsCommentTypeEnum.Medium;
            }
            else if (demodel.CommentScore == 1)
            {
                demodel.CommentGrade = Common.Enum.Goods.GoodsCommentTypeEnum.Negative;
            }
            demodel.CommentImage = "";
            if (demodel.CommentImgList != null && demodel.CommentImgList.Any())
            {
                demodel.CommentImage = JsonConvert.SerializeObject(demodel.CommentImgList);
            }
            demodel.UserPhoto ??= 0;
            demodel.Is_Top ??= 2;
            demodel.Is_Show ??= 1;
            demodel.Is_Anonymity ??= 2;
            demodel.UserId ??= 0;
            demodel.Reply ??= "";

            demodel.TenantId = req.TenantId;
            demodel.MallBaseId = req.MallBaseId;
            demodel.Status = 0;
            demodel.UpdateDate = DateTime.Now;

            bool flag = educationModule.SetArticleCommentInfo(demodel);
            if (flag) { return ApiResult.Success(); } else { return ApiResult.Failed(); }
        }

        /// <summary>
        /// 批量操作
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetArticleCommentBatch()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            string CommentIds = parms.GetStringValue("CommentIds");
            int Type = parms.GetInt("Type", 1);//1批量回复   2批量隐藏  3批量显示  4批量置顶  5取消置顶  6批量删除
            string Content = parms.GetStringValue("Content");
            if (string.IsNullOrEmpty(CommentIds))
            {
                return ApiResult.ParamIsNull();
            }
            if (Type == 1)
            {
                if (string.IsNullOrEmpty(Content))
                {
                    return ApiResult.ParamIsNull("回复内容不能为空");
                }
            }
            bool flag = educationModule.SetArticleCommentBatch(CommentIds, Type, Content, req.TenantId, req.MallBaseId);
            if (flag) { return ApiResult.Success(); } else { return ApiResult.Failed(); }
        }
        #endregion

        #region 启动页管理
        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [RateValve(Policy = Policy.Ip, Limit = 10, Duration = 60)]
        public ApiResult GetEducationStartUpModel()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Education_StartUp>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var oldLogisticsModel = educationModule.GetEducationStartUpListRepository(query).FirstOrDefault();
            if (oldLogisticsModel == null)
            {
                oldLogisticsModel = new RB_Education_StartUp();
            }
            return ApiResult.Success("", oldLogisticsModel);
        }
        /// <summary>
        /// 保存教师信息
        /// </summary>
        /// <returns></returns>
        public ApiResult AddOrUpdateEducationStartUp()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Education_StartUp>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            if (query == null)
            {
                return ApiResult.Failed("请传入启动页信息");
            }
            else
            {
                if (query.IsShow == 1)
                {
                    if (string.IsNullOrWhiteSpace(query.PicUrl))
                    {
                        return ApiResult.Failed("请上传图片");
                    }
                    if (query.Seconds == 0)
                    {
                        return ApiResult.Failed("秒数必须大于0");
                    }
                }
                if (query.ID == 0)
                {
                    query.CreateDate = System.DateTime.Now;
                }
                query.UpdateDate = System.DateTime.Now;

                bool result = educationModule.AddOrUpdateEducationStartUp(query);
                if (result)
                {
                    return ApiResult.Success("启动页信息保存成功");
                }
                else
                {
                    return ApiResult.Failed("启动页信息保存失败");
                }
            }
        }
        #endregion


        #region 话题
        [HttpPost]
        public ApiResult GetEducationTalkPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            Rb_Education_Talk_Extend demodel = JsonConvert.DeserializeObject<Rb_Education_Talk_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = dynamicModule.GetEducationTalkPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.IsOpen,
                x.Content,
                x.CoverPhoto
            });
            return ApiResult.Success("", pagelist);
        }





        /// <summary>
        /// 获取新闻信息详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSetEducationTalk()
        {
            var qequest = RequestParm;
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var model = new Rb_Education_Talk_Extend()
            {
                Id = parms.GetInt("Id", 0),
                IsOpen = parms.GetInt("IsOpen", 2),
                CoverPhoto = parms.GetStringValue("CoverPhoto"),
                Content = parms.GetStringValue("Content")
            };
            model.MallBaseId = qequest.MallBaseId;
            model.TenantId = UserInfo.TenantId;
            if (model.Id == 0)
            {
                model.CreateBy = UserInfo.EmpId;
                model.CreateTime = System.DateTime.Now;
                model.Status = 0;
            }

            var extModel = dynamicModule.SetEducationTalk(model);
            return ApiResult.Success(data: extModel);
        }

        /// <summary>
        /// 获取话题详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetEducationTalkDetails()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            int id = parmsJob.GetInt("Id");
            if (id == 0)
            {
                return ApiResult.Failed("请传递参数");
            }

            var model = dynamicModule.GetEducationTalkList(new Rb_Education_Talk_Extend { TenantId = UserInfo.TenantId, MallBaseId = parms.MallBaseId, Id = id }).FirstOrDefault();
            if (model == null)
            {
                return ApiResult.Failed("数据不存在");
            }
            else
            {
                return ApiResult.Success("", model);
            }


        }


        /// <summary>
        /// 隐藏/显示话题
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult UpdateEducationTalkShow()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            int id = parmsJob.GetInt("Id");
            int isOpen = parmsJob.GetInt("IsOpen", 0);
            if (id == 0)
            {
                return ApiResult.Failed("请传递参数");
            }

            bool flag = dynamicModule.UpdateEducationTalkShow(new Rb_Education_Talk_Extend { TenantId = UserInfo.TenantId, MallBaseId = parms.MallBaseId, Id = id, IsOpen = isOpen });
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }


        /// <summary>
        /// 删除话题
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelEducationTalk()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            int id = parmsJob.GetInt("Id");
            if (id == 0)
            {
                return ApiResult.Failed("请传递参数");
            }

            bool flag = dynamicModule.DelEducationTalk(new Rb_Education_Talk_Extend { TenantId = UserInfo.TenantId, MallBaseId = parms.MallBaseId, Id = id });
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        #endregion



        #region 活动分类管理

        /// <summary>
        /// 获取商会活动类型分页列表
        /// </summary>
        /// <returns></returns>
        public ApiResult GetActivityTypePage()
        {
            ResultPageModel pageModel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            JObject jObj = JObject.Parse(RequestParm.msg.ToString());
            var query = new RB_Education_ActivityType_Extend()
            {
                TypeName = jObj.GetStringValue("TypeName")
            };
            query.MallBaseId = RequestParm.MallBaseId;
            query.TenantId = RequestParm.TenantId;
            var list = activityModule.GetActivityTypePageListRepository(pageModel.pageIndex, pageModel.pageSize, out long rowsCount, query);
            list.ForEach(x => x.LableNameList = string.IsNullOrWhiteSpace(x.LableName) ? new List<string>() : JsonConvert.DeserializeObject<List<string>>(x.LableName));
            pageModel.count = Convert.ToInt32(rowsCount);
            pageModel.pageData = list;
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 获取商会活动类型列表
        /// </summary>
        /// <returns></returns>
        public ApiResult GetCommerceActivityTypeList()
        {
            JObject jObj = JObject.Parse(RequestParm.msg.ToString());
            var query = new RB_Education_ActivityType_Extend()
            {
                TypeName = jObj.GetStringValue("TypeName")
            };
            query.MallBaseId = RequestParm.MallBaseId;
            query.TenantId = RequestParm.TenantId;
            var list = activityModule.GetActivityTypeListRepository(query);
            list.ForEach(x => x.LableNameList = string.IsNullOrWhiteSpace(x.LableName) ? new List<string>() : JsonConvert.DeserializeObject<List<string>>(x.LableName));
            return ApiResult.Success(data: list);
        }

        /// <summary>
        /// 新增修改商会活动类型
        /// </summary>
        /// <returns></returns>
        public ApiResult SetCommerceActivityType()
        {
            RB_Education_ActivityType_Extend extModel = JsonConvert.DeserializeObject<RB_Education_ActivityType_Extend>(RequestParm.msg.ToString());
            //JObject jObj = JObject.Parse(RequestParm.msg.ToString());
            //var extModel = new RB_Education_ActivityType_Extend()
            //{
            //    Id = jObj.GetInt("Id"),
            //    TypeName = jObj.GetStringValue("TypeName"),
            //    CoverImage = jObj.GetStringValue("CoverImage")
            //};
            extModel.Status = Common.Enum.DateStateEnum.Normal;
            extModel.MallBaseId = RequestParm.MallBaseId;
            extModel.TenantId = RequestParm.TenantId;
            Int32.TryParse(RequestParm.uid, out int Uid);
            extModel.CreateBy = Uid;
            extModel.CreateDate = DateTime.Now;
            extModel.UpdateBy = Uid;
            extModel.UpdateDate = DateTime.Now;
            if (extModel.LableNameList != null && extModel.LableNameList.Any())
            {
                extModel.LableName = JsonConvert.SerializeObject(extModel.LableNameList);
            }
            else
            {
                extModel.LableName = "";
            }
            var flag = activityModule.SetActivityTypeModule(extModel);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 获取商会活动类型详情
        /// </summary>
        /// <returns></returns>
        public ApiResult GetCommerceActivityType()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var Id = parms.GetInt("Id", 0);
            var extModel = activityModule.GetActivityTypeModule(Id);
            extModel.LableNameList = string.IsNullOrWhiteSpace(extModel.LableName) ? new List<string>() : JsonConvert.DeserializeObject<List<string>>(extModel.LableName);
            return ApiResult.Success(data: extModel);
        }

        /// <summary>
        /// 更新商户活动类型状态
        /// </summary>
        /// <returns></returns>
        public ApiResult RemoveCommerceActivityType()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var Id = parms.GetInt("Id", 0);
            var Status = parms.GetInt("Status", 0);
            var flag = activityModule.RemoveActivityTypeModule(Id, Status);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }
        #endregion


        #region 活动管理
        /// <summary>
        /// 获取商会活动分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetActivityPage()
        {
            ResultPageModel pageModel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            JObject jObj = JObject.Parse(RequestParm.msg.ToString());
            var query = new RB_Education_Activity_Extend()
            {
                ActivityName = jObj.GetStringValue("ActivityName"),
                SelectStartTimeStr = jObj.GetStringValue("SelectStartTimeStr"),
                SelectEndTimeStr = jObj.GetStringValue("SelectEndTimeStr"),
                SelectIsEnd = jObj.GetInt("SelectIsEnd", -1),
                Id = jObj.GetInt("Id", 0),
            };
            query.MallBaseId = RequestParm.MallBaseId;
            query.TenantId = RequestParm.TenantId;
            var list = activityModule.GetActivityPageListModule_V2(pageModel.pageIndex, pageModel.pageSize, out long rowsCount, query, isQuerySignup: true);
            pageModel.count = Convert.ToInt32(rowsCount);
            pageModel.pageData = list;
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 新增修改商会活动
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetActivity()
        {
            JObject jObj = JObject.Parse(RequestParm.msg.ToString());
            var extModel = new RB_Education_Activity_Extend()
            {
                Id = jObj.GetInt("Id"),
                ActivityName = jObj.GetStringValue("ActivityName"),
                StartTime = jObj.GetDateTime("StartTime"),
                EndTime = jObj.GetDateTime("EndTime"),
                CoverImg = jObj.GetStringValue("CoverImg"),
                ActivityType = jObj.GetInt("ActivityType"),
                ActivityInfo = jObj.GetStringValue("ActivityInfo"),
                SignStartTime = jObj.GetDateTime("SignStartTime"),
                SignEndTime = jObj.GetDateTime("SignEndTime"),
                IsFree = jObj.GetInt("IsFree", 1),
                Price = jObj.GetDecimal("Price"),
                IsCancelConfirm = jObj.GetInt("IsCancelConfirm", 2),
                PointNum = jObj.GetInt("PointNum", 0),
                AgeLimit = jObj.GetInt("AgeLimit", 0),
                StartAge = jObj.GetInt("StartAge", 0),
                EndAge = jObj.GetInt("EndAge", 0),
                //Label = jObj.GetInt("EndAge", 0),
                WoManNum = jObj.GetInt("WoManNum", 0),
                ManNum = jObj.GetInt("ManNum", 0),
                Distinguish = jObj.GetInt("Distinguish", 0),
                LonLat = jObj.GetStringValue("LonLat"),
                LocationName = jObj.GetStringValue("LocationName"),
                LnsideLimit = jObj.GetInt("LnsideLimit", 0),
            };
            try
            {
                extModel.ActivityTitleList = JsonConvert.DeserializeObject<List<RB_Education_ActivityTitle_Extend>>(jObj.GetStringValue("ActivityTitle"));
            }
            catch
            {
                extModel.ActivityTitleList = new List<RB_Education_ActivityTitle_Extend>();
            }
            extModel.Status = Common.Enum.DateStateEnum.Normal;
            extModel.MallBaseId = RequestParm.MallBaseId;
            extModel.TenantId = RequestParm.TenantId;
            Int32.TryParse(RequestParm.uid, out int Uid);
            extModel.CreateBy = Uid;
            extModel.CreateDate = DateTime.Now;
            extModel.UpdateBy = Uid;
            extModel.UpdateDate = DateTime.Now;
            if (extModel.IsFree == 1)
            {
                extModel.Price = 0;
            }
            if (extModel.Id > 0)
            {
                var model = activityModule.GetActivityModule(extModel.Id);
                if (model == null || model.Status == Common.Enum.DateStateEnum.Delete) { return ApiResult.Failed("活动不存在"); }

                //int ManPeopleNum = activityModule.GetActivityEnrollNum(extModel.Id, 1);
                //int WoManPeopleNum = activityModule.GetActivityEnrollNum(extModel.Id, 2);
                //if (extModel.Distinguish == 0)
                //{
                //    if (extModel.ManNum < ManPeopleNum) { return ApiResult.Failed("男已报名" + ManPeopleNum + "人、不能低于此数量"); }
                //    if (extModel.WoManNum < WoManPeopleNum) { return ApiResult.Failed("女已报名" + WoManPeopleNum + "人、不能低于此数量"); }
                //}
                //else
                //{
                int ManPeopleNum = activityModule.GetActivityEnrollNum(extModel.Id, 0);
                if (extModel.ManNum < ManPeopleNum) { return ApiResult.Failed("已报名" + ManPeopleNum + "人、不能低于此数量"); }
                // }
            }

            var flag = activityModule.SetActivityModule(extModel);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }


        /// <summary>
        /// 新增修改商会活动
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSetActivityPlan()
        {
            JObject jObj = JObject.Parse(RequestParm.msg.ToString());
            var extModel = new RB_Education_Activity_Extend()
            {
                Id = jObj.GetInt("Id"),
            };
            try
            {
                extModel.ActivityTitleList = JsonConvert.DeserializeObject<List<RB_Education_ActivityTitle_Extend>>(jObj.GetStringValue("ActivityTitle"));
            }
            catch
            {
                extModel.ActivityTitleList = new List<RB_Education_ActivityTitle_Extend>();
            }
            extModel.MallBaseId = RequestParm.MallBaseId;
            extModel.TenantId = RequestParm.TenantId;
            var flag = activityModule.SetActivityPlanModule(extModel);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 获取商会活动详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetActivity()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var Id = parms.GetInt("Id", 0);
            var extModel = activityModule.GetActivityModule(Id);

            if (extModel != null && extModel.Id > 0)
            {
                extModel.ActivityTitleList = new List<RB_Education_ActivityTitle_Extend>();
                extModel.ActivityTitleList = activityModule.GetActivityTitleList(new RB_Education_ActivityTitle_Extend { ActivityId = extModel.Id, TenantId = extModel.TenantId, MallBaseId = extModel.MallBaseId });
                if (extModel.ActivityTitleList != null && extModel.ActivityTitleList.Any())
                {
                    var planList = activityModule.GetActivityPlanList(new RB_Education_ActivityPlan_Extend { ActivityId = extModel.Id, TenantId = extModel.TenantId, MallBaseId = extModel.MallBaseId });
                    if (planList != null && planList.Any())
                    {
                        planList.ForEach(x => x.TripPicList = !string.IsNullOrWhiteSpace(x.TripPic) ? JsonConvert.DeserializeObject<List<string>>(x.TripPic) : new List<string>());
                        foreach (var item in extModel.ActivityTitleList)
                        {
                            item.ActivityPlanList = new List<RB_Education_ActivityPlan_Extend>();
                            item.ActivityPlanList = planList.Where(x => x.TitleId == item.Id).ToList();
                        }
                    }

                }
            }
            return ApiResult.Success(data: extModel);
        }

        /// <summary>
        /// 更新商户活动状态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult RemoveActivity()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var Id = parms.GetInt("Id", 0);
            var Status = parms.GetInt("Status", 0);
            var flag = activityModule.RemoveActivityModule(Id, Status);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 更新活动总结
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult UpdateSummaryActivityModule()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var Id = parms.GetInt("Id", 0);
            var Summary = parms.GetStringValue("Summary");
            var flag = activityModule.UpdateSummaryActivityModule(Id, Summary);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }




        /// <summary>
        /// 获取商会活动报名分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCommerceConsultPage()
        {
            JObject jObj = JObject.Parse(RequestParm.msg.ToString());
            var query = new RB_Education_Consult_Extend()
            {
                ActivityId = jObj.GetInt("ActivityId", 0),
                LinkMan = jObj.GetStringValue("LinkMan"),
                EnrollState = jObj.GetInt("EnrollState", 0),
            };
            query.MallBaseId = RequestParm.MallBaseId;
            query.TenantId = RequestParm.TenantId;
            query.OrderStatus = 1;
            var list = activityModule.GetCommerceConsultListRepository(query);
            return ApiResult.Success(data: list);
        }


        /// <summary>
        /// 获取商会活动报名分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCommerceConsultAndFinancePage()
        {
            JObject jObj = JObject.Parse(RequestParm.msg.ToString());
            var query = new RB_Education_Consult_Extend()
            {
                ActivityId = jObj.GetInt("ActivityId", 0),
                LinkMan = jObj.GetStringValue("LinkMan"),
                EnrollState = jObj.GetInt("EnrollState", 0),
            };
            query.MallBaseId = RequestParm.MallBaseId;
            query.TenantId = RequestParm.TenantId;
            query.OrderStatus = 1;
            // query.EnrollState = 3;
            var list = activityModule.GetCommerceConsultListRepository_V2(query);

            var result = list.Select(x => new
            {
                x.Id,
                x.UnitPrice,
                x.Money,
                x.ApplyForCancelStatus,
                x.CancelRemark,
                x.ActivityName,
                Status = (int)x.Status,
                x.LinkMan,
                x.LinkTel,
                x.UserId,
                x.ActivityId,
                x.Remark,
                x.IsApplyForCancel,
                x.OrderStatus,
                PaymentTime = x.PaymentTime.HasValue ? x.PaymentTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.OrderNo,
                RefundTime = x.RefundTime.HasValue ? x.RefundTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.LocationName,
                EndTime = x.EndTime.HasValue ? x.EndTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                StartTime = x.StartTime.HasValue ? x.StartTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.CoverImg,
                x.Income,
                x.RefundPrice,
                x.IsCommission,
                x.CommissionPrice,
                x.PlatformTax,//(x.PaymentWay == OrderPaymentTypeEnum.OnlinePayment ? ((x.Status == 0 && x.OrderStatus == 1) ? (Math.Round((Convert.ToDecimal(Config.SettlementRate) / 100) * (Convert.ToDecimal(x.Money)), 2, MidpointRounding.AwayFromZero)) : 0) : x.PlatformTax),
                DueInMoney = x.Money - x.Income - x.PlatformTax - x.RefundPrice,
                PaymentWay = x.PaymentWay.HasValue ? (int)x.PaymentWay : 0,
                PaymentWayName = (x.Money == 0 && x.TotalPoint == 0) ? "免费" : (x.PaymentWay.HasValue ? EnumHelper.GetEnumName(x.PaymentWay) : ""),
                x.EduSellName,
                x.EduUserId,
                CreateTime = x.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                IncomeFinanceList = (x.FinanceList != null && x.FinanceList.Any()) ? x.FinanceList.Where(x => x.Type == WFTempLateClassEnum.IN && x.ReFinanceId2 > 0).ToList() : new List<Model.Extend.Finance.RB_Finance_Extend>(),
                ExpendFinanceList = (x.FinanceList != null && x.FinanceList.Any()) ? x.FinanceList.Where(x => x.Type == WFTempLateClassEnum.OUT && x.ReFinanceId2 > 0).ToList() : new List<Model.Extend.Finance.RB_Finance_Extend>(),
            }); ;
            return ApiResult.Success(data: result);
        }






        /// <summary>
        /// 获取商会活动报名分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetConsultOrderStatisticsPage()
        {
            ResultPageModel pageModel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            JObject jObj = JObject.Parse(RequestParm.msg.ToString());
            var query = new RB_Education_Consult_Extend()
            {
                ActivityId = jObj.GetInt("ActivityId", 0),
                LinkMan = jObj.GetStringValue("LinkMan"),
                EnrollState = jObj.GetInt("EnrollState", 0),
                ActivityName = jObj.GetStringValue("ActivityName"),//活动id
                EduUserId = jObj.GetInt("EduUserId", 0),//销售
                CreateStartTime = jObj.GetStringValue("CreateStartTime"),//报名开始时间
                CreateEndTime = jObj.GetStringValue("CreateEndTime"),//报名结束时间
                StartTime = jObj.GetDateTime("StartTime"),//活动开始时间
                EndTime = jObj.GetDateTime("EndTime"),//活动结束时间
                Id = jObj.GetInt("Id", 0),//订单号
            };
            query.MallBaseId = RequestParm.MallBaseId;
            query.TenantId = RequestParm.TenantId;
            query.OrderStatus = 1;
            var list = activityModule.GetCommerceConsultListRepository_V3(pageModel.pageIndex, pageModel.pageSize, out long rowsCount, query);
            var model = activityModule.GetCommerceConsultStatistics(query);

            if (model == null)
            {
                model = new RB_Education_Consult_Statistics();
            }
            var result = new
            {
                Statistics = model,
                List = list.Select(x => new
                {
                    x.Id,
                    x.UnitPrice,
                    x.Money,
                    x.Income,
                    x.RefundPrice,
                    x.PlatformTax,//(x.PaymentWay == OrderPaymentTypeEnum.OnlinePayment ? ((x.Status == 0 && x.OrderStatus == 1) ? (Math.Round((Convert.ToDecimal(Config.SettlementRate) / 100) * (Convert.ToDecimal(x.Money)), 2, MidpointRounding.AwayFromZero)) : 0) : x.PlatformTax),
                    x.ApplyForCancelStatus,
                    x.CancelRemark,
                    x.ActivityName,
                    DueInMoney = x.Money - x.Income - x.PlatformTax - x.RefundPrice,
                    Status = (int)x.Status,
                    x.LinkMan,
                    x.LinkTel,
                    x.UserId,
                    x.ActivityId,
                    x.EduStudentId,
                    x.EduStudentName,
                    x.WeiXinType,
                    x.Remark,
                    x.IsApplyForCancel,
                    PaymentWay = x.PaymentWay.HasValue ? (int)x.PaymentWay : 0,
                    PaymentWayName = (x.Money == 0 && x.TotalPoint == 0) ? "免费" : (x.PaymentWay.HasValue ? EnumHelper.GetEnumName(x.PaymentWay) : ""),
                    x.OrderStatus,
                    x.EduSellName,
                    x.EduUserId,
                    x.IsCommission,
                    x.CommissionPrice,
                    PaymentTime = x.PaymentTime.HasValue ? x.PaymentTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                    CreateTime = x.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    x.OrderNo,
                    RefundTime = x.RefundTime.HasValue ? x.RefundTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                    x.LocationName,
                    EndTime = x.EndTime.HasValue ? x.EndTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                    StartTime = x.StartTime.HasValue ? x.StartTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                    x.CoverImg,
                    IncomeFinanceList = (x.FinanceList != null && x.FinanceList.Any()) ? x.FinanceList.Where(x => (x.Status == FinanceAuditStatus.InReview || x.Status == FinanceAuditStatus.Pass || x.Status == FinanceAuditStatus.CTemporary) && x.Type == WFTempLateClassEnum.IN && x.ReFinanceId2 > 0).ToList() : new List<Model.Extend.Finance.RB_Finance_Extend>(),
                    ExpendFinanceList = (x.FinanceList != null && x.FinanceList.Any()) ? x.FinanceList.Where(x => (x.Status == FinanceAuditStatus.InReview || x.Status == FinanceAuditStatus.Pass || x.Status == FinanceAuditStatus.CTemporary) && x.Type == WFTempLateClassEnum.OUT && x.ReFinanceId2 > 0).ToList() : new List<Model.Extend.Finance.RB_Finance_Extend>(),
                })
            };

            pageModel.count = Convert.ToInt32(rowsCount);
            pageModel.pageData = result;
            return ApiResult.Success(data: pageModel);
        }




        /// <summary>
        /// 用户信息下载
        /// </summary>
        [HttpPost]
        public FileContentResult GetExportCommerceConsultList()
        {
            var parms = RequestParm;
            RB_Education_Consult_Extend demodel = JsonConvert.DeserializeObject<RB_Education_Consult_Extend>(parms.msg.ToString());
            demodel.MallBaseId = RequestParm.MallBaseId;
            demodel.TenantId = RequestParm.TenantId;
            demodel.OrderStatus = 1;
            string ExcelName = "参与者名单" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            if (demodel.ExcelEnumIds == null || !demodel.ExcelEnumIds.Any())
            {
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
            var Enumlist = EnumHelper.GetEnumList(typeof(ConsultOrderExportEnum));
            ExcelDataSource header = new ExcelDataSource()
            {
                ExcelRows = new List<ExcelColumn>(13)
                {
                    new ExcelColumn(value: "序号") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER }
                }
            };
            foreach (var item in demodel.ExcelEnumIds)
            {
                var Name = Enumlist.Where(x => x.Value == item.ToString()).FirstOrDefault().Key ?? "";
                header.ExcelRows.Add(new ExcelColumn(value: Name) { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER });
            }

            slist.Add(header);

            try
            {
                //demodel.TenantId = Convert.ToInt32(parms.uid);
                //demodel.MallBaseId = parms.MallBaseId;
                var list = activityModule.GetExportCommerceConsultList(demodel);
                #region 组装数据
                int Num = 0;
                foreach (var item in list)
                {
                    Num++;
                    ExcelDataSource datarow = new ExcelDataSource()
                    {
                        ExcelRows = new List<ExcelColumn>(30) {
                            new ExcelColumn(value:Num.ToString()){ },
                        }
                    };
                    foreach (var qitem in demodel.ExcelEnumIds)
                    {
                        switch (qitem)
                        {
                            case 1:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.Id.ToString()) { }); break;
                            case 2:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.LinkMan) { }); break;
                            case 3:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.LinkTel) { }); break;
                            case 4:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.UnitPrice.ToString("f2")) { }); break;
                            case 5:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.Money.ToString("f2")) { }); break;
                            case 6:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.Income.ToString("f2")) { }); break;
                            case 7:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.RefundPrice.ToString("f2")) { }); break;
                            case 8:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.PlatformTax.ToString("f2")) { }); break;
                            case 9:
                                datarow.ExcelRows.Add(new ExcelColumn(value: (item.Money - item.Income - item.PlatformTax - item.RefundPrice).ToString("f2")) { }); break;
                            case 10:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.Status == 0 ? "正常" : "取消") { }); break;
                            case 11:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.Remark) { }); break;
                            case 12:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")) { }); break;
                        }
                    }
                    slist.Add(datarow);
                }
                #endregion
                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData, "application/octet-stream", ExcelName);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, string.Format("GetFileFromWebApi_requestData: {0}", JsonHelper.Serialize(RequestParm)));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
        }

        /// <summary>
        /// 获取用户报名下载枚举列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetConsultOrderExportExcelEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(ConsultOrderExportEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }





        /// <summary>
        /// 获取商会活动报名分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetConsultOrderStatistics()
        {
            JObject jObj = JObject.Parse(RequestParm.msg.ToString());
            var query = new RB_Education_Consult_Extend()
            {
                ActivityId = jObj.GetInt("ActivityId", 0),
                LinkMan = jObj.GetStringValue("LinkMan"),
                EnrollState = jObj.GetInt("EnrollState", 0),
                ActivityName = jObj.GetStringValue("ActivityName"),//活动id
                EduUserId = jObj.GetInt("EduUserId", 0),//销售
                CreateStartTime = jObj.GetStringValue("CreateStartTime"),//报名开始时间
                CreateEndTime = jObj.GetStringValue("CreateEndTime"),//报名结束时间
                StartTime = jObj.GetDateTime("StartTime"),//活动开始时间
                EndTime = jObj.GetDateTime("EndTime"),//活动结束时间
                Id = jObj.GetInt("Id", 0),//订单号
            };
            query.MallBaseId = RequestParm.MallBaseId;
            query.TenantId = RequestParm.TenantId;
            query.OrderStatus = 1;
            var model = activityModule.GetCommerceConsultStatistics(query);

            if (model == null)
            {
                model = new RB_Education_Consult_Statistics();
            }
            return ApiResult.Success(data: model);
        }


        /// <summary>
        /// 操作活动报名申请取消
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCommerceConsultApplyCancel()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var Id = parms.GetInt("Id", 0);
            var ApplyForCancelStatus = parms.GetInt("ApplyForCancelStatus", 0);//申请取消审核状态  1同意  2拒绝
            var RejectRemark = parms.GetStringValue("RejectRemark");//拒绝备注
            bool flag;
            if (Id <= 0)
            {
                return ApiResult.ParamIsNull("请传递");
            }
            if (ApplyForCancelStatus == 2)
            {
                if (string.IsNullOrEmpty(RejectRemark))
                {
                    return ApiResult.ParamIsNull("请输入拒绝的原因");
                }
            }
            if (ApplyForCancelStatus == 1)
            {
                var model = activityModule.GetCommerceConsultListRepository(new RB_Education_Consult_Extend { OrderStatus = 1, Id = Id, MallBaseId = RequestParm.MallBaseId, TenantId = RequestParm.TenantId }).FirstOrDefault();
                if (model == null || model.Id == 0 || model.Status != Common.Enum.DateStateEnum.Normal)
                {
                    return ApiResult.Failed("报名数据不存在");
                }
                if (model.Status == Common.Enum.DateStateEnum.Normal && model.OrderStatus == 1 && model.PaymentWay == OrderPaymentTypeEnum.OnlinePayment && model.PayWay.HasValue && model.PayWay.Value == OrderPayTypeEnum.WeChatPay)
                {
                    //获取小程序信息
                    var mallModel = activityModule.GetMiniProgramExtend(model.MallBaseId);
                    string RefundOrderNo = model.OrderNo + 1;
                    var pram = new Common.Pay.WeChatPat.PayParam()
                    {
                        TotalFee = Convert.ToInt32((model.Money) * 100),
                        RefundFee = Convert.ToInt32((model.Money) * 100),
                        OrderNumber = model.OrderNo,
                        RefundNumber = RefundOrderNo
                    };
                    var Robj = new App_Code.PayUtil().Refund(pram, mallModel, _accessor);
                    if (Robj.IsSuccess)
                    {
                        var dic = ((Dictionary<string, string>)Robj.Data);
                        decimal dPaid = Convert.ToDecimal(dic["dPrice"]) / 100;
                        string refundid = dic["refundid"];//微信退款单号
                        string outRefundNo = dic["outRefundNo"];//商户退款单号
                        flag = activityModule.SetCommerceConsultApplyCancel(Id, ApplyForCancelStatus, RejectRemark, refundid, dPaid);
                    }
                    else
                    {
                        return ApiResult.Failed(Robj.Message);
                    }
                }
                else
                {
                    flag = activityModule.SetCommerceConsultApplyCancel(Id, ApplyForCancelStatus, RejectRemark, "", 0);
                }

            }
            else
            {
                flag = activityModule.SetCommerceConsultApplyCancel(Id, ApplyForCancelStatus, RejectRemark, "", 0);
            }
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }



        /// <summary>
        /// 取消报名
        /// </summary>
        /// <returns></returns>
        public ApiResult CancelCommerceConsult()
        {
            JObject jObj = JObject.Parse(RequestParm.msg.ToString());
            var ActivityId = jObj.GetInt("ActivityId");
            var Id = jObj.GetInt("Id");
            var EduUserId = jObj.GetInt("EduUserId");
            string CancelRemark = jObj.GetStringValue("CancelRemark");
            var model = activityModule.GetCommerceConsultListRepository(new RB_Education_Consult_Extend { EduUserId = EduUserId, OrderStatus = -1, ActivityId = ActivityId, Id = Id }).FirstOrDefault();
            if (model == null || model.Id == 0 || model.Status == Common.Enum.DateStateEnum.Delete)
            { return ApiResult.Failed("报名数据不存在"); }

            var activotyModel = activityModule.GetActivityModule(ActivityId);
            if (activotyModel.SignEndTime.HasValue && System.DateTime.Now > activotyModel.SignEndTime.Value)
            {
                return ApiResult.Failed("已过报名时间无法取消");
            }
            bool flag = activityModule.CancelCommerceConsult(ActivityId, CancelRemark, out int IsCancelConfirm, model);
            return flag ? ApiResult.Success("", IsCancelConfirm) : ApiResult.Failed();
        }


        #region 赞羊教育活动报名

        /// <summary>
        /// 活动报名
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetActivityEnrollInfo()
        {
            var request = RequestParm;

            Model.Extend.Education.RB_Education_Consult_Extend demodel = JsonConvert.DeserializeObject<Model.Extend.Education.RB_Education_Consult_Extend>(request.msg.ToString());
            var model = activityModule.GetActivityModule(demodel.ActivityId);
            List<RB_Education_Consult_Extend> list = new List<RB_Education_Consult_Extend>();
            if (demodel.EduStudentId > 0)
            {
                list = activityModule.GetCommerceConsultListRepository(new Model.Extend.Education.RB_Education_Consult_Extend() { TenantId = model.TenantId, MallBaseId = model.MallBaseId, ActivityId = demodel.ActivityId, EnrollState = 1, EduStudentId = demodel.EduStudentId, OrderStatus = 1 });
                if (list.Any()) { return ApiResult.Failed("已存在报名信息"); }
            }
            else
            {
                list = activityModule.GetCommerceConsultListRepository(new Model.Extend.Education.RB_Education_Consult_Extend() { TenantId = model.TenantId, MallBaseId = model.MallBaseId, ActivityId = demodel.ActivityId, EnrollState = 1, LinkTel = demodel.LinkTel, OrderStatus = 1 });
                if (list.Any(x => x.Id != demodel.Id)) { return ApiResult.Failed("已存在报名信息"); }
            }

            if (model == null || model.Status == Common.Enum.DateStateEnum.Delete) { return ApiResult.Failed("活动不存在"); }
            if (model.SignStartTime >= DateTime.Now)
            {
                return ApiResult.Failed("报名还未开始，无法报名");
            }
            if (model.SignEndTime <= DateTime.Now)
            {
                return ApiResult.Failed("已过了报名时间，无法报名");
            }

            if (model.Distinguish == 0)
            {
                if (demodel.Sex == 0)
                {
                    return ApiResult.Failed("学生性别保密，无法报名");
                }
                if (demodel.Sex == 1)
                {
                    int ManPeopleNum = activityModule.GetActivityEnrollNum(demodel.ActivityId, 1);
                    if (model.ManNum <= ManPeopleNum) { return ApiResult.Failed("已报满，无法报名"); }
                }
                else if (demodel.Sex == 2)
                {
                    int WoManPeopleNum = activityModule.GetActivityEnrollNum(demodel.ActivityId, 2);
                    if (model.WoManNum <= WoManPeopleNum) { return ApiResult.Failed("已报满，无法报名"); }
                }
                else
                {
                    return ApiResult.Failed("性别未维护，无法报名");
                }
            }
            else
            {
                int ManPeopleNum = activityModule.GetActivityEnrollNum(demodel.ActivityId, 0);
                if (model.ManNum <= ManPeopleNum) { return ApiResult.Failed("已报满，无法报名"); }
            }
            if (model.AgeLimit == 0)
            {
                if (string.IsNullOrWhiteSpace(demodel.StuBirth))
                {
                    return ApiResult.Failed("您未绑定学员信息无法获取到年龄，无法报名");
                }
                int Age = Convert.ToInt32(Common.Plugin.StringHelper.GetAge(demodel.StuBirth));
                if (model.StartAge > 0 && model.EndAge > 0)
                {
                    if (Age < model.StartAge || Age > model.EndAge)
                    {
                        return ApiResult.Failed($"年龄限制在{model.StartAge}-{model.EndAge}岁，无法报名");
                    }
                }
                else if (model.StartAge > 0 && model.EndAge == 0)
                {
                    if (Age < model.StartAge)
                    {
                        return ApiResult.Failed($"年龄必须大于{model.StartAge}岁，无法报名");
                    }
                }
                else if (model.StartAge == 0 && model.EndAge > 0)
                {
                    if (Age > model.EndAge)
                    {
                        return ApiResult.Failed($"年龄必须小于{model.EndAge}岁，无法报名");
                    }

                }
            }
            if (model.LnsideLimit == 1)
            {
                if (demodel.EduStudentId == 0)
                {
                    return ApiResult.Failed("内部限制，请选择学员信息");
                }
                else
                {

                    var bmodel = activityModule.GetStudentListByEnterID(new RB_Student { StuId = demodel.EduStudentId }, demodel.EduUserId).FirstOrDefault();
                    if (bmodel == null || bmodel.StuId == 0)
                    {
                        return ApiResult.Failed("学员信息不存在");
                    }
                }
            }
            Random R = new Random();
            int Rstr = R.Next(111, 999);
            demodel.OrderNo = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr;
            demodel.UserId = 0;
            demodel.Status = 0;
            demodel.IsCancelConfirm = model.IsCancelConfirm;
            if (demodel.Id == 0)
            {
                demodel.CreateTime = System.DateTime.Now;
            }
            else
            {
                var oldDemodel = activityModule.GetConsultEntity(demodel.Id);
                demodel.CreateTime = oldDemodel.CreateTime;
            }
            if (model.IsFree == 1)
            {
                demodel.OrderStatus = 1;
                demodel.PaymentTime = System.DateTime.Now;
            }
            else
            {
                if (model.Price != demodel.Money)
                {
                    return ApiResult.Failed("支付金额不正确");
                }
                else if (demodel.Money == 0)
                {
                    demodel.OrderStatus = 1;
                    demodel.PaymentTime = System.DateTime.Now;
                }
                else
                {
                    demodel.OrderStatus = 0;
                }
            }
            var umodel = new RB_Member_User_Extend();
            demodel.OrderSource = UserSourceEnum.EduERP;
            demodel.PaymentWay = OrderPaymentTypeEnum.OfflinePay;
            demodel.IsCommission = 1;
            demodel.IsRollCall = 1;
            int id = activityModule.SetActivityEnrollInfo(demodel, umodel);
            if (id > 0)
            {
                return ApiResult.Success("报名成功");
            }
            else
            {
                return ApiResult.Failed("报名失败");
            }

        }


        /// <summary>
        /// 根据销售的id获取对应的学员信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetEduStudent()
        {
            JObject jObj = JObject.Parse(RequestParm.msg.ToString());
            int EduUserId = jObj.GetInt("EduUserId", 0);
            var studentList = activityModule.GetStudentListByEnterID(new RB_Student { School_Id = -1 }, EduUserId).Distinct().ToList();
            List<RB_Student> result = new List<RB_Student>();
            foreach (var item in studentList)
            {
                if (!result.Any(x => x.StuId == item.StuId))
                {
                    result.Add(item);
                }
            }
            return ApiResult.Success(data: result);
        }



        /// <summary>
        /// 更新财务单据的应收与平台税金
        /// </summary>
        /// <returns></returns>
        [Microsoft.AspNetCore.Authorization.AllowAnonymous]
        [HttpPost]
        public ApiResult UpdateActivityIncome()
        {
            //int OrderId, decimal Money, int ActivityId
            JObject jObj = JObject.Parse(RequestParm.msg.ToString());
            int OrderId = jObj.GetInt("OrderId", 0);
            decimal Money = jObj.GetDecimal("Money");
            decimal PlatformTax = jObj.GetDecimal("PlatformTax");
            var studentList = activityModule.UpdateActivityIncome(OrderId, Money, PlatformTax);
            return ApiResult.Success(data: studentList);
        }


        /// <summary>
        /// 更新财务单据的应收与平台税金
        /// </summary>
        /// <returns></returns>
        [Microsoft.AspNetCore.Authorization.AllowAnonymous]
        [HttpPost]
        public ApiResult UpdateActivityReturn()
        {
            //int OrderId, decimal Money, int ActivityId
            JObject jObj = JObject.Parse(RequestParm.msg.ToString());
            int OrderId = jObj.GetInt("OrderId", 0);
            decimal Money = jObj.GetDecimal("Money");
            var studentList = activityModule.UpdateActivityReturn(OrderId, Money);
            return ApiResult.Success(data: studentList);
        }
        #endregion



        #region 收支明细

        /// <summary>
        /// 获取活动收支明细
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetActivityBalanceSheet()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());

            int Id = parms.GetInt("Id", 0);
            int OrderId = parms.GetInt("OrderId", 0);
            if (Id <= 0)
            {
                return ApiResult.ParamIsNull("");
            }

            RB_Finance_Extend model = new RB_Finance_Extend() { ReFinanceId = Id, OrderSource = 17, RB_Group_Id = 100000, FinanceType = 2, ReFinanceId2 = OrderId };

            var financeList = activityModule.GetFinanceInfoList(model).Where(t => (t.Status == FinanceAuditStatus.InReview || t.Status == FinanceAuditStatus.Pass || t.Status == FinanceAuditStatus.CTemporary)).ToList();

            //收入
            decimal IncomeReceive = 0;//应收
            decimal IncomeActual = 0;//实收
            IncomeReceive = (financeList != null && financeList.Any()) ? financeList.Where(x => x.Type == WFTempLateClassEnum.IN && x.ReFinanceId2 > 0).Sum(x => x.Money ?? 0) : 0;// (orderList != null && orderList.Any()) ? orderList.Sum(x => x.Money) : 0;
            IncomeActual = (financeList != null && financeList.Any()) ? financeList.Where(x => x.Type == WFTempLateClassEnum.IN && x.ReFinanceId2 > 0).Sum(x => x.PayMoney ?? 0) : 0;// (orderList != null && orderList.Any()) ? orderList.Sum(x => x.Money) : 0;



            //支出
            decimal PayReceive = 0;//应付
            decimal PayActual = 0;//实付
            PayReceive = (financeList != null && financeList.Any()) ? financeList.Where(x => x.Type == WFTempLateClassEnum.OUT && x.ReFinanceId2 > 0).Sum(x => x.Money ?? 0) : 0;
            PayActual = (financeList != null && financeList.Any()) ? financeList.Where(x => x.Type == WFTempLateClassEnum.OUT && x.ReFinanceId2 > 0).Sum(x => x.PayMoney ?? 0) : 0;


            //其他收入
            decimal OtherIncomeReceive = 0;//应收
            decimal OtherIncomeActual = 0;//实收
            OtherIncomeReceive = (financeList != null && financeList.Any()) ? financeList.Where(x => x.Type == WFTempLateClassEnum.IN && x.ReFinanceId2 <= 0).Sum(x => x.Money ?? 0) : 0;
            OtherIncomeActual = (financeList != null && financeList.Any()) ? financeList.Where(x => x.Type == WFTempLateClassEnum.IN && x.ReFinanceId2 <= 0).Sum(x => x.PayMoney ?? 0) : 0;


            //其他支出
            decimal OtherPayReceive = 0;//应收
            decimal OtherPayActual = 0;//实收
            OtherPayReceive = (financeList != null && financeList.Any()) ? financeList.Where(x => x.Type == WFTempLateClassEnum.OUT && x.ReFinanceId2 <= 0).Sum(x => x.Money ?? 0) : 0;
            OtherPayActual = (financeList != null && financeList.Any()) ? financeList.Where(x => x.Type == WFTempLateClassEnum.OUT && x.ReFinanceId2 <= 0).Sum(x => x.PayMoney ?? 0) : 0;


            //活动提成
            decimal ActivityCommission = activityModule.GetActivityCommission(activityId: Id, groupId: 100000);


            //利润
            decimal ProfitActual = 0;//实际利润
            decimal ProfitNow = 0;//当前利润
            ProfitActual = (IncomeActual + OtherIncomeActual) - PayReceive - OtherPayReceive - ActivityCommission;
            ProfitNow = (IncomeActual + OtherIncomeActual) - PayActual - OtherPayActual - ActivityCommission;

            //提成
            //decimal SaleCommission = (orderList != null && orderList.Any()) ? orderList.Where(x => x.IsCommissionGive == 1).Sum(x => x.CommissionMoney) : 0; ;//销售提成
            //var teacherProfitList = teachingRewardsModule.GetBonusDetailList(new RB_Teaching_BonusDetail_ViewModel { Group_Id = base.UserInfo.Group_Id, ClassId = classId, School_Id = schoolId });
            //decimal TeacherProfitNow = (teacherProfitList != null && teacherProfitList.Any()) ? teacherProfitList.Sum(x => x.Money) : 0;//老师提成

            //var meritsProfitList = teachingRewardsModule.GetTeachingPerfList(new RB_Teaching_Perf_ViewModel { Group_Id = base.UserInfo.Group_Id, ClassId = classId, School_Id = schoolId });
            //decimal MeritsProfit = (meritsProfitList != null && meritsProfitList.Any()) ? (meritsProfitList.Where(x => x.PerfState == Common.Enum.Course.PerfStateEnum.Confirmed).OrderByDescending(x => x.CreateTime).FirstOrDefault()?.Money ?? 0) : 0;//绩效提成

            //项目信息
            var projectInfo = new object();
            RB_Education_Activity_Extend classInfo = new RB_Education_Activity_Extend();
            if (Id > 0)
            {
                classInfo = activityModule.GetActivityModule(Id);
                projectInfo = new { classInfo.Id, classInfo?.ActivityName, classInfo?.StartTimeStr, classInfo?.EndTimeStr, classInfo?.LocationName };
            }

            var recultFiniceList = financeList.Select(x => new
            {
                x.FrID,
                x.Type,
                x.TCID,
                x.OrderID,
                x.Money,
                x.PayMoney,
                x.ReFinanceId2,
                x.ReFinanceId,
                x.ColorType,
                AirTotalMoney = x.AirTotalMoney ?? 0,
                AirTotalPayMoney = x.AirTotalPayMoney ?? 0,
                CostTypeList = x.CostTypeList.Distinct().ToList(),
                x.OrderSource,
                AuditList = x.AuditList.Select(t => new { t.AuditEmId, t.AuditEmName, AuditDate = t.AuditDate.HasValue ? t.AuditDate.Value.ToString("yyyy/MM/dd") : "" }),
                StatusStr = EnumHelper.GetEnumName(x.Status.Value),
                x.RB_CreateByName,
                CreateDate = x.CreateDate.Value.ToString("yyyy-MM-dd"),
                TradeDate = x.TradeDate.HasValue ? x.TradeDate.Value.ToString("yyyy-MM-dd") : "",
                TradeWayList = x.BankList?.Select(y => new { y.AccountType, y.Alias, y.BankNo, TypeName = EnumHelper.GetEnumName(y.Type), y.CurrencyName, y.OriginalMoney, y.Money, y.Rate })
            });


            var resultData = new
            {

                ClassInfo = projectInfo,
                IncomeReceive,
                IncomeActual,
                OtherIncomeReceive,
                OtherIncomeActual,
                OtherPayReceive,
                OtherPayActual,
                PayReceive,
                PayActual,
                ProfitActual,
                ProfitNow,
                ActivityCommission,
                FiniceReciveList = recultFiniceList.Where(t => t.Type == WFTempLateClassEnum.IN && t.ReFinanceId2 > 0),//活动报名收入
                FinicePayList = recultFiniceList.Where(t => t.Type == WFTempLateClassEnum.OUT && t.ReFinanceId2 > 0),//活动报名支出
                OtherFiniceReciveList = recultFiniceList.Where(t => t.Type == WFTempLateClassEnum.IN && t.ReFinanceId2 <= 0),//其他收入
                OtherFinicePayList = recultFiniceList.Where(t => t.Type == WFTempLateClassEnum.OUT && t.ReFinanceId2 <= 0),//其他支出

            };
            return ApiResult.Success("", resultData);
        }
        #endregion




        #region 素材管理
        /// <summary>
        /// 获取素材分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMaterialInfoPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Education_ActivitySummaryFile_Extend demodel = JsonConvert.DeserializeObject<RB_Education_ActivitySummaryFile_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = activityModule.GetActivitySummaryFilePageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.Type,
                x.GroupId,
                x.Path,
                x.Image,
                x.VideoTime,
                x.WithHeight,
                x.ActivityId,
                x.PathType,
                x.TenantId,
                x.MallBaseId,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd") : ""
            });
            return ApiResult.Success("", pagelist);
        }



        /// <summary>
        /// 新增素材信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetGetMaterialInfo()
        {
            var parms = RequestParm;
            RB_Education_ActivitySummaryFile_Extend demodel = JsonConvert.DeserializeObject<RB_Education_ActivitySummaryFile_Extend>(parms.msg.ToString());
            if (string.IsNullOrEmpty(demodel.Name))
            {
                return ApiResult.ParamIsNull("请输入素材名称");
            }
            if (demodel.Type != 1 && demodel.Type != 2 && demodel.Type != 3)
            {
                return ApiResult.ParamIsNull("请传递类型");
            }
            if (demodel.ActivityId < 0)
            {
                return ApiResult.ParamIsNull("请传入活动id");
            }
            if ((demodel.GroupId ?? 0) < 0)
            {
                return ApiResult.ParamIsNull("请输入分组");
            }
            if (string.IsNullOrEmpty(demodel.Path))
            {
                return ApiResult.ParamIsNull("请传递文件路径");
            }
            //HK2020-09-01修改
            //if (demodel.Type == 1)
            //{
            //    demodel.Path = Config.GetFilePath(demodel.Path);
            //    demodel.Image = Config.GetFilePath(demodel.Image);
            //}

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            demodel.Status = 0;
            bool flag = activityModule.SetMaterialInfo(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 获取素材分组列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMaterialGroupList()
        {
            var parms = RequestParm;
            RB_Education_ActivitySummaryGroup_Extend demodel = JsonConvert.DeserializeObject<RB_Education_ActivitySummaryGroup_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = activityModule.GetActivitySummaryGroupList(demodel);
            return ApiResult.Success("", list.Select(x => new
            {
                x.Id,
                x.Name,
                x.Type,
                x.Sort,
                x.TenantId,
                x.MallBaseId,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd") : ""
            }));
        }

        /// <summary>
        /// 新增修改分组
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetMaterialGroupInfo()
        {
            var parms = RequestParm;
            RB_Education_ActivitySummaryGroup_Extend demodel = JsonConvert.DeserializeObject<RB_Education_ActivitySummaryGroup_Extend>(parms.msg.ToString());
            if (string.IsNullOrEmpty(demodel.Name))
            {
                return ApiResult.ParamIsNull("请输入分组名称");
            }
            if (demodel.Type != 1 && demodel.Type != 2 && demodel.Type != 3)
            {
                return ApiResult.ParamIsNull("请传递类型");
            }
            if (demodel.ActivityId <= 0)
            {
                return ApiResult.ParamIsNull("请传递活动id");
            }
            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            demodel.Status = 0;
            bool flag = activityModule.SetActivitySummaryGroupInfo(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }



        /// <summary>
        /// 删除分组信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelMaterialGroupInfo()
        {
            var requestParm = RequestParm;
            var parms = JObject.Parse(requestParm.msg.ToString());
            int GroupId = parms.GetInt("GroupId", 0);
            if (GroupId < 0)
            {
                return ApiResult.ParamIsNull("请传递分组id");
            }

            bool flag = activityModule.DelMaterialGroupInfo(GroupId, requestParm.TenantId.ToString(), requestParm.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }





        /// <summary>
        /// 删除素材信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelMaterialInfo()
        {
            var requestParm = RequestParm;
            var parms = JObject.Parse(requestParm.msg.ToString());
            string MaterialIds = parms.GetStringValue("MaterialIds");
            if (string.IsNullOrEmpty(MaterialIds))
            {
                return ApiResult.ParamIsNull("请传递素材ids");
            }

            bool flag = activityModule.DelMaterialInfo(MaterialIds, requestParm.TenantId.ToString(), requestParm.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }


        /// <summary>
        /// 设置素材转移
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetMaterialInfoTransfer()
        {
            var requestParm = RequestParm;
            var parms = JObject.Parse(requestParm.msg.ToString());
            string MaterialIds = parms.GetStringValue("MaterialIds");
            int GroupId = parms.GetInt("GroupId", 0);
            int Type = parms.GetInt("Type", 0);
            if (string.IsNullOrEmpty(MaterialIds))
            {
                return ApiResult.ParamIsNull("请传递素材ids");
            }
            if (GroupId <= 0)
            {
                return ApiResult.ParamIsNull("请传递分组id");
            }

            bool flag = activityModule.SetMaterialInfoTransfer(MaterialIds, GroupId, Type, requestParm.uid, requestParm.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        #endregion

        #endregion


        #region 会员列表
        /// <summary>
        /// 获取用户分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMemberUserPageList()
        {
            var parms = RequestParm;
            JObject param = JObject.Parse(parms.msg.ToString());
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Member_User_Extend demodel = new RB_Member_User_Extend()
            {
                Name = param.GetStringValue("Name"),
                Source = (UserSourceEnum)param.GetInt("Source"),
                MemberGrade = param.GetInt("MemberGrade"),
                Id = param.GetInt("Id"),
                Moblie = param.GetStringValue("Moblie"),
                StartTime = param.GetStringValue("StartTime"),
                EndTime = param.GetStringValue("EndTime"),
                EduSchoolId = param.GetInt("EduSchoolId", 0),
            };
            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = activityModule.GetEduPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.AliasName,
                x.Balance,
                x.Blacklist,
                x.CardVolumeNum,
                x.ContactWay,
                x.CouponsNum,
                x.Integral,
                x.TotalConsumption,
                x.MemberGrade,
                x.MemberGradeName,
                x.Moblie,
                x.Name,
                x.OpenId,
                x.OrderNum,
                x.Photo,
                x.Remark,
                x.Source,
                SourceName = x.Source.GetEnumName(),
                x.TenantId,
                x.PostId,
                PostName = (x?.PostId ?? 0) == 1 ? "领队导游" : "",
                UserPageTypeStr = x.UserPageType.GetEnumName(),
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.PointNum,
                x.StudentId
            }); ;
            return ApiResult.Success("", pagelist);
        }




        /// <summary>
        /// 获取用户下载枚举列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetEduUserExportEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(Common.Enum.Point.EduUserExportEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }
        /// <summary>
        /// 用户信息下载
        /// </summary>
        [HttpPost]
        public FileContentResult GetMemberUserListToExcel()
        {
            var parms = RequestParm;
            RB_Member_User_Extend demodel = JsonConvert.DeserializeObject<RB_Member_User_Extend>(parms.msg.ToString());
            string ExcelName = "用户信息" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            if (demodel.ExcelEnumIds == null || !demodel.ExcelEnumIds.Any())
            {
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
            var Enumlist = EnumHelper.GetEnumList(typeof(Common.Enum.Point.EduUserExportEnum));
            ExcelDataSource header = new ExcelDataSource()
            {
                ExcelRows = new List<ExcelColumn>(30)
                {
                    new ExcelColumn(value: "序号") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER }
                }
            };
            foreach (var item in demodel.ExcelEnumIds)
            {
                var Name = Enumlist.Where(x => x.Value == item.ToString()).FirstOrDefault().Key ?? "";
                header.ExcelRows.Add(new ExcelColumn(value: Name) { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER });
            }

            slist.Add(header);

            try
            {
                demodel.TenantId = Convert.ToInt32(parms.uid);
                demodel.MallBaseId = parms.MallBaseId;
                var list = activityModule.GetEduList(demodel);
                #region 组装数据
                int Num = 0;
                foreach (var item in list)
                {
                    Num++;
                    ExcelDataSource datarow = new ExcelDataSource()
                    {
                        ExcelRows = new List<ExcelColumn>(30) {
                            new ExcelColumn(value:Num.ToString()){ },
                        }
                    };
                    foreach (var qitem in demodel.ExcelEnumIds)
                    {
                        switch (qitem)
                        {
                            case 1:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.Source.GetEnumName()) { }); break;
                            case 2:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.Id.ToString()) { }); break;
                            case 3:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.OpenId) { }); break;
                            case 4:
                                datarow.ExcelRows.Add(new ExcelColumn(value: (item.AliasName ?? "") != "" ? item.AliasName : item.Name) { }); break;
                            case 5:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.Moblie) { }); break;
                            case 6:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.ContactWay) { }); break;
                            case 7:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.Remark) { }); break;
                            case 8:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")) { }); break;
                            case 9:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.MemberGradeName) { }); break;
                            case 10:
                                datarow.ExcelRows.Add(new ExcelColumn(value: (item.OrderNum ?? 0).ToString()) { }); break;
                            case 11:
                                datarow.ExcelRows.Add(new ExcelColumn(value: (item.CouponsNum ?? 0).ToString()) { }); break;
                            case 12:
                                datarow.ExcelRows.Add(new ExcelColumn(value: (item.CardVolumeNum ?? 0).ToString()) { }); break;
                            case 13:
                                datarow.ExcelRows.Add(new ExcelColumn(value: (item.Integral ?? 0).ToString()) { }); break;
                            case 14:
                                datarow.ExcelRows.Add(new ExcelColumn(value: (item.Balance ?? 0).ToString()) { }); break;
                            case 15:
                                datarow.ExcelRows.Add(new ExcelColumn(value: (item.TotalConsumption ?? 0).ToString()) { }); break;
                            case 16:
                                datarow.ExcelRows.Add(new ExcelColumn(value: (item.PointNum).ToString()) { }); break;
                            case 17:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.StudentId > 0 ? "已绑定" : "未绑定") { }); break;
                        }
                    }
                    slist.Add(datarow);
                }
                #endregion
                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData, "application/octet-stream", ExcelName);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, string.Format("GetFileFromWebApi_requestData: {0}", JsonHelper.Serialize(RequestParm)));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
        }
        #endregion


        #region 校企合作管理
        /// <summary>
        /// 校企分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetEducationSchoolPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            Rb_Education_School_Extend demodel = JsonConvert.DeserializeObject<Rb_Education_School_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            //demodel.TeacherStatus = -1;
            var list = educationModule.GetEducationSchoolPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.ShoolName,
                x.CoverPhoto,
                x.UserCount,
                x.AgentList,
                x.AgentIds
            });
            return ApiResult.Success("", pagelist);
        }


        /// <summary>
        /// 学校详情
        /// </summary>
        /// <returns></returns>

        [HttpPost]
        public ApiResult GetEducationSchoolDetails()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            int Id = parmsJob.GetInt("Id", 0);
            if (Id == 0)
            {
                return ApiResult.ParamIsNull();
            }
            Rb_Education_School_Extend demodel = new Rb_Education_School_Extend
            {
                TenantId = UserInfo.TenantId,
                MallBaseId = parms.MallBaseId,
                Id = Id
            };
            var model = educationModule.GetEducationSchoolList(demodel);
            var result = model.Select(x => new
            {
                x.Id,
                x.ShoolName,
                x.CoverPhoto,
                x.UserCount,
                x.AgentList,
                x.AgentIds
            });
            return ApiResult.Success("", result);
        }




        /// <summary>
        /// 保存校企信息
        /// </summary>
        /// <returns></returns>
        public ApiResult AddOrUpdateEduSchool()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<Rb_Education_School_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            if (query == null)
            {
                return ApiResult.Failed("请传入校企信息");
            }
            else
            {
                if (string.IsNullOrWhiteSpace(query.ShoolName))
                {
                    return ApiResult.Failed("请输入学校名称");
                }

                if (query.Id == 0)
                {
                    query.CreateTime = System.DateTime.Now;
                    query.CreateBy = UserInfo.EmpId;
                }


                bool result = educationModule.SetEduSchool(query);
                if (result)
                {
                    return ApiResult.Success("校企信息保存成功");
                }
                else
                {
                    return ApiResult.Failed("校企信息保存失败");
                }
            }
        }


        /// <summary>
        /// 删除校企
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelSchoolInfo()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            string idInfo = parmsJob.GetStringValue("Ids");
            if (string.IsNullOrWhiteSpace(idInfo))
            {
                return ApiResult.Failed("请传递参数");
            }
            Rb_Education_School_Extend demodel = new Rb_Education_School_Extend
            {
                TenantId = UserInfo.TenantId,
                MallBaseId = parms.MallBaseId,
                Ids = idInfo
            };
            var list = educationModule.GetEducationSchoolList(demodel);
            if (list.Any(x => x.UserCount > 0))
            {
                return ApiResult.Failed("请先迁移下级用户再删除");
            }
            bool flag = educationModule.DelEduSchool(idInfo.Split(",").ToList(), UserInfo.TenantId, parms.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }
        #endregion


        #region 活动提成

        /// <summary>
        /// 创建活动提成
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous] [RateValve(Policy = Policy.Ip, Limit = 10, Duration = 60)]
        public ApiResult SetActivityCommissionInfo()
        {
            var userInfo = base.UserInfo;
            userInfo.MallBaseId = RequestParm.MallBaseId;
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            string Month = parms.GetStringValue("Month");//月份
            int CreateBy = parms.GetInt("CreateBy", 0);//创建人
            if (string.IsNullOrEmpty(Month))
            {
                return ApiResult.ParamIsNull();
            }
            if (CreateBy <= 0)
            {
                return ApiResult.ParamIsNull("请传递创建人");
            }
            try
            {
                Month = Convert.ToDateTime(Month + "-01").ToString("yyyy-MM");
            }
            catch (Exception)
            {
                return ApiResult.Failed("日期格式有误");
            }

            string msg = activityModule.SetActivityCommissionInfo(Month, CreateBy, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        #endregion
    }
}