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;

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();

        #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(query);
            if (oldLogisticsModel == null)
            {
                oldLogisticsModel = new RB_Education_Teacher_Extend();
            }
            if (!string.IsNullOrWhiteSpace(oldLogisticsModel.LableName))
            {
                oldLogisticsModel.LableNameList = JsonConvert.DeserializeObject<List<string>>(oldLogisticsModel.LableName);
            }
            //获取老师的关注数
            //判断是否已经关注过
            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;
            if (query.UserId > 0)
            {

                Followteacher = (oldList != null && oldList.Any()) ? oldList.Where(x => x.UserId == query.UserId).FirstOrDefault()?.ID ?? 0 : 0;
            }

            //获取老师对应的课程
            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?.Name,
                oldLogisticsModel?.TeacherLogo,
                oldLogisticsModel?.Introduction,
                oldLogisticsModel.FollowteacherNum,
                Followteacher//是否关注该老师，0-没有，1-已关注
            };
            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
    }
}