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>
        [HttpPost]
        public ApiResult GetPointCourseClassList()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Point_CourseClass_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var oldPointGoodsList = pointModule.GetPointCourseClassList(query);
            oldPointGoodsList.ForEach(x => x.ClassName = EnumHelper.GetEnumName(x.CourseClassType));
            oldPointGoodsList.ForEach(x => x.StudentNumTypeName = EnumHelper.GetEnumName(x.StudentNumType));
            oldPointGoodsList.ForEach(x => x.DurationUnitName = EnumHelper.GetEnumName(x.DurationUnit));

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


        /// <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



        #region 老师排课

        [HttpPost]
        public ApiResult GetTeacherCourseList()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Point_TeacherCourse_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            if (string.IsNullOrWhiteSpace(query.SelectStartTime) || string.IsNullOrWhiteSpace(query.SelectEndTime))
            {
                return ApiResult.Failed("请传入查询时间范围");
            }
            var oldPointGoodsList = pointModule.GetTeacherCourseList(query);

            if (oldPointGoodsList != null && oldPointGoodsList.Any())
            {
                oldPointGoodsList.ForEach(x => x.ClassName = EnumHelper.GetEnumName(x.CourseClassType));
                oldPointGoodsList.ForEach(x => x.StudentNumTypeName = EnumHelper.GetEnumName(x.StudentNumType));
                oldPointGoodsList.ForEach(x => x.DurationUnitName = EnumHelper.GetEnumName(x.DurationUnit));
            }
            List<object> result = new List<object>();
            DateTime startTime = Convert.ToDateTime(query.SelectStartTime);
            DateTime endTime = Convert.ToDateTime(query.SelectEndTime);

            TimeSpan sp = endTime.Subtract(startTime);

            for (int i = 0; i <= sp.Days; i++)
            {
                string DayTime = string.Empty;
                List<object> planList = new List<object>();
                var nowDayList = oldPointGoodsList.Where(x => x.StudyDate.ToString("yyyy-MM-dd") == startTime.AddDays(i).ToString("yyyy-MM-dd"));
                foreach (var item in nowDayList)
                {
                    planList.Add(new
                    {
                        item.ID,
                        item.OrderNum,
                        item.TeacherId,
                        item.TeacherLogo,
                        item.TeacherName,
                        item.StudyDuration,
                        item.CourseClassId,
                        item.StudyStartDate,
                        item.StudyEndDate,
                        item.PointNum,
                        item.CourseName,
                        item.ClassName,
                        item.MinDuration,
                        item.StudentNumTypeName,
                        item.DurationUnitName
                    });
                }
                result.Add(new
                {
                    DayTime,
                    DateYear = startTime.AddDays(i).ToString("yyyy"),
                    DateMonth = startTime.AddDays(i).ToString("MM"),
                    DateDay = startTime.AddDays(i).ToString("dd"),
                    WeekStr = StringHelper.GetWeekChar(startTime.AddDays(i)),
                    PlanList = planList
                });
            }


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



        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetTeacherCourseModel()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Point_TeacherCourse_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var oldPointGoodsModel = pointModule.GetTeacherCourseList(query).FirstOrDefault();
            if (oldPointGoodsModel == null)
            {
                oldPointGoodsModel = new RB_Point_TeacherCourse_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>
        [HttpPost]
        public ApiResult GetSetTeacherCourse()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Point_TeacherCourse_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.CourseClassId == 0)
                {
                    return ApiResult.Failed("请选择课程类型");
                }
                if (query.TeacherId == 0)
                {
                    return ApiResult.Failed("请选择老师");
                }
                if (query.PointNum == 0)
                {
                    return ApiResult.Failed("请输入点数");
                }
                if (query.StudyDuration == 0)
                {
                    return ApiResult.Failed("请输入课时时长");
                }
                if (query.MinDuration == 0)
                {
                    return ApiResult.Failed("请输入最少约课时长");
                }
                if (string.IsNullOrWhiteSpace(query.CourseName))
                {
                    return ApiResult.Failed("请输入课程名称");
                }

                //判断时间范围内是否有重复的排课
                var oldPointGoodsList = pointModule.GetTeacherCourseList(new RB_Point_TeacherCourse_Extend
                {
                    TenantId = UserInfo.TenantId,
                    MallBaseId = parms.MallBaseId,
                    TeacherId = query.TeacherId,
                    SelectEndTime = query.StudyDate.ToString("yyyy-MM-dd"),
                    SelectStartTime = query.StudyDate.ToString("yyyy-MM-dd")
                }).Where(x => x.ID != query.ID).ToList();

                query.StudyStartTime = Convert.ToDateTime(query.StudyDate.ToString("yyyy-MM-dd") + " " + query.StudyStartDate);

                query.StudyEndTime = Convert.ToDateTime(query.StudyDate.ToString("yyyy-MM-dd") + " " + query.StudyEndDate);

                oldPointGoodsList.ForEach(x => x.StudyStartTime = Convert.ToDateTime(x.StudyDate.ToString("yyyy-MM-dd") + " " + x.StudyStartDate));
                oldPointGoodsList.ForEach(x => x.StudyEndTime = Convert.ToDateTime(x.StudyDate.ToString("yyyy-MM-dd") + " " + x.StudyEndDate));
                foreach (var item in oldPointGoodsList)
                {
                    if (GetTimeSpan(query.StudyStartTime, item.StudyStartDate, item.StudyEndDate))
                    {
                        return ApiResult.Failed("排课时间不能交叉，已存在" + item.StudyStartDate + "~" + item.StudyEndDate);
                    }
                }


                query.State = 0;
                query.UpdateDate = System.DateTime.Now;
                bool result = pointModule.SetTeacherCourse(query);
                if (result)
                {
                    return ApiResult.Success("老师排课信息保存成功");
                }
                else
                {
                    return ApiResult.Failed("老师排课信息保存失败");
                }
            }
        }



        public bool GetTimeSpan(DateTime timeStr, string StartTime, string EndTime)
        {
            //判断当前时间是否在工作时间段内

            TimeSpan dspWorkingDayAM = DateTime.Parse(StartTime).TimeOfDay;
            TimeSpan dspWorkingDayPM = DateTime.Parse(EndTime).TimeOfDay;
            TimeSpan dspNow = timeStr.TimeOfDay;
            if (dspNow > dspWorkingDayAM && dspNow < dspWorkingDayPM)
            {
                return true;
            }
            return false;
        }


        /// <summary>
        /// 删除老师排课
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DeleteTeacherCourse()
        {
            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.DeleteTeacherCourse(new RB_Point_TeacherCourse_Extend { ID = Id, TenantId = UserInfo.TenantId, MallBaseId = parms.MallBaseId });
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }
        #endregion
    }
}
