using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Mall.Module.Education;
using Mall.Common.API;
using Newtonsoft.Json;
using Mall.Model.Extend.Education;
using System;
using System.Linq;
using Mall.Model.Extend.Product;
using Mall.Module.Product;
using Mall.Model.Extend.User;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using Mall.Common.Plugin;
using Google.Protobuf.WellKnownTypes;
using Mall.Model.Entity.Education;

namespace Mall.WebApi.Controllers.Education
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class AppletSchoolController : ControllerBase
    {
        private readonly EducationModule educationModule = new EducationModule();
        private readonly ProductModule productModule = new ProductModule();
        private Module.User.UserModule UserModule = new Module.User.UserModule();
        private readonly DynamicModule dynamicModule = new DynamicModule();
        #region 课程

        /// <summary>
        /// 小程序课程分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletCoursePageList(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            if (parms.MallBaseId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Extend>(parms.msg.ToString());
            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            demodel.GoodsStatus = 1;//只查询销售中的
            demodel.SmallShopsId = parms.SmallShopsId;
            int UserId = parms.UserId;
            demodel.UserId = UserId;
            RB_Member_User_Extend userModel = new RB_Member_User_Extend();
            RB_Member_Grade_Extend memberGrade = new RB_Member_Grade_Extend();
            if (UserId > 0)
            {
                userModel = productModule.GetMemberUserInfo(UserId);
                if (userModel.MemberGrade > 0)
                {
                    memberGrade = productModule.GetMemberGradeList(new RB_Member_Grade_Extend() { Id = userModel.MemberGrade ?? 0, Enabled = 1, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
                }
                if (demodel.SmallShopsId == 0)
                {
                    demodel.SmallShopsId = userModel.SmallShopId;
                }
            }
            var list = productModule.GetAppletCoursePageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            List<object> RList = new List<object>();
            if (list.Any())
            {
                foreach (var model in list)
                {
                    #region 组装价格
                    decimal price_member = model.SellingPrice ?? 0;//未设会员价格的话  就为销售价格
                    if (model.EnjoyMember == 1 && model.SeparateSetMember == 1)
                    {
                        if (model.MemberPriceList.Any())
                        {
                            var mlist = model.MemberPriceList;
                            if (UserId > 0 && userModel.MemberGrade > 0)
                            {
                                var gmodel = mlist.Where(x => x.MemberGrade == userModel.MemberGrade).FirstOrDefault();
                                price_member = gmodel.MemberPrice ?? 0;
                            }
                        }
                    }
                    else
                    {
                        if (UserId > 0 && userModel.MemberGrade > 0)
                        {
                            price_member = Math.Round((model.SellingPrice ?? 0) * (memberGrade?.Discount ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                        }
                    }
                    #endregion

                    #region 会员价格
                    decimal memberprice = model.SellingPrice ?? 0;
                    if (UserId > 0 && userModel.MemberGrade > 0 && model.EnjoyMember == 1 && model.SeparateSetMember == 1 && model.MemberPriceList.Any())
                    {
                        memberprice = model.MemberPriceList.Where(x => x.MemberGrade == userModel.MemberGrade).Min(x => x.MemberPrice ?? 0);
                    }
                    else if (UserId > 0 && userModel.MemberGrade > 0)
                    {
                        memberprice = memberprice * (memberGrade?.Discount ?? 10) / 10;
                    }
                    #endregion

                    RList.Add(new
                    {
                        id = model.Id,
                        name = model.Name,
                        cover_pic = model.CoverImage,
                        video_url = model.VideoAddress,
                        original_price = model.OriginalPrice,
                        unit = model.Unit,
                        page_url = "/pages/goods/goods?id=" + model.Id,
                        is_level = model.EnjoyMember,
                        level_price = memberprice,
                        price = (model.SellingPrice ?? 0).ToString("#0.00"),
                        price_content = "￥" + (model.SellingPrice ?? 0).ToString("#0.00"),
                        sales = "已售" + model.SalesNum + "件",
                        marketingLogo = model.MarketingLogo,
                        video_type = model.VideoType,
                        course_score = model.CourseScore,
                        is_pay = model.IsPay,
                    });
                }
            }

            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = RList;
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取小程序课程详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletGoodsInfo(object requestMsg)
        {
            var req = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            if (req.MallBaseId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            JObject prams = JObject.Parse(req.msg.ToString());
            int GoodsId = prams.GetInt("GoodsId", 0);
            if (GoodsId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            int UserId = req.UserId;

            var Robj = productModule.GetAppletCourseInfo(GoodsId, UserId, req.SmallShopsId, req.TenantId, req.MallBaseId);
            return ApiResult.Success("", Robj);
        }

        /// <summary>
        /// 获取课程是否收藏
        /// </summary>
        /// <param name="requestMsg"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletCourseCollect(object requestMsg)
        {
            var req = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            if (req.MallBaseId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            JObject prams = JObject.Parse(req.msg.ToString());
            int GoodsId = prams.GetInt("GoodsId", 0);
            if (GoodsId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            int UserId = req.UserId;

            var Robj = productModule.GetAppletCourseCollect(GoodsId, UserId, req.TenantId, req.MallBaseId);
            return ApiResult.Success("", Robj);
        }

        /// <summary>
        /// 获取小程序课程章节列表
        /// </summary>
        /// <param name="requestMsg"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletGoodsCourseList(object requestMsg)
        {
            var req = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            if (req.MallBaseId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            JObject prams = JObject.Parse(req.msg.ToString());
            int GoodsId = prams.GetInt("GoodsId", 0);
            if (GoodsId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            var list = productModule.GetAppletGoodsCourseList(pagelist.pageIndex, pagelist.pageSize, out long count, GoodsId, req.UserId, req.TenantId, req.MallBaseId);

            int IsPay = productModule.GetAppletCourseIsPay(GoodsId, req.UserId);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Sort,
                x.SortName,
                x.Name,
                x.Type,
                TypeName = x.Type.GetEnumName(),
                x.IsTrySee,
                x.Number,
                x.IsCache,
                FilePath = x.IsTrySee == 1 || IsPay == 1 ? x.FilePath : "",
                x.IsImageOK,
                x.VideoImage,
                x.VideoTime,
                IsPay,
                x.IsRead,
                ImageList = GetCourseImage(x.IsTrySee ?? 0, IsPay, x.Number ?? 0, x.Image)
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取课程图片
        /// </summary>
        /// <param name="IsTrySee"></param>
        /// <param name="IsPay"></param>
        /// <param name="Number"></param>
        /// <param name="Image"></param>
        /// <returns></returns>
        public List<CourseImageModel> GetCourseImage(int IsTrySee, int IsPay, int Number, string Image)
        {
            if (string.IsNullOrEmpty(Image) || Image == "[]")
            {
                return new List<CourseImageModel>();
            }
            if (IsPay == 1)
            {
                return JsonConvert.DeserializeObject<List<CourseImageModel>>(Image);
            }
            if (IsTrySee == 1)
            {
                var list = JsonConvert.DeserializeObject<List<CourseImageModel>>(Image);
                if (Number > 0)
                {
                    list = list.Take(Number).ToList();
                }
                return list;
            }
            return new List<CourseImageModel>();
        }

        #endregion

        #region 资讯
        /// <summary>
        /// 小程序分页列表(赞羊)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetArticlePageList(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            if (parms.MallBaseId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Education_Article_Extend demodel = JsonConvert.DeserializeObject<RB_Education_Article_Extend>(parms.msg.ToString());

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            demodel.ArticleStatus = 1;//只查询销售中的
            var list = educationModule.GetArticlePageListRepository(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            foreach (var item in list)
            {
                if (!string.IsNullOrWhiteSpace(item.LableName))
                {
                    item.LableNameList = JsonConvert.DeserializeObject<List<string>>(item.LableName);
                }
            }
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ID,
                x.Name,
                CreateDateStr = x.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                x.ArticleStatus,
                x.IsComment,
                x.CommentNum,
                x.BrowseNum,
                x.FictitiousBrowseNum,
                x.ArticlePic,
                x.TeacherName,
                x.TeacherLogo,
                x.Major
            });
            return ApiResult.Success("", pagelist);
        }



        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        public ApiResult GetArticleModel(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            if (parms.MallBaseId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            var query = JsonConvert.DeserializeObject<RB_Education_Article_Extend>(parms.msg.ToString());
            query.TenantId = parms.TenantId;
            query.MallBaseId = parms.MallBaseId;
            query.ArticleStatus = 1;
            var oldLogisticsModel = educationModule.GetArticleInfo(query);
            if (oldLogisticsModel == null)
            {
                oldLogisticsModel = new RB_Education_Article_Extend();
            }
            if (!string.IsNullOrWhiteSpace(oldLogisticsModel.LableName))
            {
                oldLogisticsModel.LableNameList = JsonConvert.DeserializeObject<List<string>>(oldLogisticsModel.LableName);
            }
            //更新浏览数
            try
            {
                if (oldLogisticsModel.ID > 0)
                {
                    educationModule.UpdateArticleBrowseNum(oldLogisticsModel);
                }

            }
            catch (Exception ex)
            {


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



        /// <summary>
        /// 获取资讯留言分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetArticleCommentPageList(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Education_ArticleComment_Extend demodel = JsonConvert.DeserializeObject<RB_Education_ArticleComment_Extend>(parms.msg.ToString());
            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = educationModule.GetArticleCommentPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ID,
                x.UserId,
                x.UserName,
                x.UserPhotoPath,
                x.ArticleId,
                x.ArticleName,
                x.CommentScore,
                x.CommentGrade,
                CommentGradeName = x.CommentGrade.GetEnumName(),
                x.CommentImgList,
                x.Content,
                x.Reply,
                x.Is_Top,
                x.Is_Show,
                x.Is_Anonymity,
                x.PlatformSource,
                x.TenantId,
                x.MallBaseId,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
            });
            return ApiResult.Success("", pagelist);
        }


        #endregion

        #region 教师

        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetTeacherModel(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            var query = JsonConvert.DeserializeObject<RB_Education_Teacher_Extend>(parms.msg.ToString());
            query.TenantId = parms.TenantId;
            query.MallBaseId = parms.MallBaseId;
            query.TeacherStatus = 1;
            var oldLogisticsModel = educationModule.GetTeacherModel(new RB_Education_Teacher_Extend { ID = query.ID, TenantId = parms.TenantId, MallBaseId = parms.MallBaseId, TeacherStatus = 1 });
            if (oldLogisticsModel == null)
            {
                oldLogisticsModel = new RB_Education_Teacher_Extend();
            }
            if (!string.IsNullOrWhiteSpace(oldLogisticsModel.LableName))
            {
                oldLogisticsModel.LableNameList = JsonConvert.DeserializeObject<List<string>>(oldLogisticsModel.LableName);
            }
            else
            {
                oldLogisticsModel.LableNameList = new List<string>();
            }
            if (!string.IsNullOrWhiteSpace(oldLogisticsModel.GoodCourse))
            {
                oldLogisticsModel.GoodCourseList = JsonConvert.DeserializeObject<List<string>>(oldLogisticsModel.GoodCourse);
            }
            else
            {
                oldLogisticsModel.GoodCourseList = new List<string>();
            }
            //获取老师的关注数
            //判断是否已经关注过
            var oldList = educationModule.GetFollowTeacherList(new RB_Education_FollowTeacher_Extend { TeacherId = query.ID, MallBaseId = query.MallBaseId, TenantId = query.TenantId });
            oldLogisticsModel.FollowteacherNum = oldList.Count();

            int Followteacher = 0;
            int DynamicStatus = 0;//登录查看更多
            if (query.UserId > 0)
            {
                Followteacher = (oldList != null && oldList.Any()) ? oldList.Where(x => x.UserId == query.UserId).FirstOrDefault()?.ID ?? 0 : 0;
            }
            List<Rb_Education_Dynamic_Extend> myArticleList = new List<Rb_Education_Dynamic_Extend>();
            if (Followteacher > 0)//关注了
            {
                DynamicStatus = 1;//关注了
                myArticleList = dynamicModule.MyDynamicList(1, 3, out long dynammicCount, new Rb_Education_Dynamic_Extend { UserId = query.UserId, TenantId = oldLogisticsModel.TenantId, MallBaseId = oldLogisticsModel.MallBaseId, UserTeacher = query.ID });
            }
            else if (query.UserId > 0)
            {
                //没有关注的情况下
                var openList = dynamicModule.MyDynamicList(1, 3, out long dynammicCount, new Rb_Education_Dynamic_Extend { IsOpen = 1, UserId = query.UserId, TenantId = oldLogisticsModel.TenantId, MallBaseId = oldLogisticsModel.MallBaseId, UserTeacher = query.ID });
                var followList = dynamicModule.MyDynamicList(1, 3, out long dynammicOpenCount, new Rb_Education_Dynamic_Extend { IsOpen = 2, UserId = query.UserId, TenantId = oldLogisticsModel.TenantId, MallBaseId = oldLogisticsModel.MallBaseId, UserTeacher = query.ID });
                if ((openList == null || !openList.Any()) && (followList == null || !followList.Any()))
                {
                    DynamicStatus = 2;//暂无动态
                }
                else if ((openList != null && openList.Any()) && (followList == null || !followList.Any()))
                {
                    myArticleList = openList;
                    DynamicStatus = 3;//查看更多
                }
                else
                {
                    myArticleList = openList;
                    DynamicStatus = 4;//关注查看更多
                }
            }
            List<object> list = new List<object>();
            foreach (var item in myArticleList)
            {
                list.Add(DecoratorDynameicResult(item));
            }
            //获取老师对应的课程
            var goodsList = educationModule.GetListByTeacherId(1, 4, out long count, new RB_Goods_Extend { TeacherId = oldLogisticsModel.ID, TenantId = oldLogisticsModel.TenantId, MallBaseId = oldLogisticsModel.MallBaseId });
            var goodsResult = goodsList.Select(x => new
            {
                x.CoverImage,
                x.Name,
                x.CourseNum,
                x.Id
            });


            var teacherResult = new
            {
                oldLogisticsModel?.WorkYears,
                oldLogisticsModel?.Major,
                oldLogisticsModel?.LableNameList,
                oldLogisticsModel.GoodCourseList,
                oldLogisticsModel?.Name,
                oldLogisticsModel?.TeacherLogo,
                oldLogisticsModel?.Introduction,
                oldLogisticsModel.FollowteacherNum,
                Followteacher,//是否关注该老师，0-没有，1-已关注
                DynamicStatus,
                DynamicList = list
            };
            return ApiResult.Success("", new { teacherResult, goodsResult });
        }



        /// <summary>
        /// 小程序分页列表(赞羊)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetTeacherGoodsList(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            if (parms.MallBaseId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Extend>(parms.msg.ToString());

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            if (demodel.TeacherId <= 0)
            {
                return ApiResult.Failed("老师编号不能为0");
            }
            var list = educationModule.GetListByTeacherId(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.CoverImage,
                x.Name,
                x.CourseNum,
                x.Id
            });
            return ApiResult.Success("", pagelist);
        }


        #endregion


        #region 启动页
        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetEducationStartUpModel(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            //var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Education_StartUp>(parms.msg.ToString());
            query.TenantId = parms.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var oldLogisticsModel = educationModule.GetEducationStartUpListRepository(query).FirstOrDefault();
            if (oldLogisticsModel == null)
            {
                oldLogisticsModel = new RB_Education_StartUp();
            }
            return ApiResult.Success("", oldLogisticsModel);
        }
        #endregion

        #region 老师动态
        /// <summary>
        /// 老师动态列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDynamicList(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            Rb_Education_Dynamic_Extend demodel = JsonConvert.DeserializeObject<Rb_Education_Dynamic_Extend>(parms.msg.ToString());
            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            List<Rb_Education_Dynamic_Extend> myArticleList = dynamicModule.DynamicList(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="article">动态内容</param>
        /// <returns></returns>
        [HttpPost]
        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;
        }

        #endregion


    }
}