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.BaseSetUp;
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 AppletPointController : BaseController
    {

        private readonly PointModule pointModule = new PointModule();

        private readonly Module.User.MiniProgramModule appletWeChatModule = new Module.User.MiniProgramModule();
        #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 GetAppletUserPointOrderPageList()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            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;
            demodel.UserId = userInfo.UserId;
            demodel.OrderStatus = 2;
            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.UserId,
                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 GetPointTeacherCoursePageList()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_Point_TeacherCourse_Extend demodel = JsonConvert.DeserializeObject<RB_Point_TeacherCourse_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            //根据userid  查询teacherid 
            int TeacherId = pointModule.GetUserTeacherId(userInfo.TenantId, userInfo.UserId);
            if (TeacherId <= 0) { return ApiResult.Failed("不是教师，无法查询"); }
            demodel.TeacherId = TeacherId;
            var list = pointModule.GetPointTeacherCoursePageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ID,
                x.CourseClassId,
                x.CourseClassType,
                CourseClassTypeName = x.CourseClassType.GetEnumName(),
                x.CourseName,
                x.TeacherId,
                StudyDate = x.StudyDate.ToString("yyyy-MM-dd"),
                x.StudyStartDate,
                x.StudyEndDate,
                x.PointNum,
                x.MinDuration,
                x.StudyDuration,
                DurationUnit = x.DurationUnit.GetEnumName(),
                x.ConfirmNum,
                x.OrderNum,
                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 GetPointTeacherCourseDetail()
        {
            var userInfo = AppletUserInfo;
            var parms = JObject.Parse(RequestParm.msg.ToString());
            int CourseId = parms.GetInt("CourseId", 0);//课程Id
            if (CourseId <= 0)
            {
                return ApiResult.ParamIsNull("课程id不存在，请核实后再试");
            }
            //根据userid  查询teacherid 
            int TeacherId = pointModule.GetUserTeacherId(userInfo.TenantId, userInfo.UserId);
            if (TeacherId <= 0) { return ApiResult.Failed("不是教师，无法查询"); }

            return pointModule.GetPointTeacherCourseDetail(CourseId, TeacherId, userInfo);
        }

        #endregion

        #region 订单列表
        /// <summary>
        /// 获取订单列表分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetPointOrderPageList()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            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;
            demodel.UserId = userInfo.UserId;//只能查询自己的订单列表
            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"),
                StudyDateStr = x.StudyDate.ToString("yyyy-MM-dd HH:mm:ss"),
                x.StudyDuration,
                x.TotalStudyDuration,
                x.DurationUnit,
                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 = AppletUserInfo;
            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("订单不存在"); }
            if (model.UserId != userInfo.UserId) { 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"),
                StudyDateStr = model.StudyDate.ToString("yyyy-MM-dd HH:mm:ss"),
                model.StudyDuration,
                model.TotalStudyDuration,
                model.DurationUnit,
                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>
        /// 获取商品版面类型枚举
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetOrderStausEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(Common.Enum.Point.OrderStausEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }
        #endregion

        #region 课程订单下单
        /// <summary>
        /// 保存课程分类信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSetTeacherCourseOrder()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            var query = JsonConvert.DeserializeObject<RB_Point_TeacherCourseOrder_Extend>(RequestParm.msg.ToString());
            query.TenantId = userInfo.TenantId;
            query.MallBaseId = userInfo.MallBaseId;
            if (query == null)
            {
                return ApiResult.Failed("请传入课程订单信息");
            }
            else
            {
                if (query.CourseId == 0)
                {
                    return ApiResult.Failed("请选择您要购买的课程");
                }
                if (query.ID == 0)
                {
                    query.CreateDate = System.DateTime.Now;
                }
                query.OrderStaus = Common.Enum.Point.OrderStausEnum.NoPaid;
                if (query.StudyDate <= System.DateTime.Now)
                {
                    return ApiResult.Failed("请提前预约课程");
                }
                //查询课程信息
                var courseModel = pointModule.GetTeacherCourseList(new RB_Point_TeacherCourse_Extend { TeacherId = query.TeacherId, ID = query.CourseId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();
                // var courseClassModel = pointModule.GetPointCourseClassList(new RB_Point_CourseClass_Extend { ID = query.CourseClassId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();
                query.TeacherId = courseModel.TeacherId;

                //判断时长是否一致
                if ((query.TotalStudyDuration % courseModel.StudyDuration) != 0)
                {
                    return ApiResult.Failed("约课总时长必须课时时长的整数倍");
                }
                //判断时长是否一致
                if (query.StudyDuration != courseModel.StudyDuration)
                {
                    return ApiResult.Failed("约课时长与课时时长不等");
                }

                if (query.BasePointNum != courseModel.PointNum)
                {
                    return ApiResult.Failed("约课点数错误");
                }

                if (query.TotalPointNum != (query.BasePointNum * (query.TotalStudyDuration / courseModel.StudyDuration)))
                {
                    return ApiResult.Failed("约课总点数错误");

                }


                //if (query.OrderStaus == Common.Enum.Point.OrderStausEnum.Paid)
                //{
                var userModel = pointModule.GetUserEntity(userInfo.UserId);
                if (userModel == null)
                {
                    return ApiResult.Failed("用户信息不存在");
                }
                else
                {
                    if (userModel.PointNum < query.TotalPointNum)
                    {
                        return ApiResult.Failed("点数不够，请先购买点数");
                    }
                    else
                    {
                        query.OrderStaus = Common.Enum.Point.OrderStausEnum.Paid;
                    }
                }
                if (!string.IsNullOrWhiteSpace(courseModel.RoomId) && query.OrderStaus == Common.Enum.Point.OrderStausEnum.Paid)
                {
                    query.OrderStaus = Common.Enum.Point.OrderStausEnum.NoClass;
                    query.IsSendRoom = 1;
                    query.RoomInfo = "微信直播";
                }
                courseModel.StudyStartTime = Convert.ToDateTime(courseModel.StudyDate.ToString("yyyy-MM-dd") + " " + courseModel.StudyStartDate);
                if (courseModel.StudentNumType == Common.Enum.Point.StudentNumTypeEnum.OneToMany)//一对多的时候判断开始时间是否和课程一样
                {
                    if (courseModel.StudyDate != courseModel.StudyStartTime)
                    {
                        return ApiResult.Failed("预约时间与课程时间不一致");
                    }
                }
                else
                {
                    var orderList = pointModule.GetPointOrderList(new RB_Point_TeacherCourseOrder_Extend { TeacherId = query.TeacherId, CourseId = query.CourseId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });

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


                    //判断同一时间是否重复预约
                    if (query.StudyDate < courseModel.StudyStartTime)
                    {
                        return ApiResult.Failed("预约时间不能小于开始时间");
                    }
                    if (nowOrderDate > Convert.ToDateTime(courseModel.StudyDate.ToString("yyyy-MM-dd") + " " + courseModel.StudyEndDate))
                    {
                        return ApiResult.Failed("预约结束时间不能大于课程预约结束时间");
                    }

                    foreach (var item in orderList)
                    {
                        DateTime endTime = item.StudyDate;

                        if (item.DurationUnit == Common.Enum.Point.DurationUnitEnum.Hour)
                        {
                            endTime = item.StudyDate.AddMinutes(Convert.ToDouble(item.TotalStudyDuration * 60));
                        }
                        else
                        {
                            endTime = item.StudyDate.AddMinutes(Convert.ToDouble(item.TotalStudyDuration));
                        }
                        if (query.StudyDate == item.StudyDate)
                        {
                            return ApiResult.Failed("当前预约时间已预约");
                        }
                        if (pointModule.GetTimeSpan(query.StudyDate, item.StudyDate.ToString("HH:mm"), endTime.ToString("HH:mm")))
                        {
                            return ApiResult.Failed("当前预约时间已预约");
                        }
                        if (pointModule.GetTimeSpan(nowOrderDate, item.StudyDate.ToString("HH:mm"), endTime.ToString("HH:mm")))
                        {
                            return ApiResult.Failed("当前预约时间已预约");
                        }
                    }
                }

                query.ActualPointNum = query.TotalPointNum;
                query.State = 0;
                query.UserId = userInfo.UserId;
                query.UpdateDate = System.DateTime.Now;
                bool result = pointModule.SetTeacherCourseOrder(query);
                if (result)
                {
                    return ApiResult.Success("预约成功");
                }
                else
                {
                    return ApiResult.Failed("预约失败");
                }
            }
        }

        /// <summary>
        /// 保存课程分类信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetTeacherCourseOrder()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            var query = JsonConvert.DeserializeObject<RB_Point_TeacherCourseOrder_Extend>(RequestParm.msg.ToString());
            query.TenantId = userInfo.TenantId;
            query.MallBaseId = userInfo.MallBaseId;
            if (query == null)
            {
                return ApiResult.Failed("请传入课程订单信息");
            }
            else
            {
                if (query.CourseId == 0)
                {
                    return ApiResult.Failed("请选择您要购买的课程");
                }
                if (query.ID == 0)
                {
                    query.CreateDate = System.DateTime.Now;
                }
                if (query.StudyDate <= System.DateTime.Now)
                {
                    return ApiResult.Failed("请提前预约课程");
                }
                //查询课程信息
                var courseModel = pointModule.GetTeacherCourseList(new RB_Point_TeacherCourse_Extend { TeacherId = query.TeacherId, ID = query.CourseId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();
                // var courseClassModel = pointModule.GetPointCourseClassList(new RB_Point_CourseClass_Extend { ID = query.CourseClassId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();
                query.TeacherId = courseModel.TeacherId;

                //判断时长是否一致
                //if ((query.TotalStudyDuration % courseModel.StudyDuration) != 0)
                //{
                //    return ApiResult.Failed("约课总时长必须课时时长的整数倍");
                //}
                ////判断时长是否一致
                //if (query.StudyDuration != courseModel.StudyDuration)
                //{
                //    return ApiResult.Failed("约课时长与课时时长不等");
                //}

                //if (query.BasePointNum != courseModel.PointNum)
                //{
                //    return ApiResult.Failed("约课点数错误");
                //}

                //if (query.TotalPointNum != (query.BasePointNum * (query.TotalStudyDuration / courseModel.StudyDuration)))
                //{
                //    return ApiResult.Failed("约课总点数错误");

                //}


                //if (query.OrderStaus == Common.Enum.Point.OrderStausEnum.Paid)
                //{
                var userModel = pointModule.GetUserEntity(userInfo.UserId);
                if (userModel == null)
                {
                    return ApiResult.Failed("用户信息不存在");
                }
                else
                {
                    if (userModel.PointNum < query.TotalPointNum)
                    {
                        return ApiResult.Failed("点数不够，请先购买点数");
                    }
                }

                courseModel.StudyStartTime = Convert.ToDateTime(courseModel.StudyDate.ToString("yyyy-MM-dd") + " " + courseModel.StudyStartDate);
                if (courseModel.StudentNumType == Common.Enum.Point.StudentNumTypeEnum.OneToMany)//一对多的时候判断开始时间是否和课程一样
                {
                    if (courseModel.StudyDate != courseModel.StudyStartTime)
                    {
                        return ApiResult.Failed("预约时间与课程时间不一致");
                    }
                }
                else
                {
                    var orderList = pointModule.GetPointOrderList(new RB_Point_TeacherCourseOrder_Extend { TeacherId = query.TeacherId, CourseId = query.CourseId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });

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


                    //判断同一时间是否重复预约
                    if (query.StudyDate < courseModel.StudyStartTime)
                    {
                        return ApiResult.Failed("预约时间不能小于开始时间");
                    }
                    if (nowOrderDate > Convert.ToDateTime(courseModel.StudyDate.ToString("yyyy-MM-dd") + " " + courseModel.StudyEndDate))
                    {
                        return ApiResult.Failed("预约结束时间不能大于课程预约结束时间");
                    }

                    foreach (var item in orderList)
                    {
                        DateTime endTime = item.StudyDate;

                        if (item.DurationUnit == Common.Enum.Point.DurationUnitEnum.Hour)
                        {
                            endTime = item.StudyDate.AddMinutes(Convert.ToDouble(item.TotalStudyDuration * 60));
                        }
                        else
                        {
                            endTime = item.StudyDate.AddMinutes(Convert.ToDouble(item.TotalStudyDuration));
                        }
                        if (query.StudyDate == item.StudyDate)
                        {
                            return ApiResult.Failed("当前预约时间已预约");
                        }
                        if (pointModule.GetTimeSpan(query.StudyDate, item.StudyDate.ToString("HH:mm"), endTime.ToString("HH:mm")))
                        {
                            return ApiResult.Failed("当前预约时间已预约");
                        }
                        if (pointModule.GetTimeSpan(nowOrderDate, item.StudyDate.ToString("HH:mm"), endTime.ToString("HH:mm")))
                        {
                            return ApiResult.Failed("当前预约时间已预约");
                        }
                    }
                }
                return ApiResult.Success("当前时间课预约");

            }
        }
        /// <summary>
        /// 保存课程分类信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetConfirmTeacherCourseOrder()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            var query = JsonConvert.DeserializeObject<RB_Point_TeacherCourseOrder_Extend>(RequestParm.msg.ToString());
            query.TenantId = userInfo.TenantId;
            query.MallBaseId = userInfo.MallBaseId;
            if (userInfo.UserTeacher == 0)
            {
                return ApiResult.Failed("您当前无权操作");
            }
            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 = userInfo.UserTeacher });
                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);

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


        /// <summary>
        /// 保存课程分类信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult CompleteTeacherCourseOrder()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            var query = JsonConvert.DeserializeObject<RB_Point_TeacherCourseOrder_Extend>(RequestParm.msg.ToString());
            query.TenantId = userInfo.TenantId;
            query.MallBaseId = userInfo.MallBaseId;
            query.TeacherId = userInfo.UserTeacher;
            if (userInfo.UserTeacher == 0)
            {
                return ApiResult.Failed("您当前无权操作");
            }
            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;
                bool result = pointModule.CompleteTeacherCourseOrder(oldModel);
                if (result)
                {
                    return ApiResult.Success("订单确认成功");
                }
                else
                {
                    return ApiResult.Failed("订单确认失败");
                }
            }
        }
        #endregion


        #region 充值点数

        /// <summary>
        /// 小程序获取点数记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetPointGoodsList()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            RB_Point_Goods_Extend demodel = JsonConvert.DeserializeObject<RB_Point_Goods_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            var list = pointModule.GetPointGoodsList(demodel);
            var result = list.OrderBy(x => x.Sort).Select(x => new
            {
                x.ID,
                x.PonitNum,
                x.GivePoint,
                x.GoodsName,
                x.SellingPrice,
            });
            return ApiResult.Success("", result);
        }
        #endregion


        #region 老师排课
        /// <summary>
        /// 小程序获取点数记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetPointCourseClassList()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            RB_Point_CourseClass_Extend demodel = JsonConvert.DeserializeObject<RB_Point_CourseClass_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            var list = pointModule.GetPointCourseClassList(demodel);
            List<object> result = new List<object>();
            foreach (var item in list.GroupBy(x => x.StudentNumType))
            {
                result.Add(new
                {
                    StudentNumTypeStr = EnumHelper.GetEnumName(item.Key),
                    ClassList = list.Where(y => y.StudentNumType == item.Key).Select(t => new { t.IsFree, t.IsPublic, t.PointNum, t.ID, ClassName = EnumHelper.GetEnumName(t.CourseClassType), t.ClassPic, t.Title, t.Duration, DurationUnitName = EnumHelper.GetEnumName(t.DurationUnit) })
                });
            }
            return ApiResult.Success("", result);
        }



        /// <summary>
        /// 小程序获取点数记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetPointCourseDetail()
        {
            var userInfo = AppletUserInfo;
            RB_Point_TeacherCourse_Extend demodel = new RB_Point_TeacherCourse_Extend();
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            var parms = JObject.Parse(RequestParm.msg.ToString());
            int courseId = parms.GetInt("CourseId", 0);
            demodel.ID = courseId;
            var model = pointModule.GetTeacherCourseList(demodel).FirstOrDefault();
            var miniModel = appletWeChatModule.GetMiniProgramModule(new Model.Extend.User.RB_MiniProgram_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });
            List<RB_Point_TeacherCourseOrder_Extend> courseOrder = new List<RB_Point_TeacherCourseOrder_Extend>();
            if (model != null)
            {
                courseOrder = pointModule.GetPointOrderList(new RB_Point_TeacherCourseOrder_Extend { SelectOrderStatus = 1, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, CourseId = model.ID, UserId = userInfo.UserId });
            }

            List<object> orderList = new List<object>();
            if (courseOrder != null && courseOrder.Any())
            {
                orderList.AddRange(courseOrder.Select(x => new { x.UserName, x.Photo, StartStudyDate = x.StudyDate.ToString("HH:mm"), EndStudyDate = x.DurationUnit == Common.Enum.Point.DurationUnitEnum.Hour ? (x.StudyDate.AddMinutes(Convert.ToDouble(x.TotalStudyDuration * 60))) : x.StudyDate.AddMinutes(Convert.ToDouble(x.TotalStudyDuration)) }));
            }
            List<string> template_message_list = new List<string>();

            if (miniModel != null)
            {
                if (!string.IsNullOrWhiteSpace(miniModel.CourseOrderTpl))
                {
                    template_message_list.Add(miniModel.CourseOrderTpl);
                }
            }
            var result = new
            {
                template_message_list,
                model.ID,
                model.IsFree,
                model.IsPublic,
                model.MinDuration,
                model.StudyDuration,
                DurationUnitName = EnumHelper.GetEnumName(model.DurationUnit),
                model.PointNum,
                model.TeacherId,
                model.TeacherLogo,
                model.TeacherName,
                model.CourseName,
                model.RoomId,
                StudyDateStr = model.StudyDate.ToString("yyyy-MM-dd"),
                orderList,
                StudentNumTypeName = EnumHelper.GetEnumName(model.StudentNumType)
            };
            return ApiResult.Success("", result);
        }


        /// <summary>
        /// 课程列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetTeacherCourseList()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            var query = JsonConvert.DeserializeObject<RB_Point_TeacherCourse_Extend>(RequestParm.msg.ToString());
            query.TenantId = userInfo.TenantId;
            query.MallBaseId = userInfo.MallBaseId;
            if (string.IsNullOrWhiteSpace(query.SelectStartTime) || string.IsNullOrWhiteSpace(query.SelectEndTime))
            {
                return ApiResult.Failed("请传入查询时间范围");
            }
            var oldPointGoodsList = pointModule.GetTeacherCourseList(query);
            List<RB_Point_TeacherCourseOrder_Extend> courseOrder = new List<RB_Point_TeacherCourseOrder_Extend>();
            if (oldPointGoodsList != null && oldPointGoodsList.Any())
            {
                string courseIds = string.Join(",", oldPointGoodsList.Select(x => x.ID));
                courseOrder = pointModule.GetPointOrderList(new RB_Point_TeacherCourseOrder_Extend { SelectOrderStatus = 1, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, CourseIds = courseIds });
            }

            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 = 0;

                foreach (var item in nowDayList)
                {
                    var nowCourseOrderList = courseOrder.Where(x => item.ID == x.CourseId);
                    haveCourseCount += nowCourseOrderList.Count();

                    List<object> orderList = new List<object>();
                    if (nowCourseOrderList != null && nowCourseOrderList.Any())
                    {
                        orderList.AddRange(nowCourseOrderList.Select(x => new { x.UserName, x.Photo, StartStudyDate = x.StudyDate.ToString("HH:mm"), EndStudyDate = (x.DurationUnit == Common.Enum.Point.DurationUnitEnum.Hour ? (x.StudyDate.AddMinutes(Convert.ToDouble(x.TotalStudyDuration * 60))) : x.StudyDate.AddMinutes(Convert.ToDouble(x.TotalStudyDuration))).ToString("HH:mm") }));
                    }
                    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,
                        item.RoomId,
                        IsHaveCourse = nowCourseOrderList.Count(),
                        OrderList = orderList
                    });
                }
                result.Add(new
                {
                    DayTime,
                    DateYear = startTime.AddDays(i).ToString("yyyy"),
                    DateMonth = startTime.AddDays(i).ToString("MM"),
                    DateDay = startTime.AddDays(i).ToString("dd"),
                    haveCourseCount,
                    WeekStr = StringHelper.GetWeek(startTime.AddDays(i)).Replace('周', ' ').TrimStart(' '),
                    PlanList = planList
                });
            }
            return ApiResult.Success("", result);
        }

        #endregion
    }
}
