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;

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 = educationModule.GetAppletCoursePageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            List<object> RList = new List<object>();
            if (list.Any())
            {
                foreach (var model in list)
                {
                    #region 组装价格
                    List<object> priceList = new List<object>();

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


                    priceList.Add(new
                    {
                        id = 0,
                        goods_id = model.Id,
                        sign_id = "",
                        stock = model.InventoryNum,
                        price = model.SellingPrice ?? 0,
                        no = model.GoodsNumbers,
                        weight = model.GoodsWeight,
                        pic_url = "",
                        is_delete = 0,
                        attr_list = new
                        {
                            attr_group_name = "规格",
                            attr_group_id = 0,
                            attr_id = 0,
                            attr_name = model.DefaultSpecificationName
                        },
                        price_member
                    });

                    #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,
                        sign = "",
                        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_negotiable = model.IsGoodsNegotiable,
                        is_level = model.EnjoyMember,
                        level_price = memberprice,
                        price = (model.SellingPrice ?? 0).ToString("#0.00"),
                        price_content = "￥" + (model.SellingPrice ?? 0).ToString("#0.00"),
                        is_sales = model.GoodsStatus,
                        sales = "已售" + model.SalesNum + "件",
                        freeShippingName = model.FreeShippingModel.Name,
                        freeShippingFullMoneyPinkage = model.FreeShippingModel.FullMoneyPinkage ?? 0,
                        freeShippingFullNumPinkage = model.FreeShippingModel.FullNumPinkage ?? 0,
                        attr_groups = model.SpecificationList.Select(x => new
                        {
                            attr_group_id = x.Sort,
                            attr_group_name = x.Name,
                            attr_list = x.SpecificationValueList.Select(z => new
                            {
                                attr_id = z.Sort,
                                attr_name = z.Name,
                                pic_url = z.ImagePath
                            })
                        }),
                        attr = priceList,
                        goods_stock = model.InventoryNum,
                        goods_num = model.InventoryNum,
                        marketingLogo = model.MarketingLogo,
                        video_type = model.VideoType,
                        erpgoodobj = model.ERPGoodObj
                    });
                }
            }

            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.GetAppletGoodsInfo_V2(GoodsId, UserId, req.SmallShopsId, req.TenantId, req.MallBaseId);
            return ApiResult.Success("", Robj);
        }

        #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);
            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();
            }
            //更新浏览数
            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.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 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
            });
            var teacherResult = new {
                oldLogisticsModel?.WorkYears,
                oldLogisticsModel?.Major,
                oldLogisticsModel?.LableNameList,
                oldLogisticsModel?.Name,
                oldLogisticsModel?.TeacherLogo,
                oldLogisticsModel?.Introduction

            };
            return ApiResult.Success("", new { teacherResult, goodsResult });
        }

        #endregion
    }
}