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 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);
            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,
                x.OrderId
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 后台获取充值订单列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserPointOrderPageList()
        {
            var parms = RequestParm;
            var userInfo = UserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_Point_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Point_Order_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            var list = pointModule.GetPointOrderPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ID,
                x.OrderNo,
                x.PonitNum,
                x.OldPonitNum,
                x.GivePoint,
                x.Income,
                PaymentTime = x.PaymentTime.HasValue ? x.PaymentTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.PaymentWay,
                PaymentWayName = x.PaymentWay.GetEnumName(),
                x.OrderStatus,
                x.OrderSource,
                OrderSourceName = x.OrderSource.GetEnumName(),
                x.PayWay,
                PayWayName = x.PayWay.GetEnumName(),
                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 GetPointOrderPageList()
        {
            var userInfo = UserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_Point_TeacherCourseOrder_Extend demodel = JsonConvert.DeserializeObject<RB_Point_TeacherCourseOrder_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            var list = pointModule.GetPointOrderPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ID,
                x.CourseClassId,
                CourseClassTypeName = x.CourseClassType.GetEnumName(),
                x.CourseId,
                x.CourseName,
                x.TeacherId,
                x.TeacherName,
                x.TeacherLogo,
                StudyDate = x.StudyDate.ToString("MM-dd HH:mm"),
                x.StudyDuration,
                x.TotalStudyDuration,
                DurationUnit = x.DurationUnit.GetEnumName(),
                x.OrderStaus,
                OrderStatusName = x.OrderStaus.GetEnumName(),
                x.IsSendRoom,
                x.RoomInfo,
                x.TotalPointNum,
                x.ActualPointNum,
                x.BasePointNum,
                x.UserId,
                x.UserName,
                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 GetPointOrderInfo()
        {
            var userInfo = UserInfo;
            var parms = JObject.Parse(RequestParm.msg.ToString());
            int OrderId = parms.GetInt("OrderId", 0);
            if (OrderId <= 0)
            {
                return ApiResult.ParamIsNull("请传递订单id");
            }

            var model = pointModule.GetPointOrderInfo(OrderId, userInfo.TenantId);
            if (model == null) { return ApiResult.Failed("订单不存在"); }
            return ApiResult.Success("", new
            {
                model.ID,
                model.CourseClassId,
                CourseClassTypeName = model.CourseClassType.GetEnumName(),
                model.CourseId,
                model.CourseName,
                model.TeacherId,
                model.TeacherName,
                model.TeacherLogo,
                StudyDate = model.StudyDate.ToString("MM-dd HH:mm"),
                model.StudyDuration,
                model.TotalStudyDuration,
                DurationUnit = model.DurationUnit.GetEnumName(),
                model.OrderStaus,
                OrderStatusName = model.OrderStaus.GetEnumName(),
                model.IsSendRoom,
                model.RoomInfo,
                model.TotalPointNum,
                model.ActualPointNum,
                model.BasePointNum,
                model.UserId,
                model.UserName,
                CreateDate = model.CreateDate.HasValue ? model.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
            });
        }

        /// <summary>
        /// 约课订单excel下载
        /// </summary>
        [HttpPost]
        public FileContentResult GetPointOrderListToExcel()
        {
            var userInfo = UserInfo;
            RB_Point_TeacherCourseOrder_Extend demodel = JsonConvert.DeserializeObject<RB_Point_TeacherCourseOrder_Extend>(RequestParm.msg.ToString());
            string ExcelName = "约课列表" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            ExcelDataSource header = new ExcelDataSource()
            {
                ExcelRows = new List<ExcelColumn>(30) {
                    new ExcelColumn(value: "单号") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "课程分类") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "课程名称") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "教师") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "学习时间") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "学习时长") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "学习总时长") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "房间信息") { CellWidth = 25, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "总点数") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "实际点数") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "基础点数") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "用户名称") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "报名时间") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "状态") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                }
            };
            slist.Add(header);

            try
            {
                demodel.TenantId = userInfo.TenantId;
                demodel.MallBaseId = userInfo.MallBaseId;
                var list = pointModule.GetPointOrderPageList(1, 99999, out long count, demodel);
                #region 组装数据
                foreach (var item in list)
                {
                    ExcelDataSource datarow = new ExcelDataSource()
                    {
                        ExcelRows = new List<ExcelColumn>(30) {
                            new ExcelColumn(value:item.ID.ToString()){ },
                            new ExcelColumn(value:item.CourseClassType.GetEnumName()){ },
                            new ExcelColumn(value:item.CourseName){ },
                            new ExcelColumn(value:item.TeacherName){ },
                            new ExcelColumn(value:item.StudyDate.ToString("yyyy-MM-dd HH:mm")){ },
                            new ExcelColumn(value:item.StudyDuration.ToString()){ },
                            new ExcelColumn(value:item.TotalStudyDuration.ToString()){ },
                            new ExcelColumn(value:item.RoomInfo){ },
                            new ExcelColumn(value:item.TotalPointNum.ToString()){ },
                            new ExcelColumn(value:item.ActualPointNum.ToString()){ },
                            new ExcelColumn(value:item.BasePointNum.ToString()){ },
                            new ExcelColumn(value:item.UserName + "("+item.UserId.ToString()+")"){ },
                            new ExcelColumn(value:(item.CreateDate.HasValue ? item.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "")){ },
                            new ExcelColumn(value:item.OrderStaus.GetEnumName()){ },
                        },
                        ColumnHight = 30
                    };
                    slist.Add(datarow);
                }
                #endregion

                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);

                return File(byteData, "application/octet-stream", ExcelName);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, string.Format("GetFileFromWebApi_requestData: {0}", JsonHelper.Serialize(RequestParm)));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }

        }



        /// <summary>
        /// 保存课程分类信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetConfirmTeacherCourseOrder()
        {
            var parms = RequestParm;
            var userInfo = UserInfo;
            var query = JsonConvert.DeserializeObject<RB_Point_TeacherCourseOrder_Extend>(RequestParm.msg.ToString());
            query.TenantId = userInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
          
            if (query == null)
            {
                return ApiResult.Failed("请传入课程订单信息");
            }
            else
            {
                if (query.CourseId == 0)
                {
                    return ApiResult.Failed("请选择课程信息");
                }
                if (query.TeacherId == 0)
                {
                    return ApiResult.Failed("请传入老师id");
                }
                if (string.IsNullOrWhiteSpace(query.RoomInfo))
                {
                    return ApiResult.Failed("请传入房间信息");
                }

                var oldcourseOrderList = pointModule.GetPointOrderList(new RB_Point_TeacherCourseOrder_Extend { CourseId = query.CourseId, TeacherId = query.TeacherId });
                var updateList = new List<RB_Point_TeacherCourseOrder_Extend>();
                if (query.StudentNumType == Common.Enum.Point.StudentNumTypeEnum.OneOnOne)
                {
                    if (query.ID == 0)
                    {
                        return ApiResult.Failed("请传入订单号id");
                    }
                    else
                    {
                        updateList = oldcourseOrderList.Where(x => x.ID == query.ID && x.OrderStaus == Common.Enum.Point.OrderStausEnum.Paid).ToList();
                    }
                }
                else
                {
                    updateList = oldcourseOrderList.Where(x => x.OrderStaus == Common.Enum.Point.OrderStausEnum.Paid).ToList();
                }
                if (updateList == null || !updateList.Any())
                {
                    return ApiResult.Failed("订单已确认");
                }
                updateList.ForEach(x => x.OrderStaus = Common.Enum.Point.OrderStausEnum.NoClass);
                updateList.ForEach(x => x.UpdateDate = System.DateTime.Now);
                updateList.ForEach(x => x.RoomInfo = query.RoomInfo);

                bool result = pointModule.ConfirmTeacherCourseOrder(updateList);
                if (result)
                {
                    return ApiResult.Success("订单确认成功");
                }
                else
                {
                    return ApiResult.Failed("订单确认失败");
                }
            }
        }


        /// <summary>
        /// 保存课程分类信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCompleteTeacherCourseOrder()
        {
            var parms = RequestParm;
            var userInfo = UserInfo;
            var query = JsonConvert.DeserializeObject<RB_Point_TeacherCourseOrder_Extend>(RequestParm.msg.ToString());
            query.TenantId = userInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
          
            if (query == null)
            {
                return ApiResult.Failed("请传入课程订单信息");
            }
            else
            {
                if (query.ID == 0)
                {
                    return ApiResult.Failed("请传入课程订单信息");
                }
                var oldModel = pointModule.GetPointOrderList(query).FirstOrDefault();
                if (oldModel == null || oldModel.ID == 0)
                {
                    return ApiResult.Failed("请传入课程订单信息");
                }
                oldModel.ActualPointNum = query.ActualPointNum;
                oldModel.UpdateDate = System.DateTime.Now;
                oldModel.OrderStaus = Common.Enum.Point.OrderStausEnum.Complete;

                DateTime nowOrderDate = query.StudyDate;

                if (query.DurationUnit == Common.Enum.Point.DurationUnitEnum.Hour)
                {
                    nowOrderDate = query.StudyDate.AddMinutes(Convert.ToDouble(query.TotalStudyDuration * 60));
                }
                else
                {
                    nowOrderDate = query.StudyDate.AddMinutes(Convert.ToDouble(query.TotalStudyDuration));
                }
                bool result = pointModule.CompleteTeacherCourseOrder(oldModel);
                if (result)
                {
                    return ApiResult.Success("订单完成操作成功");
                }
                else
                {
                    return ApiResult.Failed("订单完成操作失败");
                }
            }
        }


        /// <summary>
        /// 获取订单状态枚举
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetOrderStausEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(Common.Enum.Point.OrderStausEnum));
            return ApiResult.Success("", list.OrderBy(x => Convert.ToInt32(x.Value)).Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }


        #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,
                x.Title
            });
            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"));
                int haveCourseCount = nowDayList.Count();
                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,
                        RoomIdInfo = string.IsNullOrWhiteSpace(item.RoomId) ? "第三方" : "微信房间号：" + item.RoomId
                    });
                }
                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,
                    HaveCourseCount = haveCourseCount
                });
            }


            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.IsPublic == 0)
                {
                    if (query.PointNum == 0)
                    {
                        return ApiResult.Failed("请输入点数");
                    }
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(query.RoomId))
                    {
                        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 (pointModule.GetTimeSpan(query.StudyStartTime, item.StudyStartDate, item.StudyEndDate))
                    {
                        return ApiResult.Failed("排课时间不能交叉，已存在" + item.StudyStartDate + "~" + item.StudyEndDate);
                    }
                    if (pointModule.GetTimeSpan(item.StudyStartTime, query.StudyStartDate, query.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("老师排课信息保存失败");
                }
            }
        }

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