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

        private readonly PointModule pointModule = new PointModule();


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


        #region 课程订单下单
        /// <summary>
        /// 保存课程分类信息
        /// </summary>
        /// <returns></returns>
        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;
                }
                //查询课程信息
                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("当前预约时间已预约");
                        }
                    }
                }

                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 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"),
                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 = 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"),
                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") : "",
            });
        }



        #endregion
    }
}
