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

namespace Mall.WebApi.Controllers.Education
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class AppletEducationController : BaseController
    {
        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();
        #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, 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, 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
    }
}