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;

namespace Mall.WebApi.Controllers.Education
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class AppletEducationController : BaseController
    {
        private readonly EducationModule educationModule = new EducationModule();
        private Module.User.UserModule UserModule = new Module.User.UserModule();
        private Module.Product.ProductModule productModule = new Module.Product.ProductModule();
        private readonly Module.User.MiniProgramModule programModule = new Module.User.MiniProgramModule();
        #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 parms = RequestParm;
            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();
                memberCoupon.Id = 0;
                memberCoupon.UserId = userInfo.UserId;
                memberCoupon.Description = oldLogisticsModel.Describe;
                memberCoupon.CreateDate = System.DateTime.Now;
                memberCoupon.TenantId = userInfo.TenantId;
                memberCoupon.MallBaseId = userInfo.MallBaseId;
                memberCoupon.Remarks = "";
                memberCoupon.CouponId = oldLogisticsModel.ID;
                memberCoupon.Name = oldLogisticsModel.Name;
                memberCoupon.HeXiao = oldLogisticsModel.HeXiao;
                memberCoupon.UseHeXiao = 0;
                memberCoupon.UseType = oldLogisticsModel.UseType;
                if (oldLogisticsModel.IndateType == Common.Enum.MarketingCenter.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>();
                memberList.Add(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 parms = RequestParm;
            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 = new RB_Education_Coupon_Extend();
            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);//秒
            int CourseId = parms.GetInt("CourseId", 0);//课程id
            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);
        }

        #endregion

        #region 资讯留言

        /// <summary>
        /// 管理新增评论
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetArticleCommentInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            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("资讯不允许留言");
            }

            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,
                CreateDate = x.CreateDate.ToString("yyyy-MM-dd HH:ss:mm"),

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



        /// <summary>
        /// 关注老师
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult FollowTeacher()
        {
            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
            {
                if (query.ID == 0)
                {
                    isUpdate = false;
                    query.CreateDate = System.DateTime.Now;
                    query.UpdateDate = System.DateTime.Now;
                    if (query.TeacherId <= 0)
                    {
                        return ApiResult.Failed("请传入我关注的老师信息");
                    }
                    //判断是否已经关注过
                    var oldList = educationModule.GetFollowTeacherList(new RB_Education_FollowTeacher_Extend { UserId = query.UserId, TeacherId = query.TeacherId, MallBaseId = query.MallBaseId, TenantId = query.TenantId });
                    if (oldList != null && oldList.Any())
                    {
                        return ApiResult.Failed("您已关注，请勿重复操作");
                    }
                }


                bool result = educationModule.AddOrUpdateFollowTeacher(query);
                if (isUpdate)
                {
                    if (result)
                    {
                        return ApiResult.Success("取消关注成功");
                    }
                    else
                    {
                        return ApiResult.Failed("取消关注成功");
                    }
                }
                else
                {

                    if (result)
                    {
                        return ApiResult.Success("关注成功");
                    }
                    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


    }
}