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;

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

        #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);
            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,
                model?.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;
            RB_Goods_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Extend>(parms.msg.ToString());
            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();
                oldLogisticsModel.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();
                            memberCoupon.Id = 0;
                            memberCoupon.UserId = Convert.ToInt32(item);
                            memberCoupon.Description = oldLogisticsModel.Describe;
                            memberCoupon.CreateDate = System.DateTime.Now;
                            memberCoupon.TenantId = oldLogisticsModel.TenantId;
                            memberCoupon.MallBaseId = oldLogisticsModel.MallBaseId;
                            memberCoupon.Remarks = "";
                            memberCoupon.CouponId = oldLogisticsModel.ID;
                            memberCoupon.Name = oldLogisticsModel.Name;
                            memberCoupon.UseType = oldLogisticsModel.UseType;
                            memberCoupon.HeXiao = oldLogisticsModel.HeXiao;
                            memberCoupon.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]
        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());
            Int32.TryParse(RequestParm.uid, out int Uid);
            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
    }
}