using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Edu.Cache.User;
using Edu.Common.API;
using Edu.Common.Enum.Course;
using Edu.Common.Plugin;
using Edu.Model.ViewModel.Course;
using Edu.Model.ViewModel.Grade;
using Edu.Model.ViewModel.Sell;
using Edu.Model.ViewModel.User;
using Edu.Module.Course;
using Edu.Module.Finance;
using Edu.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace Edu.WebApi.Controllers.Course
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class TeacherClassController : BaseController
    {
        /// <summary>
        /// 班级处理类对象
        /// </summary>
        private readonly ClassModule classModule = AOP.AOPHelper.CreateAOPObject<ClassModule>();

        /// <summary>
        /// 财务处理类对象
        /// </summary>
        private readonly FinanceModule financeModule = AOP.AOPHelper.CreateAOPObject<FinanceModule>();
        #region 班级管理
        /// <summary>
        /// 获取班级页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetClassPageList()
        {
            var pageModel = Common.Plugin.JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Class_ViewModel()
            {
                ClassName = base.ParmJObj.GetStringValue("ClassName"),
                ClassStatus = (ClassStatusEnum)base.ParmJObj.GetInt("ClassStatus"),
                Teacher_Id = base.ParmJObj.GetInt("Teacher_Id"),
                CouseId = base.ParmJObj.GetInt("CouseId"),
                School_Id = base.ParmJObj.GetInt("School_Id"),
                TeacherName = base.ParmJObj.GetStringValue("TeacherName"),
                CourseName = base.ParmJObj.GetStringValue("CourseName"),
                CourseSubject = base.ParmJObj.GetInt("CourseSubject"),
            };
            query.Group_Id = base.UserInfo.Group_Id;
            List<object> result = new List<object>();
            var list = classModule.GetClassPageListModule(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);
            foreach (var item in list)
            {
                if (item.CreateBy > 0)
                {
                    item.CreateByName = UserReidsCache.GetUserLoginInfo(item.CreateBy)?.AccountName ?? "";
                }
                if (item.UpdateBy > 0)
                {
                    item.UpdateByName = UserReidsCache.GetUserLoginInfo(item.UpdateBy)?.AccountName ?? "";
                }
                result.Add(new
                {
                    item.ClassId,
                    item.ClassName,
                    item.School_Id,
                    item.SchoolName,
                    item.CourseName,
                    item.Teacher_Id,
                    item.TeacherName,
                    item.ClassRoomId,
                    item.RoomName,
                    item.ClassPersion,
                    item.TotalPlanNum,
                    item.UsePlanNum,
                    OpenTime = Common.ConvertHelper.FormatDate(item.OpenTime),
                    item.ClassStatusStr,
                    item.NewPlanDateTime,
                    item.ClassStatus,
                    item.Status,
                    item.OtherCourseList,
                    item.ClassNo,
                    item.CouseId,
                    item.FinishTimeStr,
                    item.OrderStudentCount,
                    item.CourseSubject,
                    item.CourseSubjectName,
                });
            }
            pageModel.Count = rowsCount;
            pageModel.PageData = result;
            return ApiResult.Success(data: pageModel);
        }
        #endregion

        #region 我的课表
        /// <summary>
        /// 老师上课计划统计
        /// </summary>
        /// <returns></returns>
        public ApiResult GetClassPlanStatistical()
        {
            var startDate = base.ParmJObj.GetStringValue("StartTime");
            var endDate = base.ParmJObj.GetStringValue("EndTime");
            DateTime now = DateTime.Now;

            //获取当前月的第一天
            DateTime d1 = new DateTime(now.Year, now.Month, 1);
            //当月最后一天
            DateTime d2 = d1.AddMonths(1).AddDays(-1);
            if (string.IsNullOrEmpty(startDate))
            {
                startDate = Common.ConvertHelper.FormatDate(d1);
            }
            if (string.IsNullOrEmpty(endDate))
            {
                endDate = Common.ConvertHelper.FormatDate(d2);
            }
            else
            {
                //if (Convert.ToDateTime(endDate) > Convert.ToDateTime(Common.ConvertHelper.FormatDate(DateTime.Now)))
                //{
                //    endDate = Common.ConvertHelper.FormatDate(DateTime.Now);
                //}
            }
            RB_Class_Plan_ViewModel query = new RB_Class_Plan_ViewModel()
            {
                StartTime = startDate,
                EndTime = endDate,
                TeacherId = base.ParmJObj.GetInt("TeacherId"),
                ClassRoomId = base.ParmJObj.GetInt("ClassRoomId"),
                Group_Id = base.UserInfo.Group_Id,
                School_Id = -1,
                ClassId = base.ParmJObj.GetInt("ClassId"),
            };
            //课程类型(0-全部,1-正常,2-试听课)
            int ClassType = base.ParmJObj.GetInt("ClassType");
            var obj = classModule.GetTeacherPlanStatisticalModule(query, ClassType: ClassType);
            return ApiResult.Success(data: obj);
        }



        /// <summary>
        /// 老师上课计划统计
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetClassPlanStatisticalPage()
        {
            var pageModel = Common.Plugin.JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var startDate = base.ParmJObj.GetStringValue("StartTime");
            var endDate = base.ParmJObj.GetStringValue("EndTime");
            DateTime now = DateTime.Now;

            //获取当前月的第一天
            DateTime d1 = new DateTime(now.Year, now.Month, 1);
            //当月最后一天
            DateTime d2 = d1.AddMonths(1).AddDays(-1);
            if (string.IsNullOrEmpty(startDate))
            {
                startDate = Common.ConvertHelper.FormatDate(d1);
            }
            if (string.IsNullOrEmpty(endDate))
            {
                endDate = Common.ConvertHelper.FormatDate(d2);
            }
            RB_Class_Plan_ViewModel query = new RB_Class_Plan_ViewModel()
            {
                StartTime = startDate,
                EndTime = endDate,
                TeacherId = base.ParmJObj.GetInt("TeacherId"),
                ClassRoomId = base.ParmJObj.GetInt("ClassRoomId"),
                Group_Id = base.UserInfo.Group_Id,
                School_Id = -1,
                ClassId = base.ParmJObj.GetInt("ClassId"),
                OrderBy = base.ParmJObj.GetInt("OrderBy", 0),
                ClassType = base.ParmJObj.GetInt("ClassType")// //课程类型(0-全部,1-正常,2-试听课)
            };
            var result = classModule.GetTeacherPlan(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);
            pageModel.Count = rowsCount;
            pageModel.PageData = result;
            return ApiResult.Success(data: pageModel);
        }


        #endregion


        #region 月度耗课
        /// <summary>
        /// 班级月度课耗统计
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetClassMonthStatistics()
        {
            var userInfo = base.UserInfo;
            int classId = base.ParmJObj.GetInt("ClassId", 0);

            var list = financeModule.GetTeacherClassMonthStatistics(classId, userInfo);
            return ApiResult.Success("", list);
        }

        #endregion


        #region 学员管理
        /// <summary>
        /// 获取学员列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetClassStudent()
        {
            var pageModel = Common.Plugin.JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());

            var model = new RB_Order_Guest_ViewModel
            {
                Teacher_Id = base.ParmJObj.GetInt("Teacher_Id", 0),
                GuestName = base.ParmJObj.GetStringValue("GuestName"),
                ClassId = base.ParmJObj.GetInt("ClassId", 0),
                CourseId = base.ParmJObj.GetInt("CourseId", 0),
                EnterID = base.ParmJObj.GetInt("EnterID", 0),
            };
            model.Group_Id = base.UserInfo.Group_Id;
            var list = classModule.GetTeacherStudentPage(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, model);
            List<object> result = new List<object>();

            foreach (var item in list)
            {
                if (item.EnterID > 0)
                {
                    item.EnterName = UserReidsCache.GetUserLoginInfo(item.EnterID)?.AccountName ?? "";
                }
                result.Add(new
                {
                    item.Id,
                    item.GuestName,
                    Mobile=item.StuTel,
                    item.ClassId,
                    item.ClassName,
                    item.CourseId,
                    item.CourseName,
                    item.GuestState,
                    item.GuestStateStr,
                    item.School_Id,
                    item.Teacher_Id,
                    item.TotalPlanNum,
                    item.Ranks,
                    item.EnterName,
                    item.EnterID,
                    item.IsRenewOrder,
                    item.RenewOrderId,
                    item.JoinType,
                    JoinTypeName = item.JoinType.ToName(),
                    item.TargetJoinType,
                    TargetJoinTypeName = item.TargetJoinType.ToName(),
                    item.TargetOrderId,
                    item.SourceOrderId,
                    item.StudentId
                });
            }
            pageModel.Count = rowsCount;
            pageModel.PageData = result;
            return ApiResult.Success(data: pageModel);
        }




        /// <summary>
        /// 获取学员列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetNotClassStudentList()
        {
            var model = new RB_Order_Guest_ViewModel
            {
                Teacher_Id = base.ParmJObj.GetInt("Teacher_Id", 0),
                GuestName = base.ParmJObj.GetStringValue("GuestName"),
                ClassId = base.ParmJObj.GetInt("ClassId", 0),
                CourseId = base.ParmJObj.GetInt("CourseId", 0),
                EnterID = base.ParmJObj.GetInt("EnterID", 0),
            };
            model.Group_Id = base.UserInfo.Group_Id;
            var list = classModule.GetNotClassStudentList(model);
            List<object> result = new List<object>();
            foreach (var item in list)
            {
                if (item.EnterID > 0)
                {
                    item.EnterName = UserReidsCache.GetUserLoginInfo(item.EnterID)?.AccountName ?? "";
                }
                result.Add(new
                {
                    item.Id,
                    item.GuestName,
                    item.Mobile,
                    item.ClassId,
                    item.ClassName,
                    item.CourseId,
                    item.CourseName,
                    item.GuestState,
                    item.GuestStateStr,
                    item.School_Id,
                    item.Teacher_Id,
                    item.TotalPlanNum,
                    item.Ranks,
                    item.EnterName,
                    item.EnterID,
                    item.IsRenewOrder,
                    item.RenewOrderId
                });
            }
            return ApiResult.Success(data: result);
        }
        #endregion


        #region 上课反馈
        /// <summary>
        /// 获取上课详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetFeedBackDetails()
        {
            var ID = base.ParmJObj.GetInt("ID", 0);
            var timeModel = classModule.GetClassTimeList_V2(new RB_Class_Time_ViewModel { ClassTimeId = ID, Group_Id = base.UserInfo.Group_Id }).FirstOrDefault();
            if (timeModel == null || timeModel.ClassTimeId == 0)
            {
                return ApiResult.Failed("班级上课时间信息不存在");
            }
            var orderGuestList = classModule.GetOrderGuestListModule(new RB_Order_Guest_ViewModel { Group_Id = base.UserInfo.Group_Id, School_Id = 0, ClassId = timeModel.ClassId });

            var tempOrderGuestList = classModule.GetTempInvitationGuest(new Model.ViewModel.EduTask.RB_Temporary_Invitation_ViewModel { ClassTimeId = ID, ClassId = timeModel.ClassId });

            var allOrderGuestList = new List<RB_Order_Guest_ViewModel>();
            allOrderGuestList.AddRange(orderGuestList.Where(x => x.GuestState == GuestStateEnum.Normal || x.GuestState == GuestStateEnum.StopClassesApplyIng || ((x.GuestState == GuestStateEnum.StopClasses || x.GuestState == GuestStateEnum.Graduate) && x.ChangeEffectTime.HasValue && Convert.ToDateTime(Common.ConvertHelper.FormatDate(x.ChangeEffectTime)) >= Convert.ToDateTime(Common.ConvertHelper.FormatDate(timeModel.NewPlanDateTime)))));

            var feedBackList = classModule.GetClassFeedBackList(new RB_Class_FeedBack_ViewModel { ClassTimeId = ID, Group_Id = base.UserInfo.Group_Id, ClassId = timeModel.ClassId });
            if (tempOrderGuestList != null && tempOrderGuestList.Any())
            {
                allOrderGuestList.AddRange(tempOrderGuestList.Where(x => x.GuestState == GuestStateEnum.Normal || x.GuestState == GuestStateEnum.StopClassesApplyIng || ((x.GuestState == GuestStateEnum.StopClasses || x.GuestState == GuestStateEnum.Graduate) && x.ClassTimeId == ID && x.ClassId == timeModel.ClassId && x.ChangeEffectTime.HasValue && Convert.ToDateTime(Common.ConvertHelper.FormatDate(x.ChangeEffectTime)) >= Convert.ToDateTime(Common.ConvertHelper.FormatDate(timeModel.NewPlanDateTime)))));
            }
            List<object> result = new List<object>();
            foreach (var item in allOrderGuestList)
            {
                var FeedBackModel = feedBackList.Where(y => y.OrderGuestId == item.Id).FirstOrDefault();
                if (FeedBackModel != null && FeedBackModel.FeedBackId > 0)
                {
                    if (!string.IsNullOrWhiteSpace(FeedBackModel.Photo))
                    {
                        FeedBackModel.PhotoList = JsonHelper.DeserializeObject<List<string>>(FeedBackModel.Photo);
                    }
                    else {
                        FeedBackModel.PhotoList = new List<string>();
                    }
                }
                var guest = new
                {
                    timeModel.ClassPlanId,
                    timeModel.ClassId,
                    timeModel.ClassTimeId,
                    item.GuestName,
                    item.Mobile,
                    item.Teacher_Id,
                    item.School_Id,
                    OrderGuestId = item.Id,
                    Score = FeedBackModel?.Score ?? 0,
                    Comment = FeedBackModel?.Comment ?? "",
                    PhotoList = FeedBackModel?.PhotoList ?? new List<string>(),
                    FeedBackId = FeedBackModel?.FeedBackId ?? 0,
                    TeacherName = FeedBackModel?.TeacherName ?? "",
                    TeacherIcon = FeedBackModel?.TeacherIcon ?? "",
                    CreateTimeStr = (FeedBackModel != null && FeedBackModel.FeedBackId > 0) ? FeedBackModel.CreateTime.ToString("yyyy-MM-dd HH:mm") : ""
                };
                result.Add(guest);
            }
            return ApiResult.Success("", result);
        }

        /// <summary>
        /// 老师上课反馈填写
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetFeedBack()
        {
            List<RB_Class_FeedBack_ViewModel> list = new List<RB_Class_FeedBack_ViewModel>();
            JArray array = JArray.Parse(RequestParm.Msg.ToString());
            if (array != null && array.Count > 0)
            {
                foreach (var jItem in array)
                {
                    JObject obj = JObject.Parse(jItem.ToString());
                    var nowModel = new RB_Class_FeedBack_ViewModel()
                    {
                        OrderGuestId = obj.GetInt("OrderGuestId"),
                        ClassTimeId = obj.GetInt("ClassTimeId"),
                        ClassPlanId = obj.GetInt("ClassPlanId"),
                        School_Id = obj.GetInt("School_Id"),
                        Score = obj.GetInt("Score"),
                        TeacherId = obj.GetInt("TeacherId"),
                        ClassId = obj.GetInt("ClassId"),
                        Comment = obj.GetStringValue("Comment")
                    };
                    List<string> photoList = JsonHelper.DeserializeObject<List<string>>(obj.GetStringValue("PhotoList"));
                    if (photoList != null && photoList.Any())
                    {
                        nowModel.Photo = JsonHelper.Serialize(photoList);
                    }
                    else
                    {
                        nowModel.Photo = "";
                    }
                    list.Add(nowModel);
                }
            }
            if (list == null || !list.Any())
            {
                return ApiResult.ParamIsNull(message: "请选择上课反馈学员!");
            }


            //判断当天是否有已反馈数据
            var classFeedBackList = classModule.GetClassFeedBackList(new RB_Class_FeedBack_ViewModel
            {
                Group_Id = base.UserInfo.Group_Id,
                ClassId = list.FirstOrDefault().ClassId,
                ClassTimeId = list.FirstOrDefault().ClassTimeId,
            });
            foreach (var item in list)
            {
                var signModel = classFeedBackList?.Where(qitem => qitem.ClassId == item.ClassId && qitem.OrderGuestId == item.OrderGuestId)?.FirstOrDefault();
                if (signModel != null && signModel.FeedBackId > 0)
                {
                    item.FeedBackId = signModel.FeedBackId;
                    item.Group_Id = signModel.Group_Id;
                    item.CreateTime = signModel.CreateTime;
                    item.CreateBy = base.UserInfo.Id;
                    item.Status = 0;
                }
                else
                {
                    item.Group_Id = base.UserInfo.Group_Id;
                    item.CreateTime = System.DateTime.Now;
                    item.CreateBy = base.UserInfo.Id;
                    item.Status = 0;
                }
            }
            bool result = classModule.SetFeedBack(list);

            return result ? ApiResult.Success() : ApiResult.Failed("上课反馈失败");
        }
        #endregion
    }
}
