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;

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();
        #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.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.TotalNum == -1 ? 0 : ((x.TotalNum - x.MemberNum > 0 ? 0 : 1)),  //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.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, "", "");
            }
        }
        #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
    }
}