using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Mall.CacheManager.User;
using Mall.Common.API;
using Mall.Common.Plugin;
using Mall.Model.Extend.Point;
using Mall.Module.Education;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Mall.WebApi.Controllers.Education
{

    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class PointController : BaseController
    {

        private readonly PointModule pointModule = new PointModule();

        #region 点数商品
        [HttpPost]
        public ApiResult GetPointGoodsPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_Point_Goods_Extend demodel = JsonConvert.DeserializeObject<RB_Point_Goods_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            //demodel.TeacherStatus = -1;
            var list = pointModule.GetPointGoodsPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ID,
                x.GivePoint,
                x.GoodsName,
                x.PonitNum,
                x.SellingPrice,
                IsGive = (x.GivePoint > 0) ? 1 : 0
            });
            return ApiResult.Success("", pagelist);
        }


        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetPointGoodsModel()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Point_Goods_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var oldPointGoodsModel = pointModule.GetPointGoodsList(query).FirstOrDefault();
            if (oldPointGoodsModel == null)
            {
                oldPointGoodsModel = new RB_Point_Goods_Extend();
            }
            return ApiResult.Success("", oldPointGoodsModel);
        }


        /// <summary>
        /// 保存点数产品信息
        /// </summary>
        /// <returns></returns>
        public ApiResult SetPointGoods()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Point_Goods_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            if (query == null)
            {
                return ApiResult.Failed("请传入点数产品信息");
            }
            else
            {
                if (string.IsNullOrWhiteSpace(query.GoodsName))
                {
                    return ApiResult.Failed("请输入产品名称");
                }
                if (query.PonitNum == 0)
                {
                    return ApiResult.Failed("请输入点数");
                }
                if (query.SellingPrice == 0)
                {
                    return ApiResult.Failed("请输入价格");
                }
                if (query.ID == 0)
                {
                    query.CreateDate = System.DateTime.Now;

                }
                query.OriginalPrice = 0;
                query.CostPrice = 0;
                query.Sort = 0;
                query.State = 0;
                query.UpdateDate = System.DateTime.Now;
                bool result = pointModule.SetPointGoods(query);
                if (result)
                {
                    return ApiResult.Success("点数产品信息保存成功");
                }
                else
                {
                    return ApiResult.Failed("点数产品信息保存失败");
                }
            }
        }



        /// <summary>
        /// 删除点数产品
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DeletePointGoods()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            int Id = parmsJob.GetInt("Id", 0);

            if (Id == 0)
            {
                return ApiResult.Failed("请选择您要删除的点数信息");
            }
            bool flag = pointModule.DeletePointGoods(new RB_Point_Goods_Extend { ID = Id, TenantId = UserInfo.TenantId, MallBaseId = parms.MallBaseId });
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        #endregion


        #region 个人中心-点数记录

        /// <summary>
        /// 小程序获取点数记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletUserPointDetailPageList() {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_Member_PointBalance_Extend demodel = JsonConvert.DeserializeObject<RB_Member_PointBalance_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            var list = pointModule.GetUserPointDetailPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            int PointNum = pointModule.GetUserPointBalance(userInfo.UserId);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = new
            {
                PointNum,
                List = list.Select(x => new
                {
                    x.Id,
                    x.Type,
                    TypeName = x.Type.GetEnumName(),
                    x.Description,
                    x.PonitNum,
                    x.Remarks,
                    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 GetUserPointDetailPageList()
        {
            var parms = RequestParm;
            var userInfo = UserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_Member_PointBalance_Extend demodel = JsonConvert.DeserializeObject<RB_Member_PointBalance_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            var list = pointModule.GetUserPointDetailPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            list.ForEach(x =>
            {
                var umodel = UserReidsCache.GetAppletUserLoginInfo(x.UserId);
                x.UserName = umodel?.Name ?? "";
                x.UserPhoto = umodel?.Photo ?? "";
            });
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Type,
                TypeName = x.Type.GetEnumName(),
                x.Description,
                x.PonitNum,
                x.Remarks,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.UserId,
                x.UserName,
                x.UserPhoto
            });
            return ApiResult.Success("", pagelist);
        }
        #endregion

        #region 在线课程分类
        /// <summary>
        /// 课程分类
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetPointCourseClassPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_Point_CourseClass_Extend demodel = JsonConvert.DeserializeObject<RB_Point_CourseClass_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            //demodel.TeacherStatus = -1;
            var list = pointModule.GetPointCourseClassPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ID,
                x.IsFree,
                x.CourseClassType,
                CourseClassName = EnumHelper.GetEnumName(x.CourseClassType),
                x.Duration,
                x.DurationUnit,
                x.StudentNumType,
                StudentNumTypeStr = EnumHelper.GetEnumName(x.StudentNumType),
                DurationUnitStr = EnumHelper.GetEnumName(x.DurationUnit),
                x.PointNum,
                x.IsPublic
            });
            return ApiResult.Success("", pagelist);
        }


        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetPointCourseClassModel()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Point_CourseClass_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var oldPointGoodsModel = pointModule.GetPointCourseClassList(query).FirstOrDefault();
            if (oldPointGoodsModel == null)
            {
                oldPointGoodsModel = new RB_Point_CourseClass_Extend();
            }
            else {
                oldPointGoodsModel.ClassName = EnumHelper.GetEnumName(oldPointGoodsModel.CourseClassType);
                oldPointGoodsModel.StudentNumTypeName = EnumHelper.GetEnumName(oldPointGoodsModel.StudentNumType);
                oldPointGoodsModel.DurationUnitName = EnumHelper.GetEnumName(oldPointGoodsModel.DurationUnit);
            }
            return ApiResult.Success("", oldPointGoodsModel);
        }


        /// <summary>
        /// 保存课程分类信息
        /// </summary>
        /// <returns></returns>
        public ApiResult SetPointCourseClass()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Point_CourseClass_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            if (query == null)
            {
                return ApiResult.Failed("请传入课程分类信息");
            }
            else
            {
                if (query.ID == 0)
                {
                    query.CreateDate = System.DateTime.Now;
                }
                if (query.CourseClassType == 0)
                {
                    return ApiResult.Failed("请选择课程分类类型");
                }
                if (query.StudentNumType == 0)
                {
                    return ApiResult.Failed("请选择上课人数");
                }
                if (query.IsFree == 0)
                {
                    if (query.PointNum == 0)
                    {
                        return ApiResult.Failed("课程分类不免费，请填入点数");
                    }
                }
                if (query.Duration == 0)
                {
                    return ApiResult.Failed("请输入时长");
                }
                query.Sort = 0;
                query.State = 0;
                query.UpdateDate = System.DateTime.Now;
                bool result = pointModule.SetPointCourseClass(query);
                if (result)
                {
                    return ApiResult.Success("课程分类信息保存成功");
                }
                else
                {
                    return ApiResult.Failed("课程分类信息保存失败");
                }
            }
        }



        /// <summary>
        /// 删除课程分类
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DeletePointCourseClass()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            int Id = parmsJob.GetInt("Id", 0);

            if (Id == 0)
            {
                return ApiResult.Failed("请选择您要删除的课程分类信息");
            }
            bool flag = pointModule.DeletePointCourseClass(new RB_Point_CourseClass_Extend { ID = Id, TenantId = UserInfo.TenantId, MallBaseId = parms.MallBaseId });
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }



        /// <summary>
        /// 获取课程分类枚举
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCourseClassTypeEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(Common.Enum.Point.CourseClassTypeEnum));
            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 GetDurationUnitEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(Common.Enum.Point.DurationUnitEnum));
            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 GetStudentNumTypeEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(Common.Enum.Point.StudentNumTypeEnum));
            return ApiResult.Success("", list.OrderBy(x => Convert.ToInt32(x.Value)).Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }
        #endregion
    }
}
