using System;
using System.Collections.Generic;
using System.Linq;
using Mall.CacheManager.User;
using Mall.Common;
using Mall.Common.API;
using Mall.Common.Enum;
using Mall.Common.Enum.Goods;
using Mall.Common.Enum.MarketingCenter;
using Mall.Common.Plugin;
using Mall.Model.Entity.Education;
using Mall.Model.Entity.MarketingCenter;
using Mall.Model.Extend.Education;
using Mall.Model.Extend.MarketingCenter;
using Mall.Model.Extend.Product;
using Mall.Model.Extend.User;
using Mall.Module.Education;
using Mall.Module.User;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Mall.WebApi.Controllers.Education
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class AppletEducationController : BaseController
    {
        private readonly IHttpContextAccessor _accessor;
        private readonly EducationModule educationModule = new EducationModule();
        private readonly DynamicModule dynamicModule = new DynamicModule();
        private readonly UserModule UserModule = new UserModule();
        private readonly Module.Product.ProductModule productModule = new Module.Product.ProductModule();
        private readonly MiniProgramModule programModule = new MiniProgramModule();
        private readonly Module.MarketingCenter.SurveyModule surveyModule = new Module.MarketingCenter.SurveyModule();
        private readonly ActivityModule activityModule = new ActivityModule();

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

        #region 课程卡

        /// <summary>
        /// 领劵中心
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAllCouponPageList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_Education_Coupon_Extend demodel = JsonConvert.DeserializeObject<RB_Education_Coupon_Extend>(req.msg.ToString());
            demodel.UserId = userInfo.UserId;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.SmallShopId = userInfo.UserSmallShopId;
            var list = educationModule.GetAllCouponList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Name,
                x.Describe,
                x.TotalNum,
                x.MemberNum,
                x.CouponIco,
                CouponId = x.ID,
                x.IndateDay,
                x.MaxDiscountsPrice,
                x.IndateType,
                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") : "",
                IsReceive = x.MemberNum > 0 ? 1 : 0,
                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
            });
            return ApiResult.Success("", pagelist);
        }



        /// <summary>
        /// 领取优惠券
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GrantCoupon()
        {
            var userInfo = AppletUserInfo;
            var query = JsonConvert.DeserializeObject<RB_Education_MemberCoupon_Extend>(RequestParm.msg.ToString());
            query.TenantId = userInfo.TenantId;
            query.MallBaseId = userInfo.MallBaseId;
            query.UserId = userInfo.UserId;
            if (query == null)
            {
                return ApiResult.Failed("请传入课程卡信息");
            }
            else
            {
                var oldLogisticsModel = educationModule.GetDiscountCouponList(new RB_Education_Coupon_Extend { TenantId = query.TenantId, MallBaseId = query.MallBaseId, ID = query.CouponId }).FirstOrDefault();
                var allMemberInfo = UserModule.GetMemberUserInfo(userInfo.UserId);

                if (oldLogisticsModel == null || oldLogisticsModel.ID == 0)
                {
                    return ApiResult.Failed("课程卡信息不存在，请核实后再操作");
                }
                if (allMemberInfo.SmallShopId == 0)
                {
                    if (oldLogisticsModel.SmallShopId > 0)
                    {
                        return ApiResult.Failed("您不属于当前店铺");
                    }
                }
                else
                {
                    if (oldLogisticsModel.SmallShopId > 0 && oldLogisticsModel.SmallShopId != allMemberInfo.SmallShopId)
                    {
                        return ApiResult.Failed("领取课程卡不属于当前店铺");
                    }
                    if (allMemberInfo.SmallShopId > 0 && oldLogisticsModel.SmallShopId == 0 && oldLogisticsModel.IsZanYangUse == 1)
                    {
                        return ApiResult.Failed("领取课程卡不属于当前店铺");
                    }
                }


                if (oldLogisticsModel.TotalNum != -1)//判断优惠券剩余数量是够足够
                {
                    if (oldLogisticsModel.TotalNum < 1)
                    {
                        return ApiResult.Failed("课程卡已领完");
                    }
                }
                //判断优惠券是否已领取
                var receiveList = educationModule.GetMemberDiscountCouponList(query);
                if (receiveList != null && receiveList.Any())
                {
                    return ApiResult.Failed("您已领取课程卡");
                }

                if (oldLogisticsModel.IndateType == Common.Enum.MarketingCenter.IndateTypeEnum.TimeHorizon)
                {
                    if (oldLogisticsModel.EndDate.Value < System.DateTime.Now)
                    {
                        return ApiResult.Failed("课程卡时间已过期");
                    }
                }


                RB_Education_MemberCoupon_Extend memberCoupon = new RB_Education_MemberCoupon_Extend
                {
                    Id = 0,
                    UserId = userInfo.UserId,
                    Description = oldLogisticsModel.Describe,
                    CreateDate = System.DateTime.Now,
                    TenantId = userInfo.TenantId,
                    MallBaseId = userInfo.MallBaseId,
                    Remarks = "",
                    CouponId = oldLogisticsModel.ID,
                    Name = oldLogisticsModel.Name,
                    HeXiao = oldLogisticsModel.HeXiao,
                    UseHeXiao = 0,
                    UseType = oldLogisticsModel.UseType
                };
                if (oldLogisticsModel.IndateType == IndateTypeEnum.DayHorizon)
                {
                    memberCoupon.StartDate = System.DateTime.Now;
                    LogHelper.WriteInfo(userInfo.Name + "课程卡领取时间:" + memberCoupon.StartDate);
                    memberCoupon.EndDate = memberCoupon.StartDate.Value.AddDays(oldLogisticsModel.IndateDay);
                }
                else
                {
                    memberCoupon.StartDate = oldLogisticsModel.StartDate;
                    memberCoupon.EndDate = oldLogisticsModel.EndDate;
                }
                var memberList = new List<RB_Education_MemberCoupon_Extend>
                {
                    memberCoupon
                };
                bool result = educationModule.GrantCoupon(memberList, oldLogisticsModel);
                if (result)
                {
                    return ApiResult.Success("课程卡信息领取成功");
                }
                else
                {
                    return ApiResult.Failed("课程卡信息领取成功");
                }
            }
        }


        /// <summary>
        /// 我的优惠券
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMemberCouponPageList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_Education_Coupon_Extend demodel = JsonConvert.DeserializeObject<RB_Education_Coupon_Extend>(req.msg.ToString());
            demodel.UserId = userInfo.UserId;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.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.UseHeXiao,
                x.HeXiao,
                x.ID,
                x.MaxDiscountsPrice,
                x.CouponIco,
                x.MemberCouponId,
                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
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 分享领取课程卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult ShareEducationCoupon()
        {
            var userInfo = AppletUserInfo;
            var query = JsonConvert.DeserializeObject<RB_Education_Coupon_Extend>(RequestParm.msg.ToString());
            query.TenantId = userInfo.TenantId;
            query.MallBaseId = userInfo.MallBaseId;
            query.UserId = userInfo.UserId;
            RB_Education_Coupon_Extend resultModel;
            if (query.TriggerType == 2)
            {
                query.TriggerType = 4;
                resultModel = educationModule.AutoEducationCoupon(query);
                if (resultModel == null || resultModel.ID == 0)
                {
                    query.TriggerType = 2;
                    resultModel = educationModule.AutoEducationCoupon(query);
                }
            }
            else
            {
                resultModel = educationModule.AutoEducationCoupon(query);
            }
            if (resultModel != null && resultModel.ID > 0)
            {
                return ApiResult.CouponSuccess(ResultCode.Success, 1, "", resultModel.Name);
            }
            else
            {
                return ApiResult.CouponFailed(ResultCode.Fail, 1, "", "");
            }
        }




        /// <summary>
        /// 获取用户未使用的优惠券
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetNoUseCouponList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject prams = JObject.Parse(req.msg.ToString());
            var query = JsonConvert.DeserializeObject<RB_Education_Coupon_Extend>(RequestParm.msg.ToString());

            query.TenantId = userInfo.TenantId;
            query.MallBaseId = userInfo.MallBaseId;
            query.UserId = userInfo.UserId;
            var list = educationModule.GetNoUseCouponList(query);

            //获取优惠券对应的商品，或者分类
            List<RB_Product_Category_Extend> categotyList = new List<RB_Product_Category_Extend>();

            List<RB_Education_CouponProduct_Extend> productList = new List<RB_Education_CouponProduct_Extend>();

            string Ids = "";
            foreach (var item in list.Where(x => x.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Category))
            {
                productList.AddRange(item.ProductList);
                item.CategoryIds = item.ProductList.Select(x => x.ProductId).ToList().ToArray();
            }
            if (productList != null && productList.Any())
            {
                Ids = string.Join(",", productList.Select(x => x.ProductId));
            }
            if (!string.IsNullOrWhiteSpace(Ids))
            {
                categotyList = productModule.GetCategoryListModule(new Model.Extend.Product.RB_Product_Category_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, CategoryIds = Ids });
            }

            if (categotyList == null || !categotyList.Any())
            {
                categotyList = new List<RB_Product_Category_Extend>();
            }



            List<RB_Goods_Extend> goodsList = new List<RB_Goods_Extend>();

            productList = new List<RB_Education_CouponProduct_Extend>();

            Ids = "";

            foreach (var item in list.Where(x => x.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Product))
            {
                productList.AddRange(item.ProductList);
                item.GoodsIds = item.ProductList.Select(x => x.ProductId).ToList().ToArray();
            }
            if (productList != null && productList.Any())
            {
                Ids = string.Join(",", productList.Select(x => x.ProductId));
            }

            if (!string.IsNullOrWhiteSpace(Ids))
            {
                goodsList = productModule.GetProductGoodsList(new RB_Goods_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, GoodsIds = Ids });
            }
            if (goodsList == null || !goodsList.Any())
            {
                goodsList = new List<RB_Goods_Extend>();
            }
            var result = list.Select(x => new
            {
                id = x.MemberCouponId,
                mall_id = userInfo.MallBaseId,
                user_id = userInfo.UserId,
                coupon_id = x.ID,
                start_time = x.StartDate.HasValue ? x.StartDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                end_time = x.EndDate.HasValue ? x.EndDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                is_use = 0,
                is_delete = 0,
                created_at = x.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                updated_at = x.UpdateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                deleted_at = "0000-00-00 00:00:00",
                receive_type = "",
                discount_limit = x.MaxDiscountsPrice,
                usehexiao = x.HeXiao - x.UseHeXiao,
                couponIco = x.CouponIco,
                coupon_data = new
                {
                    id = x.ID,
                    mall_id = userInfo.MallBaseId,
                    name = x.Name,
                    pic_url = "",
                    desc = "",
                    total_count = x.TotalNum + x.ReceiveNum,
                    expire_type = x.IndateType,
                    expire_day = x.IndateDay,
                    begin_time = x.StartDate.HasValue ? x.StartDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                    end_time = x.EndDate.HasValue ? x.EndDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                    appoint_type = (int)x.UseType,
                    rule = x.Describe,
                    is_delete = 0,
                    deleted_at = "0000-00-00 00:00:00",
                    created_at = x.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                    updated_at = x.UpdateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                    discount_limit = x.MaxDiscountsPrice,
                    couponIco = x.CouponIco,
                    usehexiao = x.HeXiao - x.UseHeXiao,
                    car = categotyList.Where(y => x.CategoryIds.Contains(x.ID)).Select(y => new
                    {
                        id = y.Id,
                        mall_id = userInfo.MallBaseId,
                        mch_id = 0,
                        parent_id = y.ParentId,
                        name = y.Name,
                        pic_url = y.AdvertisingImagePath,
                        sort = y.Sort,
                        big_pic_url = y.BigIconPath,
                        advert_pic = y.AdvertisingImage,
                        advert_url = y.AdvertisingImagePath,
                        status = y.Status,
                        created_at = y.CreateDate.HasValue ? y.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                        updated_at = y.UpdateDate.HasValue ? y.UpdateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                        deleted_at = "0000-00-00 00:00:00",
                        is_delete = 0,
                        is_show = y.IsShow,
                        advert_open_type = "",
                        advert_params = ""
                    }),
                    goods = goodsList.Where(y => x.GoodsIds.Contains(x.ID)).Select(y => new
                    {
                        id = y.Id,
                        mall_id = userInfo.MallBaseId,
                        name = y.Name,
                        original_price = y.OriginalPrice,
                        cost_price = y.CostPrice,
                        detail = y.GoodsDetails,
                        cover_pic = y.CoverImage,
                        pic_url = "",
                        video_url = y.VideoAddress,
                        unit = y.Unit,
                        created_at = y.CreateDate.HasValue ? y.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                        updated_at = y.UpdateDate.HasValue ? y.UpdateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                        deleted_at = "0000-00-00 00:00:00",
                        is_delete = 0,
                    }),
                },
                x.Name,
                x.Describe,
                x.MaxDiscountsPrice,
                x.UseType
            });
            return ApiResult.Success("", result);

        }

        #endregion

        #region 我的学习

        /// <summary>
        /// 获取我的学习时间
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMyStudyTime()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            int Day = parms.GetInt("Day", 0);
            var obj = educationModule.GetMyStudyTime(Day, userInfo.UserId);
            return ApiResult.Success("", obj);
        }

        /// <summary>
        /// 增加课程学习时间
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetMyStudyTime()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            int GoodsId = parms.GetInt("GoodsId", 0);
            int Time = parms.GetInt("Time", 10);//秒
            if (GoodsId <= 0)
            {
                return ApiResult.ParamIsNull("请传递课程id");
            }
            if (Time <= 0)
            {
                return ApiResult.ParamIsNull("时间不能小于等于0");
            }
            bool flag = educationModule.SetMyStudyTime(GoodsId, Time, userInfo.UserId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 设置课程已观看
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetMyCourseStudyOK()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            int GoodsId = parms.GetInt("GoodsId", 0);
            int CourseId = parms.GetInt("CourseId", 0);//课程id
            if (GoodsId <= 0)
            {
                return ApiResult.ParamIsNull("请传递课程id");
            }
            if (CourseId <= 0)
            {
                return ApiResult.ParamIsNull("请传递课程id");
            }
            bool flag = educationModule.SetMyCourseStudyOK(GoodsId, CourseId, userInfo.UserId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 获取最新学习列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMyRecentStudyPageList()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());

            var list = educationModule.GetMyRecentStudyPageList(pagelist.pageIndex, pagelist.pageSize, out long count, userInfo.UserId);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list;
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取学习明细列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMyStudyDetailPageList()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());

            var list = educationModule.GetMyStudyDetailPageList(pagelist.pageIndex, pagelist.pageSize, out long count, userInfo.UserId);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list;
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取我的报名记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMyOrderStudyRecordPageList()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());

            var list = educationModule.GetMyOrderStudyRecordPageList(pagelist.pageIndex, pagelist.pageSize, out long count, userInfo.UserId);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list;
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取课程未缓存的章节列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMyCourseNoCachePageList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            JObject prams = JObject.Parse(req.msg.ToString());
            int GoodsId = prams.GetInt("GoodsId", 0);
            string CourseName = prams.GetStringValue("CourseName");
            if (GoodsId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            if (userInfo != null && userInfo.UserId > 0)
            {
                var list = educationModule.GetMyCourseNoCachePageList(pagelist.pageIndex, pagelist.pageSize, out long count, GoodsId, CourseName, userInfo.UserId, userInfo.TenantId, userInfo.MallBaseId);

                pagelist.count = Convert.ToInt32(count);
                pagelist.pageData = list.Select(x => new
                {
                    x.Id,
                    x.GoodsId,
                    x.Sort,
                    x.SortName,
                    x.Name,
                    x.Type,
                    TypeName = x.Type.GetEnumName(),
                    x.FilePath
                });
            }
            else
            {
                pagelist.count = 0;
                pagelist.pageData = new List<RB_Goods_WK_Course_Extend>();
            }
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取课程已缓存的章节列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMyCourseCachedPageList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            JObject prams = JObject.Parse(req.msg.ToString());
            int GoodsId = prams.GetInt("GoodsId", 0);
            string CourseName = prams.GetStringValue("CourseName");
            if (GoodsId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            if (userInfo != null && userInfo.UserId > 0)
            {
                var list = educationModule.GetMyCourseCachedPageList(pagelist.pageIndex, pagelist.pageSize, out long count, GoodsId, CourseName, userInfo.UserId, userInfo.TenantId, userInfo.MallBaseId);

                pagelist.count = Convert.ToInt32(count);
                pagelist.pageData = list.Select(x => new
                {
                    x.Id,
                    x.GoodsId,
                    x.Sort,
                    x.SortName,
                    x.Name,
                    x.Type,
                    TypeName = x.Type.GetEnumName(),
                    x.FilePath,
                    x.FileState,
                    x.Size,
                    x.Unit
                });
            }
            else
            {
                pagelist.count = 0;
                pagelist.pageData = new List<RB_Goods_WK_Course_Extend>();
            }
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetMyCourseCache()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            RB_Goods_WK_DownLoad_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_WK_DownLoad_Extend>(req.msg.ToString());
            if (demodel.CourseId <= 0)
            {
                return ApiResult.ParamIsNull("请传递课程id");
            }
            if (string.IsNullOrEmpty(demodel.FilePath))
            {
                return ApiResult.ParamIsNull("请传递本地存储路径");
            }
            if (demodel.FileType <= 0)
            {
                return ApiResult.ParamIsNull("请传递文件类型");
            }

            demodel.UserId = userInfo.UserId;
            return educationModule.SetMyCourseCache(demodel);
        }

        /// <summary>
        /// 设置缓存课程状态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetMyCourseCacheState()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            int CourseId = parms.GetInt("CourseId");
            int FileState = parms.GetInt("FileState");
            if (CourseId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            bool flag = educationModule.SetMyCourseCacheState(CourseId, userInfo.UserId, FileState);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 删除缓存
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelMyCourseCache()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            string CourseIds = parms.GetStringValue("CourseIds");
            if (string.IsNullOrEmpty(CourseIds))
            {
                return ApiResult.ParamIsNull();
            }

            bool flag = educationModule.DelMyCourseCache(CourseIds, userInfo.UserId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        #endregion

        #region 资讯留言

        /// <summary>
        /// 管理新增评论
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetArticleCommentInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            AppletUserInfo uInfo = UserReidsCache.GetAppletUserBlacklistInfo(userInfo.UserId);
            if ((uInfo?.Blacklist ?? 0) == 1)
            {
                return ApiResult.Failed("已进入黑名单，无法访问");
            }
            RB_Education_ArticleComment_Extend demodel = JsonConvert.DeserializeObject<RB_Education_ArticleComment_Extend>(req.msg.ToString());

            if (demodel.ArticleId <= 0)
            {
                return ApiResult.ParamIsNull("请选择资讯");
            }
            if (string.IsNullOrEmpty(demodel.Content))
            {
                return ApiResult.ParamIsNull("请输入评价内容");
            }
            var articleModle = educationModule.GetArticleEntity(demodel.ArticleId);
            if (articleModle == null)
            {
                return ApiResult.ParamIsNull("资讯信息不存在");
            }
            if (articleModle.IsComment == 0)
            {
                return ApiResult.ParamIsNull("资讯不允许留言");
            }

            #region 内容是否违规
            try
            { //获取订阅消息
                var miniModel = programModule.GetMiniProgramModule(new RB_MiniProgram_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });
                int violationNum = new MiniProgramMsgModule().CheckViolation(miniModel, demodel.Content);
                if (violationNum == 0)
                {
                    return ApiResult.Failed("评论内容检测失败，请稍后再试");
                }
                else if (violationNum == 1)
                {
                    var violationLogList = educationModule.GetViolationLogList(new RB_Education_ViolationLog { TenantId = uInfo.TenantId, MallBaseId = uInfo.MallBaseId, UserId = uInfo.UserId });
                    if (violationLogList != null && violationLogList.Any() && (violationLogList.Count() + 1) >= miniModel.ViolationNum)
                    {
                        userInfo = new AppletUserInfo
                        {
                            MallBaseId = uInfo.MallBaseId,
                            UserId = uInfo.UserId,
                            TenantId = uInfo.TenantId,
                            Name = uInfo.Name,
                            SuperiorId = uInfo.SuperiorId,
                            Blacklist = 1
                        };
                        CacheManager.User.UserReidsCache.AppletUserInfoSet(CacheKey.UserModuleCacheKeyConfig.Applet_Blacklist_Info + uInfo.UserId, userInfo, Config.JwtExpirTime);
                        educationModule.UpdateUserBlacklist(uInfo.TenantId, uInfo.MallBaseId, uInfo.UserId);
                    }
                    educationModule.SetEducationViolationLog(new RB_Education_ViolationLog { TenantId = uInfo.TenantId, MallBaseId = uInfo.MallBaseId, UserId = uInfo.UserId, ViolationType = 1, CreateDate = System.DateTime.Now });
                    return ApiResult.Failed("评论存在违规内容，若多次发布违规内容将被拉黑");
                }
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "InsertOrderPayInfo");
                return ApiResult.Failed("评论内容检测失败，请稍后再试");
            }
            #endregion
            demodel.CommentGrade ??= Common.Enum.Goods.GoodsCommentTypeEnum.Praise;
            demodel.CommentScore ??= 5;
            demodel.CommentImage = "";
            if (demodel.CommentImgList != null && demodel.CommentImgList.Any())
            {
                demodel.CommentImage = JsonConvert.SerializeObject(demodel.CommentImgList);
            }
            demodel.UserId = userInfo.UserId;
            demodel.UserName = userInfo.Name;
            demodel.PlatformSource = userInfo.Source;
            demodel.UserPhoto ??= 0;
            demodel.Is_Top ??= 2;
            demodel.Is_Show ??= 1;
            demodel.Is_Anonymity ??= 2;
            demodel.Reply ??= "";
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.Status = 0;
            demodel.UpdateDate = DateTime.Now;
            demodel.CreateDate = DateTime.Now;
            bool flag = educationModule.SetArticleCommentInfo(demodel);
            if (flag) { return ApiResult.Success(); } else { return ApiResult.Failed(); }
        }
        #endregion

        #region 我的订单

        /// <summary>
        /// 获取订单状态枚举
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult EducationOrderStatusEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(Common.Enum.Goods.EducationOrderStatusEnum));
            return ApiResult.Success("", list.OrderBy(x => Convert.ToInt32(x.Value)).Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }



        /// <summary>
        /// 我的订单分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletGoodsEducationOrderPageList()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(parms.msg.ToString());

            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            demodel.Recycled = 2;
            var list = educationModule.GetAppletGoodsMyOrderPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            //获取订阅消息
            var miniModel = programModule.GetMiniProgramModule(new RB_MiniProgram_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });

            List<string> template_message_list = new List<string>();

            if (miniModel != null)
            {
                if (!string.IsNullOrWhiteSpace(miniModel.RefundTpl))
                {
                    template_message_list.Add(miniModel.RefundTpl);
                }
                if (!string.IsNullOrWhiteSpace(miniModel.OrderCancelTpl))
                {
                    template_message_list.Add(miniModel.OrderCancelTpl);
                }
            }
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                template_message_list,
                x.OrderId,
                x.OrderNo,
                x.DeliveryMethod,
                x.Income,
                x.FreightMoney,
                x.CouponMoney,
                x.PaymentWay,
                PaymentWayName = x.PaymentWay.GetEnumName(),
                DetailList = x.DetailList.Select(y => new
                {
                    y.Id,
                    y.GoodsId,
                    y.CoverImagePath,
                    y.OrderType,
                    OrderTypeName = y.OrderType.GetEnumName(),
                    y.GoodsName,
                    y.SpecificationSort,
                    SpecificationList = JsonConvert.DeserializeObject<List<string>>(y.Specification),
                    y.ProductCode,
                    y.Final_Price,
                    y.Unit_Price,
                    y.Number,
                    y.UseDay,
                    y.IsSpell,
                    y.CarNumber,
                    y.LineName,
                    y.IsComment,
                    TripSTime = y.TripSTime.HasValue ? y.TripSTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                    TripETime = y.TripETime.HasValue ? y.TripETime.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
                }),
                x.OrderStatus,
                OrderStatusName = ((Common.Enum.Goods.EducationOrderStatusEnum)x.OrderStatus).GetEnumName(),
                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 GetAppletGuidecarOrderOrderInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderId = parms.GetInt("OrderId", 0);
            //HK2020-08-08新增
            if (parms.GetInt("NewUserId") > 0)
            {
                userInfo.UserId = parms.GetInt("NewUserId");
            }
            if (OrderId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            return educationModule.GetAppletMyOrderInfo(OrderId, userInfo.UserId, userInfo.TenantId, userInfo.MallBaseId);
        }

        #endregion

        #region 我关注的老师
        /// <summary>
        /// 我关注的老师
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetFollowTeacherPageList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_Education_FollowTeacher_Extend demodel = JsonConvert.DeserializeObject<RB_Education_FollowTeacher_Extend>(req.msg.ToString());
            demodel.UserId = userInfo.UserId;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            var list = educationModule.GetFollowTeacherPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            foreach (var item in list)
            {
                if (!string.IsNullOrWhiteSpace(item.LableName))
                {
                    item.LableNameList = JsonConvert.DeserializeObject<List<string>>(item.LableName);
                }
            }
            pagelist.pageData = list.Select(x => new
            {
                x.ID,
                x.TeacherLogo,
                x.Telephone,
                x.Major,
                x.LableNameList,
                x.Name,
                x.TeacherId,
                CreateDate = x.CreateDate.ToString("yyyy-MM-dd HH:ss:mm"),

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



        /// <summary>
        /// 关注老师
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetFollowTeacher()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            var query = JsonConvert.DeserializeObject<RB_Education_FollowTeacher>(RequestParm.msg.ToString());
            query.TenantId = userInfo.TenantId;
            query.MallBaseId = userInfo.MallBaseId;
            query.UserId = userInfo.UserId;

            bool isUpdate = true;

            if (query == null)
            {
                return ApiResult.Failed("请传入我关注的老师信息");
            }
            else
            {
                //判断是否已经关注过
                var oldList = educationModule.GetFollowTeacherList(new RB_Education_FollowTeacher_Extend { Status = -1, UserId = query.UserId, TeacherId = query.TeacherId, MallBaseId = query.MallBaseId, TenantId = query.TenantId }); ;
                if (query.ID == 0)
                {
                    isUpdate = false;
                    query.CreateDate = System.DateTime.Now;
                    query.UpdateDate = System.DateTime.Now;
                    if (query.TeacherId <= 0)
                    {
                        return ApiResult.Failed("请传入我关注的老师信息");
                    }

                    if (oldList != null && oldList.Any(x => x.Status == 0))
                    {
                        return ApiResult.Failed("您已关注，请勿重复操作");
                    }
                    else
                    {
                        if (oldList != null && oldList.Any())
                        {
                            query.ID = oldList.OrderByDescending(x => x.CreateDate).FirstOrDefault().ID;
                        }
                        query.Status = 0;
                    }
                }
                else
                {
                    query.Status = 1;
                }

                bool result = educationModule.AddOrUpdateFollowTeacher(query);
                if (isUpdate)
                {
                    if (result)
                    {
                        return ApiResult.Success("取消关注成功");
                    }
                    else
                    {
                        return ApiResult.Failed("取消关注成功");
                    }
                }
                else
                {
                    //获取订阅消息
                    var miniModel = programModule.GetMiniProgramModule(new RB_MiniProgram_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });

                    List<string> template_message_list = new List<string>();

                    if (miniModel != null)
                    {
                        if (!string.IsNullOrWhiteSpace(miniModel.EducationDynamicTpl))
                        {
                            template_message_list.Add(miniModel.EducationDynamicTpl);
                        }
                    }
                    if (result)
                    {
                        return ApiResult.Success("关注成功", template_message_list);
                    }
                    else
                    {
                        return ApiResult.Failed("关注成功");
                    }
                }
            }
        }
        #endregion

        #region 我的收藏

        /// <summary>
        /// 获取收藏商品分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserCollectionPageList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_Goods_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Extend>(req.msg.ToString());

            demodel.UserId = userInfo.UserId;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            var list = educationModule.GetCollectEducationGoodsPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            foreach (var item in list)
            {
                if (!string.IsNullOrWhiteSpace(item.CourseLable))
                {
                    item.CourseLableList = JsonConvert.DeserializeObject<List<string>>(item.CourseLable);
                }
            }
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.CoverImage,
                x.SellingPrice,
                x.SalesNum,
                x.CourseLableList
            });

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

        #endregion



        #region 问卷调查
        /// <summary>
        /// 新增会员意见调查信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetGuestSurvey()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            List<Rb_Survey_Extend> modelSurvey = JsonConvert.DeserializeObject<List<Rb_Survey_Extend>>(req.msg.ToString());

            if (modelSurvey == null || !modelSurvey.Any())
            {
                return ApiResult.Failed("选项信息不能空");
            }
            Rb_GuestSurvey_Extend model = new Rb_GuestSurvey_Extend();
            if ((modelSurvey.FirstOrDefault()?.ActivitySurveyId ?? 0) == 0)
            {
                return ApiResult.Failed("请选择活动对应的问卷信息");
            }

            var activeSurueyModel = surveyModule.GetActivitySurveyList(new RB_ActivitySurvey_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, ID = modelSurvey.FirstOrDefault()?.ActivitySurveyId ?? 0 }).FirstOrDefault();
            if (activeSurueyModel == null || activeSurueyModel.ID == 0)
            {
                return ApiResult.Failed("请选择活动对应的问卷信息");
            }

            //先判断是否已添加
            var GuestSurvey = surveyModule.GetGuestSurveyList(new Rb_GuestSurvey_Extend { ActivitySurveyId = modelSurvey.FirstOrDefault()?.ActivitySurveyId ?? 0, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });

            if (activeSurueyModel.StartDate.HasValue && activeSurueyModel.EndDate.HasValue)
            {
                if (activeSurueyModel.StartDate.Value > System.DateTime.Now)
                {
                    return ApiResult.Failed("问卷调查活动还未开始");
                }
                if (activeSurueyModel.EndDate.Value < System.DateTime.Now)
                {
                    return ApiResult.Failed("问卷调查活动已结束");
                }
            }
            //if (activeSurueyModel.SurveyNum != -1 && activeSurueyModel.SurveyNum <= GuestSurvey.Count())
            //{
            //    return ApiResult.Failed(activeSurueyModel.SurveyNum + "份问卷调查已填写完");
            //}
            if (GuestSurvey.Where(x => x.UserId == userInfo.UserId).Count() > 0)
            {
                return ApiResult.Failed("请勿重复参与问卷调查");
            }

            model.UserId = userInfo.UserId;
            model.TenantId = userInfo.TenantId;
            model.MallBaseId = userInfo.MallBaseId;
            model.CreateDate = System.DateTime.Now;
            model.ID = 0;
            model.State = DateStateEnum.Normal;
            model.ActivitySurveyId = modelSurvey.FirstOrDefault()?.ActivitySurveyId ?? 0;
            var scoreList = modelSurvey.Where(x => x.SurveyType == SurveyTypeEnum.Score);
            if (scoreList != null && scoreList.Any())
            {
                model.ScoreNum = Convert.ToDecimal(scoreList.Sum(x => x.ScoreNum)) / Convert.ToDecimal(scoreList.Count());
            }
            else
            {
                model.ScoreNum = 0;
            }
            model.SurveyOptionsList = new List<Rb_GuestSurveyDetails>();
            foreach (var item in modelSurvey)
            {
                Rb_GuestSurveyDetails modelSurveyOptions = new Rb_GuestSurveyDetails
                {
                    ID = 0,
                    SurveyId = item.ID,
                };
                if (item.SurveyType == SurveyTypeEnum.MultiSelect)
                {
                    modelSurveyOptions.ScoreNum = 0;
                    var surveyDetailsList = item.SurveyOptionsList.Where(x => x.IsCheck == "1");
                    if ((surveyDetailsList == null || !surveyDetailsList.Any()) && item.IsRequired == 1)
                    {
                        return ApiResult.Failed(item.Title + "您还未选择");
                    }
                    modelSurveyOptions.SurveyOptionIds = (surveyDetailsList == null || !surveyDetailsList.Any()) ? "" : string.Join(",", surveyDetailsList.Select(x => x.ID));
                }
                else if (item.SurveyType == SurveyTypeEnum.Score)
                {
                    if (item.IsRequired == 1 && item.ScoreNum == 0)
                    {
                        return ApiResult.Failed(item.Title + "您还未打分");
                    }
                    modelSurveyOptions.ScoreNum = item.ScoreNum;
                }
                else if (item.SurveyType == SurveyTypeEnum.TheRadio)
                {
                    modelSurveyOptions.ScoreNum = 0;
                    var surveyDetailsList = item.SurveyOptionsList.Where(x => x.IsCheck == "1");
                    if ((surveyDetailsList == null || !surveyDetailsList.Any()) && item.IsRequired == 1)
                    {
                        return ApiResult.Failed(item.Title + "您还未选择");
                    }
                    else if (surveyDetailsList.Count() > 1)
                    {
                        return ApiResult.Failed(item.Title + "请勿多选");
                    }
                    modelSurveyOptions.SurveyOptionIds = (surveyDetailsList == null || !surveyDetailsList.Any()) ? "" : string.Join(",", surveyDetailsList.Select(x => x.ID));
                }
                else if (item.SurveyType == SurveyTypeEnum.TheText)
                {
                    if (item.IsRequired == 1 && string.IsNullOrWhiteSpace(item.TextContent))
                    {
                        return ApiResult.Failed(item.Title + "必填填写");
                    }
                    modelSurveyOptions.TextContent = item.TextContent;
                    modelSurveyOptions.ScoreNum = 0;
                }
                model.SurveyOptionsList.Add(modelSurveyOptions);
            }

            int flag = surveyModule.SetGuestSurvey(model);
            if (flag > 0)
            {
                return ApiResult.Success();
            }

            else
                return ApiResult.Failed("问卷调查提交失败");
        }



        /// <summary>
        /// 获取会员调查问题列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSurveyShowList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            Rb_Survey_Extend model = JsonConvert.DeserializeObject<Rb_Survey_Extend>(req.msg.ToString());
            var activeSurueyModel = surveyModule.GetActivitySurveyList(new RB_ActivitySurvey_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, ID = model.ActivitySurveyId }).FirstOrDefault();
            if (activeSurueyModel == null || activeSurueyModel.ID == 0)
            {
                return ApiResult.Failed("问卷调查活动不存在");
            }
            //先判断是否已添加
            var GuestSurvey = surveyModule.GetGuestSurveyList(new Rb_GuestSurvey_Extend { ActivitySurveyId = model.ActivitySurveyId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });

            int isEnd = 0;
            if (activeSurueyModel.StartDate.HasValue && activeSurueyModel.EndDate.HasValue)
            {
                if (activeSurueyModel.StartDate.Value < System.DateTime.Now && activeSurueyModel.EndDate.Value > System.DateTime.Now)
                {
                    isEnd = 1;
                }
                else if (activeSurueyModel.StartDate.Value > System.DateTime.Now)
                {
                    isEnd = 0;
                }
                else if (activeSurueyModel.EndDate.Value < System.DateTime.Now)
                {
                    isEnd = 2;
                }
            }
            var list = surveyModule.GetAllList(model);
            var result = new
            {
                isEnd,
                activeSurueyModel.SurveyNum,
                GuestSurveyNum = GuestSurvey.Count(),
                Surplus = activeSurueyModel.SurveyNum - GuestSurvey.Count(),
                StartDate = activeSurueyModel.StartDate.HasValue ? activeSurueyModel.StartDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                EndDate = activeSurueyModel.EndDate.HasValue ? activeSurueyModel.EndDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                activeSurueyModel.Title,
                activeSurueyModel.Description,
                activeSurueyModel.PrizeAddress,
                activeSurueyModel.PrizeType,
                activeSurueyModel.ID,
                FillInNum = GuestSurvey.Where(x => x.UserId == userInfo.UserId).Count(),
                BaseList = list.Where(x => x.FormType == FormTypeEnum.Base).OrderBy(x => x.Sort).Select(x => new { x.ID, x.IsRequired, x.ActivitySurveyId, SurveyType = (int)x.SurveyType, x.FormType, x.Title, x.Sort, SurveyTypeStr = EnumHelper.GetEnumName(x.SurveyType), FormTypeStr = EnumHelper.GetEnumName(x.FormType), x.SurveyOptionsList, ScoreNum = (x.SurveyType.HasValue && x.SurveyType == SurveyTypeEnum.Score) ? 5 : 0, TextContent = "" }).ToList(),
                SurveyList = list.Where(x => x.FormType == FormTypeEnum.Survey).OrderBy(x => x.Sort).Select(x => new { x.ID, x.IsRequired, x.ActivitySurveyId, SurveyType = (int)x.SurveyType, x.FormType, x.Title, x.Sort, SurveyTypeStr = EnumHelper.GetEnumName(x.SurveyType), FormTypeStr = EnumHelper.GetEnumName(x.FormType), x.SurveyOptionsList, ScoreNum = (x.SurveyType.HasValue && x.SurveyType == SurveyTypeEnum.Score) ? 5 : 0, TextContent = "" }).ToList()
            };
            return ApiResult.Success("", result);
        }

        #endregion


        #region 老师动态

        /// <summary>
        /// 我的动态列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMyDynamicList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            Rb_Education_Dynamic_Extend demodel = JsonConvert.DeserializeObject<Rb_Education_Dynamic_Extend>(req.msg.ToString());
            demodel.CreateBy = userInfo.UserId;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            List<Rb_Education_Dynamic_Extend> myArticleList = dynamicModule.MyDynamicList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            List<object> list = new List<object>();
            foreach (var item in myArticleList)
            {
                list.Add(DecoratorDynameicResult(item));
            }
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list;
            return ApiResult.Success("", pagelist);
        }


        /// <summary>
        /// 我的动态列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAboutMeDynamicList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            Rb_Education_Dynamic_Extend demodel = JsonConvert.DeserializeObject<Rb_Education_Dynamic_Extend>(req.msg.ToString());
            demodel.CreateBy = userInfo.UserId;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            List<Rb_Education_Dynamic_Extend> myArticleList = dynamicModule.AboutMeDynamicList(demodel, pagelist.pageIndex, pagelist.pageSize, out long count);
            List<object> list = new List<object>();
            foreach (var item in myArticleList)
            {
                List<string> fileList = new List<string>();
                if (!string.IsNullOrEmpty(item.Files))
                {
                    fileList = JsonConvert.DeserializeObject<List<string>>(item.Files);
                }
                var resultData = new { id = item.Id, content = StringHelper.FromUnicodeString(item.Content), coverPhoto = item.CoverPhoto, item.TalkId, item.TalkContent, fileType = item.FileType, fileList, realtionType = item.RealtionType, commentContent = StringHelper.FromUnicodeString(item.CommentContent), createEmpId = item.CreateBy, createEmName = item.CreateByName, crearteEmPhoto = item.CrearteByPhoto, replyName = item.ReplyName ?? "", replyPhoto = item.ReplyPhoto ?? "", createTime = StringHelper.DateFormatToString(item.CreateTime.Value), commentId = item.CommentId };
                list.Add(resultData);
            }
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list;
            return ApiResult.Success("", pagelist);
        }



        /// <summary>
        /// 发布动态
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetPublishDynamic()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            if (userInfo == null)
            {
                return ApiResult.Failed("请重新登录");
            }
            if (userInfo.UserTeacher == 0)
            {
                return ApiResult.Failed("您暂无绑定老师账户");
            }

            Rb_Education_Dynamic_Extend article = JsonConvert.DeserializeObject<Rb_Education_Dynamic_Extend>(req.msg.ToString());
            var teacherModel = educationModule.GetTeacherModel(new RB_Education_Teacher_Extend { ID = userInfo.UserTeacher, MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId });
            if (teacherModel.TeacherStatus == 2)
            {
                return ApiResult.Failed("您暂时无法发布动态");
            }

            article.Content = StringHelper.UrlDecode(article.Content);
            if (string.IsNullOrWhiteSpace(article.Content) && (article.FileList == null || !article.FileList.Any()))
            {
                return ApiResult.Failed("文字和文件不能同时为空");
            }
            article.CreateTime = DateTime.Now;
            article.CreateBy = userInfo.UserId;
            article.TenantId = userInfo.TenantId;
            article.MallBaseId = userInfo.MallBaseId;
            article.UserTeacher = userInfo.UserTeacher;
            article.CoverPhoto = "";
            if (article.FileList != null && article.FileList.Count() > 0)
            {
                article.Files = JsonConvert.SerializeObject(article.FileList);
                article.CoverPhoto = article.FileList[0];
            }
            else
            {
                article.FileType = 0;
            }
            article.Content = StringHelper.ToUnicodeString(article.Content);

            article.Status = 0;
            if (dynamicModule.PublishDynamic(article))
            {
                var oldList = educationModule.GetFollowUserList(new RB_Education_FollowTeacher_Extend { TeacherId = userInfo.UserTeacher, MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId });
                if (oldList != null && oldList.Any())//有关注的人
                {
                    List<string> openIds = oldList.Select(x => x.OpenId).ToList();
                    new MiniProgramMsgModule().SendEducationDynamicMsg(userInfo.TenantId, userInfo.MallBaseId, openIds, "您关注的老师又有新动态了", teacherModel.Name, article.CreateTime.Value.ToString("yyyy年MM月dd日"));
                }
                return ApiResult.Success("发布成功");
            }
            else
            {
                return ApiResult.Failed("发布失败");
            }
        }

        /// <summary>
        /// 动态列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDynamicDetial()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parm = JObject.Parse(req.msg.ToString());
            int articleId = parm.GetInt("articleId");
            if (articleId == 0)
            {
                return ApiResult.Failed("动态id不为空");
            }
            Rb_Education_Dynamic_Extend articele = dynamicModule.GetDynamicDetial(new Rb_Education_Dynamic_Extend { UserId = userInfo.UserId, Id = articleId });
            if (articele != null)
            {
                var data = DecoratorDynameicResult(articele);
                return ApiResult.Success(data: data);
            }
            else
            {
                return ApiResult.Failed("动态不存在");
            }
        }



        /// <summary>
        /// 返回动态详情
        /// </summary>
        /// <param name="article">动态内容</param>
        /// <returns></returns>

        public object DecoratorDynameicResult(Rb_Education_Dynamic_Extend article)
        {
            List<string> fileList = new List<string>();
            if (!string.IsNullOrEmpty(article.Files))
            {
                fileList = JsonConvert.DeserializeObject<List<string>>(article.Files);
            }
            //StringHelper.UrlEncode(StringHelper.FromUnicodeString(article.Content))
            var resultData = new { id = article.Id, createEmpId = article.CreateBy, article.TalkContent, article.TalkId, createEmName = article.CreateByName, crearteEmPhoto = article.CrearteByPhoto, YearTime = article.CreateTime.HasValue ? (article.CreateTime.Value.Year == System.DateTime.Now.Year ? "" : article.CreateTime.Value.ToString("yyyy")) : "", MonthTime = article.CreateTime.HasValue ? article.CreateTime.Value.ToString("MM") : "", DayTime = article.CreateTime.HasValue ? article.CreateTime.Value.ToString("dd") : "", createTime = article.CreateTime.HasValue ? StringHelper.DateFormatToString(article.CreateTime.Value) : "", content = StringHelper.FromUnicodeString(article.Content), coverPhoto = article.CoverPhoto, fileType = article.FileType, latAndLong = article.LatAndLong, address = article.Address, files = fileList, hasLike = article.HasLike, likeList = article.LikeList.Select(t => new { empId = t.UserId, empName = t.EmName, t.Id }), commentList = article.CommentList.Select(t => new { commentId = t.Id, empId = t.UserId, empName = t.UserName, byReplayEmpId = t.ByReplyEmpId, byReplayEmpName = t.ByReplyEmName, content = StringHelper.FromUnicodeString(t.Content) }) };
            return resultData;
        }
        /// <summary>
        /// 删除动态
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDeleteDynamic()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parm = JObject.Parse(req.msg.ToString());
            int articleId = parm.GetInt("articleId");
            if (articleId == 0)
            {
                return ApiResult.Failed("动态id不为空");
            }
            if (dynamicModule.DeleteDynamic(userInfo.UserId, articleId, userInfo.TenantId, userInfo.MallBaseId))
            {
                return ApiResult.Success("删除成功");
            }
            else
            {
                return ApiResult.Failed("动态不存在");
            }
        }
        /// <summary>
        /// 动态点赞
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDynamicLike()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parm = JObject.Parse(req.msg.ToString());
            int articleId = parm.GetInt("articleId");
            if (articleId == 0)
            {
                return ApiResult.Failed("动态id不为空");
            }

            var likeList = dynamicModule.GetDynamicLikeList(new Rb_Education_DynamicLike_Extend { UserId = userInfo.UserId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, ArticleId = articleId });
            if (likeList != null && likeList.Any())
            {
                return ApiResult.Failed("请勿重复点赞");
            }
            if (dynamicModule.DynamicLike(new Rb_Education_DynamicLike { UserId = userInfo.UserId, ArticleId = articleId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }))
            {
                return ApiResult.Success("点赞成功");
            }
            else
            {
                return ApiResult.Failed("点赞失败");
            }
        }
        /// <summary>
        /// 动态取消点赞
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDynamicCancelLike()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parm = JObject.Parse(req.msg.ToString());
            int articleId = parm.GetInt("articleId");
            if (articleId == 0)
            {
                return ApiResult.Failed("动态id不能为空");
            }
            var likeModel = dynamicModule.GetDynamicLikeList(new Rb_Education_DynamicLike_Extend { UserId = userInfo.UserId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, ArticleId = articleId }).FirstOrDefault();
            if (likeModel != null && likeModel.Id > 0)
            {
                dynamicModule.DynamicCancelLike(new Rb_Education_DynamicLike { UserId = userInfo.UserId, Id = likeModel.Id, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });
            }

            return ApiResult.Success("取消成功");
        }
        /// <summary>
        /// 动态评论
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDynamicComment()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            AppletUserInfo uInfo = UserReidsCache.GetAppletUserBlacklistInfo(userInfo.UserId);
            if ((uInfo?.Blacklist ?? 0) == 1)
            {
                return ApiResult.Failed("已进入黑名单，无法访问");
            }
            Rb_Education_DynamicComment comment = JsonConvert.DeserializeObject<Rb_Education_DynamicComment>(req.msg.ToString());
            comment.Content = StringHelper.UrlDecode(comment.Content);
            string str = comment.Validate();
            if (!str.Equals("ok"))
            {
                return ApiResult.Failed(str);
            }
            comment.Content = StringHelper.ToUnicodeString(comment.Content);

            #region 内容是否违规
            try
            {
                var miniModel = programModule.GetMiniProgramModule(new RB_MiniProgram_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });
                int violationNum = new MiniProgramMsgModule().CheckViolation(miniModel, StringHelper.FromUnicodeString(comment.Content));
                if (violationNum == 0)
                {
                    return ApiResult.Failed("评论内容检测失败，请稍后再试");
                }
                else if (violationNum == 1)
                {
                    var violationLogList = educationModule.GetViolationLogList(new RB_Education_ViolationLog { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, UserId = userInfo.UserId });
                    if (violationLogList != null && violationLogList.Any() && violationLogList.Count() >= 1)
                    {
                        userInfo = new AppletUserInfo
                        {
                            MallBaseId = uInfo.MallBaseId,
                            UserId = uInfo.UserId,
                            TenantId = uInfo.TenantId,
                            Name = uInfo.Name,
                            SuperiorId = uInfo.SuperiorId,
                            Blacklist = 1
                        };
                        CacheManager.User.UserReidsCache.AppletUserInfoSet(CacheKey.UserModuleCacheKeyConfig.Applet_Blacklist_Info + uInfo.UserId, userInfo, Config.JwtExpirTime);
                        educationModule.UpdateUserBlacklist(userInfo.TenantId, userInfo.MallBaseId, userInfo.UserId);


                    }
                    educationModule.SetEducationViolationLog(new RB_Education_ViolationLog { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, UserId = userInfo.UserId, ViolationType = 2, CreateDate = System.DateTime.Now });
                    return ApiResult.Failed("评论存在违规内容，若多次发布违规内容将被拉黑");
                }
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "GetDynamicComment");
                return ApiResult.Failed("评论内容检测失败，请稍后再试");
            }
            #endregion
            comment.Status = 0;
            comment.CreateTime = DateTime.Now;
            comment.UserId = userInfo.UserId;
            comment.TenantId = userInfo.TenantId;
            comment.MallBaseId = userInfo.MallBaseId;
            if (dynamicModule.DynamicCommemt(comment))
            {
                return ApiResult.Success("评论成功");
            }
            else
            {
                return ApiResult.Failed("评论失败");
            }

        }
        /// <summary>
        /// 动态评论删除
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDynamicDeleteComment()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parm = JObject.Parse(req.msg.ToString());
            int commentId = parm.GetInt("commentId");
            if (commentId == 0)
            {
                return ApiResult.Failed("评论id不为空");
            }
            if (dynamicModule.DynamicDeleteComment(new Rb_Education_DynamicComment_Extend { UserId = userInfo.UserId, Id = commentId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }))
            {
                return ApiResult.Success("删除成功");
            }
            else
            {
                return ApiResult.Failed("删除失败");
            }
        }

        /// <summary>
        /// 获取未读消息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDynamicMessageCount()
        {
            var userInfo = AppletUserInfo;
            int messageCount = 0;
            if (userInfo != null && userInfo.UserId > 0)
            {
                messageCount = dynamicModule.GetDynamicMessageCount(new Rb_Education_DynamicMessage { UserId = userInfo.UserId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });
            }
            return ApiResult.Success("", messageCount);
        }
        #endregion


        #region 活动


        /// <summary>
        /// 获取商会活动类型列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetActivityTypeList(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            JObject jObj = JObject.Parse(parms.msg.ToString());
            var query = new RB_Education_ActivityType_Extend()
            {
                TypeName = jObj.GetStringValue("TypeName")
            };
            query.MallBaseId = parms.MallBaseId;
            query.TenantId = parms.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>
        [HttpPost]

        public ApiResult GetActivityPage()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            //  var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            ResultPageModel pageModel = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            JObject jObj = JObject.Parse(req.msg.ToString());
            var query = new RB_Education_Activity_Extend()
            {
                SelectIsEnd = jObj.GetInt("SelectIsEnd", 0),
                ActivityName = jObj.GetStringValue("ActivityName"),
                ActivityType = jObj.GetInt("ActivityType", 0),
            };
            query.SelectStartTimeStr = System.DateTime.Now.ToString("yyyy-MM-dd");
            query.SelectEndTimeStr = System.DateTime.Now.AddDays(60).ToString("yyyy-MM-dd");
            query.OrderByStr = "StartTime";
            query.TenantId = userInfo.TenantId;
            query.MallBaseId = userInfo.MallBaseId;
            var list = activityModule.GetActivityPageListModule(pageModel.pageIndex, pageModel.pageSize, out long rowsCount, query, isQuerySignup: true);
            foreach (var item in list)
            {
                if (item.EducationConsultList != null && item.EducationConsultList.Any())
                {
                    item.IsJoinActivity = (item.EducationConsultList.Where(x => x.UserId == userInfo.UserId) != null && item.EducationConsultList.Where(x => x.UserId == userInfo.UserId).Any()) ? 1 : 0;
                }
            }
            pageModel.count = Convert.ToInt32(rowsCount);
            var result = list.Select(x => new
            {
                x.ActivityName,
                x.ManNum,
                x.WoManNum,
                TotalMan = x.Distinguish == 0 ? (x.WoManNum + x.ManNum) : x.ManNum,
                JoinNum = x.EducationConsultList.Count(),
                YearStr = x.StartTime.ToString("yyyy"),
                MonthStr = x.StartTime.ToString("MM"),
                DayStr = x.StartTime.ToString("dd"),
                WeekStr = StringHelper.GetWeek(x.StartTime),
                x.PointNum,
                x.Price,
                x.IsFree,
                BMStart = x.SignStartTime.HasValue ? x.SignStartTime.Value.ToString("MM/dd HH:mm") : "",
                BMEnd = x.SignEndTime.HasValue ? x.SignEndTime.Value.ToString("MM/dd HH:mm") : "",
                HDStart = x.StartTime.ToString("MM/dd HH:mm"),
                HDEnd = x.EndTime.ToString("MM/dd HH:mm"),
                x.Id,
                x.IsJoinActivity
            });
            pageModel.pageData = result;
            return ApiResult.Success(data: pageModel);
        }




        /// <summary>
        /// 获取商会活动分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]

        public ApiResult GetUserActivityList()
        {
            // var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            JObject jObj = JObject.Parse(req.msg.ToString());
            var query = new RB_Education_Activity_Extend()
            {
                ActivityName = jObj.GetStringValue("ActivityName"),
                ActivityType = jObj.GetInt("ActivityType", 0),
            };
            //  query.SelectStartTimeStr = System.DateTime.Now.ToString("yyyy-MM-dd");
            // query.SelectEndTimeStr = System.DateTime.Now.AddDays(60).ToString("yyyy-MM-dd");
            // query.OrderByStr = "StartTime";
            query.TenantId = userInfo.TenantId;
            query.MallBaseId = userInfo.MallBaseId;
            query.CreateBy = userInfo.UserId;
            var list = activityModule.GetUserActivityPageModule(pagelist.pageIndex, pagelist.pageSize, out long rowsCount, query);
            pagelist.count = Convert.ToInt32(rowsCount);
            var result = list.Select(x => new
            {
                x.ActivityName,
                x.ManNum,
                x.WoManNum,
                TotalMan = x.Distinguish == 0 ? (x.WoManNum + x.ManNum) : x.ManNum,
                JoinNum = 0,
                YearStr = x.StartTime.ToString("yyyy"),
                MonthStr = x.StartTime.ToString("MM"),
                DayStr = x.StartTime.ToString("dd"),
                WeekStr = StringHelper.GetWeek(x.StartTime),
                x.PointNum,
                x.Price,
                x.IsFree,
                BMStart = x.SignStartTime.HasValue ? x.SignStartTime.Value.ToString("MM/dd HH:mm") : "",
                BMEnd = x.SignEndTime.HasValue ? x.SignEndTime.Value.ToString("MM/dd HH:mm") : "",
                HDStart = x.StartTime.ToString("MM/dd HH:mm"),
                HDEnd = x.EndTime.ToString("MM/dd HH:mm"),
                x.Id,
            });
            pagelist.pageData = result;
            return ApiResult.Success(data: pagelist);
        }


        /// <summary>
        /// 活动详情
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetActivityDetial()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parm = JObject.Parse(req.msg.ToString());
            int Id = parm.GetInt("Id");
            if (Id == 0)
            {
                return ApiResult.Failed("活动id不为空");
            }
            RB_Education_Activity_Extend model = activityModule.GetActivityModule(Id);
            if (model != null)
            {
                model.EducationConsultList = new List<RB_Education_Consult_Extend>();
                model.EducationConsultList = activityModule.GetCommerceConsultListRepository_V2(new RB_Education_Consult_Extend { ActivityId = Id, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, EnrollState = 1, OrderStatus = 1 });

                var group = activityModule.GetActivitySummaryGroupList(new RB_Education_ActivitySummaryGroup_Extend { ActivityId = model.Id }).OrderByDescending(x => x.Type);
                var fileList = activityModule.GetActivitySummaryFileList(new RB_Education_ActivitySummaryFile_Extend { ActivityId = model.Id });
                foreach (var item in group)
                {
                    item.FileList = new List<RB_Education_ActivitySummaryFile_Extend>();
                    item.FileList = fileList.Where(x => x.GroupId == item.Id).ToList();
                }

                List<object> fileGroup = new List<object>();

                for (int i = 2; i >= 1; i--)
                {
                    List<object> fileObjectList = new List<object>();
                    foreach (var itemGroup in fileList.Where(x => x.Type == i).GroupBy(x => x.GroupId))
                    {
                        fileObjectList.Add(new
                        {
                            Name = group.Where(x => x.Id == itemGroup.Key).FirstOrDefault()?.Name ?? "默认",
                            Id = itemGroup.Key,
                            Type = i,
                            FileList = fileList.Where(x => x.GroupId == itemGroup.Key && x.Type == i).ToList()
                        });
                    }
                    fileGroup.Add(new
                    {
                        Key = i,
                        // groupList = group.Where(x => x.Type == item.Key).ToList(),
                        groupList = fileObjectList
                    });
                }
                model.ActivityTitleList = new List<RB_Education_ActivityTitle_Extend>();
                model.ActivityTitleList = activityModule.GetActivityTitleList(new RB_Education_ActivityTitle_Extend { ActivityId = model.Id, TenantId = model.TenantId, MallBaseId = model.MallBaseId });
                if (model.ActivityTitleList != null && model.ActivityTitleList.Any())
                {
                    var planList = activityModule.GetActivityPlanList(new RB_Education_ActivityPlan_Extend { ActivityId = model.Id, TenantId = model.TenantId, MallBaseId = model.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 model.ActivityTitleList)
                        {
                            item.ActivityPlanList = new List<RB_Education_ActivityPlan_Extend>();
                            item.ActivityPlanList = planList.Where(x => x.TitleId == item.Id).ToList();
                        }
                    }
                }
                var data = new
                {
                    model.ActivityName,
                    model.ManNum,
                    model.WoManNum,
                    model.ActivityInfo,
                    TotalMan = model.Distinguish == 0 ? (model.WoManNum + model.ManNum) : model.ManNum,
                    JoinNum = model.EducationConsultList.Count(),
                    YearStr = model.StartTime.ToString("yyyy"),
                    MonthStr = model.StartTime.ToString("MM"),
                    DayStr = model.StartTime.ToString("dd"),
                    WeekStr = StringHelper.GetWeek(model.StartTime),
                    model.PointNum,
                    model.Price,
                    model.IsFree,
                    BMStart = model.SignStartTime.HasValue ? model.SignStartTime.Value.ToString("MM/dd HH:mm") : "",
                    BMEnd = model.SignEndTime.HasValue ? model.SignEndTime.Value.ToString("MM/dd HH:mm") : "",
                    HDStart = model.StartTime.ToString("MM/dd HH:mm"),
                    HDEnd = model.EndTime.ToString("MM/dd HH:mm"),
                    model.Id,
                    model.ActivityStatus,
                    model.AgeLimit,
                    model.CoverImg,
                    model.Distinguish,
                    model.EndAge,
                    model.IsSignUp,
                    model.LnsideLimit,
                    model.LocationName,
                    model.LonLat,
                    model.StartAge,
                    IsJoinActivity = (model.EducationConsultList.Where(x => x.UserId == userInfo.UserId) != null && model.EducationConsultList.Where(x => x.UserId == userInfo.UserId).Any()) ? 1 : 0,
                    model.Summary,
                    FileGroup = fileGroup,
                    ActivityTitleList = (model.ActivityTitleList != null && model.ActivityTitleList.Any()) ? model.ActivityTitleList : new List<RB_Education_ActivityTitle_Extend>()
                };
                return ApiResult.Success(data: data);
            }
            else
            {
                return ApiResult.Failed("活动不存在");
            }
        }



        /// <summary>
        /// 取消报名
        /// </summary>
        /// <returns></returns>
        public ApiResult CancelCommerceConsult()
        {
            bool flag = false;
            JObject jObj = JObject.Parse(RequestParm.msg.ToString());
            var ActivityId = jObj.GetInt("ActivityId");
            var Id = jObj.GetInt("Id");
            string CancelRemark = jObj.GetStringValue("CancelRemark");
            var userInfo = AppletUserInfo;
            var model = activityModule.GetCommerceConsultListRepository(new RB_Education_Consult_Extend { UserId = userInfo.UserId, OrderStatus = 1, ActivityId = ActivityId, Id = Id, MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId }).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("已过报名时间无法取消");
            }
            if (model.IsCancelConfirm == 2 && 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.CancelCommerceConsultModule(ActivityId, CancelRemark, out int IsCancelConfirm, userInfo.UserId, refundid, model, dPaid);
                    return flag ? ApiResult.Success("", IsCancelConfirm) : ApiResult.Failed();
                }
                else
                {
                    ApiResult.Failed("取消报名失败，请联系客服");
                }
            }
            else
            {
                flag = activityModule.CancelCommerceConsultModule(ActivityId, CancelRemark, out int IsCancelConfirm, userInfo.UserId, "", model, 0);
                return flag ? ApiResult.Success("", IsCancelConfirm) : ApiResult.Failed();
            }
            return ApiResult.Failed("报名取消失败，请联系客服");

        }






        /// <summary>
        /// 获取活动报名列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserJoinActivityPageList()
        {
            ResultPageModel pageModel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_Education_Consult_Extend dmodel = JsonConvert.DeserializeObject<RB_Education_Consult_Extend>(RequestParm.msg.ToString());
            var userInfo = AppletUserInfo;
            dmodel.MallBaseId = RequestParm.MallBaseId;
            dmodel.TenantId = userInfo?.TenantId ?? 0;
            dmodel.UserId = userInfo.UserId;
            dmodel.OrderStatus = 1;
            var list = activityModule.GetUserJoinActivityPageList(pageModel.pageIndex, pageModel.pageSize, out long rowsCount, dmodel);
            pageModel.count = Convert.ToInt32(rowsCount);
            pageModel.pageData = list.Select(x => new
            {
                x.Id,
                x.ActivityId,
                x.UserId,
                x.LinkMan,
                x.LinkTel,
                CreateTime = x.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                x.Status,
                x.PeopleNum,
                x.Money,
                x.TotalPoint,
                x.Remark,
                x.IsApplyForCancel,
                x.CancelRemark,
                x.ApplyForCancelStatus,
                x.RejectRemark,
                x.ActivityName,
                x.CoverImg,
                StartTime = x.StartTime.HasValue ? x.StartTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                EndTime = x.EndTime.HasValue ? x.EndTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.TypeName
            });
            return ApiResult.Success(data: pageModel);
        }
        #endregion


        #region 绑定学员信息
        /// <summary>
        /// 激活账号发送短信验证码
        /// </summary>
        /// <param name="request">获取信息</param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SendCodeByStudentInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject jobj = JObject.Parse(req.msg.ToString());
            string stuTel = jobj.GetStringValue("StuTel");
            var model = activityModule.GetStudentList(new RB_Student()
            {
                StuTel = stuTel,
                School_Id = -1
            })?.FirstOrDefault();
            if (model == null)
            {
                return ApiResult.Failed("该账号不存在");
            }
            else if (model.IsDisable == 0)
            {
                return ApiResult.Failed(message: $"此账号已禁用");
            }

            string code = StringHelper.CreateRandomCode(4);

            try
            {
                bool canSendCode = UserReidsCache.CheckCanSendCode(stuTel, out string message);
                if (!canSendCode)
                {
                    return ApiResult.Failed(message);
                }
                MobileCodeTypeEnum mobileCodeType = MobileCodeTypeEnum.StudentMsg;//
                ThirdCore.Message.SMSService.SendCode(stuTel, code, EnumHelper.GetEnumName(mobileCodeType));
                UserReidsCache.SetSendCode(CacheKey.UserModuleCacheKeyConfig.User_Send_Code + stuTel, code, 600);
                UserReidsCache.AddUserSendCodeHistory(stuTel);
                return ApiResult.Success("验证码已发送，请注意查收", data: null);
            }
            catch (Exception ex)
            {
                return ApiResult.Failed("发送短信失败，请稍后再试");
            }
        }




        /// <summary>
        /// 判断输入的验证码是否正确
        /// </summary>
        /// <returns></returns>

        [HttpPost]
        public ApiResult CheckSendCode()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject jobj = JObject.Parse(req.msg.ToString());

            string StuTel = jobj.GetStringValue("StuTel");
            string sendcode = jobj.GetStringValue("Sendcode");
            if (string.IsNullOrWhiteSpace(sendcode))
            {
                return ApiResult.Failed("验证码不能为空");
            }
            else
            {
                object cacheCode = UserReidsCache.GetUserCode(CacheKey.UserModuleCacheKeyConfig.User_Send_Code + StuTel);
                if (cacheCode == null)
                {
                    return ApiResult.Failed("验证码已失效,请重新获取");
                }
                else
                {
                    if (!cacheCode.ToString().Equals(sendcode))
                    {
                        return ApiResult.Failed("验证码不正确，请填写正确的验证码");
                    }
                }
                var model = activityModule.GetStudentList(new RB_Student()
                {
                    StuTel = StuTel,
                    School_Id = -1
                })?.FirstOrDefault();
                if (model == null)
                {
                    return ApiResult.Failed("该账号不存在");
                }

                //判断改手机号码是否绑定其他了用户了
                var oldModel = activityModule.GetEducationBaseInfo(new RB_Education_BaseInfo_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, StudentId = model.StuId }).FirstOrDefault();
                if (oldModel != null && oldModel.UserId != userInfo.UserId)
                {
                    return ApiResult.Failed("手机号已绑定其他用户");
                }

                var eduModel = activityModule.GetEducationBaseInfo(new RB_Education_BaseInfo_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, UserId = userInfo.UserId }).FirstOrDefault();
                if (eduModel == null || eduModel.Id == 0)
                {
                    eduModel = new RB_Education_BaseInfo_Extend();
                    eduModel.Id = 0;
                    eduModel.TenantId = userInfo.TenantId;
                    eduModel.MallBaseId = userInfo.MallBaseId;
                    eduModel.Sex = 0;
                    eduModel.CreateDate = System.DateTime.Now;
                    eduModel.Status = 0;
                    eduModel.UserId = userInfo.UserId;
                }
                eduModel.Birthday = model.StuBirth.HasValue ? model.StuBirth.Value.ToString("yyyy-MM-dd") : "";
                eduModel.StudentId = model.StuId;
                eduModel.PhoneNum = StuTel;

                bool result = activityModule.SetEduBaseInfo(eduModel);
                if (result)
                {
                    UserReidsCache.SetSendCode(CacheKey.UserModuleCacheKeyConfig.User_Send_Code + StuTel, sendcode, 1);
                }
                return result ? ApiResult.Success("学员信息绑定成功") : ApiResult.Failed("学员信息绑定失败");
            }


        }




        #endregion



        #region 
        /// <summary>
        /// 获取代理的学校
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetEduSchool()
        {
            var userInfo = AppletUserInfo;
            Rb_Education_School_Extend demodel = new Rb_Education_School_Extend();
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            var list = educationModule.GetEducationSchoolList(demodel);
            return ApiResult.Success("", list.Select(x => new { x.Id, x.CoverPhoto, x.ShoolName }));
        }

        #endregion



        #region 绑定销售
        /// <summary>
        /// 绑定甲鹤销售
        /// </summary>
        /// <returns></returns>

        [HttpPost]
        public ApiResult GetBindEduSell()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject jobj = JObject.Parse(req.msg.ToString());

            string eduSellAccount = jobj.GetStringValue("EduSellAccount");
            string password = jobj.GetStringValue("password");
            if (string.IsNullOrWhiteSpace(eduSellAccount) || string.IsNullOrWhiteSpace(password))
            {
                return ApiResult.Failed("账户或密码不能为空");
            }
            var model = activityModule.GetEmployeeListModule(new Employee_ViewModel()
            {
                Account = eduSellAccount,
                School_Id = -1
            })?.FirstOrDefault();
            if (model == null)
            {
                return ApiResult.Failed("该账号不存在");
            }

            password = Common.DES.Encrypt(password);
            if (model.Password != password)
            {
                return ApiResult.Failed("密码错误");
            }

            //判断改手机号码是否绑定其他了用户了
            var eduModel = activityModule.GetEducationSellBaseInfo(new RB_Education_EduSell_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, EduSellId = model.Id }).FirstOrDefault();
            if (eduModel != null && eduModel.UserId != userInfo.UserId)
            {
                return ApiResult.Failed("账户已绑定其他用户");
            }

            //  var eduModel = activityModule.GetEducationSellBaseInfo(new RB_Education_EduSell_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, UserId = userInfo.UserId }).FirstOrDefault();
            if (eduModel == null || eduModel.Id == 0)
            {
                eduModel = new RB_Education_EduSell_Extend();
                eduModel.Id = 0;
                eduModel.TenantId = userInfo.TenantId;
                eduModel.MallBaseId = userInfo.MallBaseId;
                eduModel.CreateDate = System.DateTime.Now;
                eduModel.Status = 0;
                eduModel.UserId = userInfo.UserId;
            }
            eduModel.EduSellId = model.Id;
            bool result = activityModule.SetEduSellBaseInfo(eduModel);

            return result ? ApiResult.Success("销售信息绑定成功") : ApiResult.Failed("销售信息绑定失败");

        }


        /// <summary>
        /// 获取用户绑定的甲鹤销售
        /// </summary>
        /// <returns></returns>

        [HttpPost]
        public ApiResult GetBindEduSellInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;

            var eduModel = activityModule.GetEducationSellBaseInfo(new RB_Education_EduSell_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, UserId = userInfo.UserId }).FirstOrDefault();
            if (eduModel == null || eduModel.Id == 0)
            {
                eduModel = new RB_Education_EduSell_Extend();
            }

            return ApiResult.Success("", new
            {
                eduModel.Id,
                EmpId = eduModel.employeeModel?.Id ?? 0,
                EmployeeName = eduModel.employeeModel?.EmployeeName ?? "",
                UserIcon = eduModel.employeeModel?.UserIcon ?? "",
                PostName = eduModel.employeeModel?.PostName ?? "",
                DeptName = eduModel.employeeModel?.DeptName ?? "",
            });
        }
        #endregion
    }
}