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.Enum.System;
using Edu.Common.Plugin;
using Edu.Model.ViewModel.Course;
using Edu.Module.Course;
using Edu.WebApi.Filter;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

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

        #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"),
                ClassNo = base.ParmJObj.GetStringValue("ClassNo")
            };
            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.CouseId,
                    item.CourseName,
                    item.Teacher_Id,
                    item.TeacherName,
                    item.ClassPersion,
                    item.OrderStudentCount,
                    OpenTime = Common.ConvertHelper.FormatDate(item.OpenTime),
                    item.CompleteProgress,
                    item.ClassStatusStr,
                    item.NewPlanDateTime,
                    item.ClassStatus,
                    item.Status,
                    item.OtherCourseList,
                    item.ClassNo,
                    item.FinishTimeStr
                });
            }
            pageModel.Count = rowsCount;
            pageModel.PageData = result;
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 获取班级列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetClassListForProperty()
        {
            var query = new RB_Class_ViewModel()
            {
                CouseId = base.ParmJObj.GetInt("CourseId"),
                School_Id = base.ParmJObj.GetInt("School_Id", -1)
            };
            query.Group_Id = base.UserInfo.Group_Id;
            var list = classModule.GetClassListForProperty(query);
            if (list == null)
            {
                list = new List<RB_Class_ViewModel>();
            }
            return ApiResult.Success(data: list.Select(qitem => new
            {
                qitem.ClassId,
                qitem.ClassName,
                qitem.CourseName
            }));
        }

        /// <summary>
        /// 获取班级列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetClassList()
        {
            //是够添加默选项
            int IsAddDefault = base.ParmJObj.GetInt("IsAddDefault");
            var query = new RB_Class_ViewModel()
            {
                CouseId = base.ParmJObj.GetInt("CourseId", 0),
                IsQuerySurplus = base.ParmJObj.GetInt("IsQuerySurplus"),

                MoreStatus = base.ParmJObj.GetStringValue("MoreStatus"),
                Teacher_Id = base.ParmJObj.GetInt("Teacher_Id"),
                IsQuerySurplusPlan = base.ParmJObj.GetInt("IsQuerySurplusPlan")
            };
            query.School_Id = base.ParmJObj.GetInt("SchoolId", -1);
            query.Group_Id = base.UserInfo.Group_Id;

            var list = classModule.GetClassListModule(query);

            List<object> result = new List<object>();
            foreach (var item in list)
            {
                List<object> planList = new List<object>();
                if (item.ClassPlanList != null && item.ClassPlanList.Count > 0)
                {
                    foreach (var subItem in item.ClassPlanList)
                    {
                        var subObj = new
                        {
                            subItem.ClassPlanId,
                            ClassDate = Common.ConvertHelper.FormatDate(subItem.ClassDate),
                            subItem.WeekDayStr,
                            subItem.ClassRoomId,
                            subItem.RoomName,
                            subItem.TeacherId,
                            subItem.TeacherName,
                            TimeList = subItem?.PlanTimeList?.Select(qitem => new { qitem.ClassTimeId, qitem.StartTime, qitem.EndTime, qitem.TimeHour })
                        };
                        planList.Add(subObj);
                    }
                }
                var obj = new
                {
                    item.ClassId,
                    item.ClassName,
                    item.CouseId,
                    item.CourseName,
                    OpenTime = Common.ConvertHelper.FormatDate(item.OpenTime),
                    PlanList = planList
                };
                result.Add(obj);
            }
            return ApiResult.Success(data: result);
        }

        /// <summary>
        /// 添加修改班级
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetClass()
        {
            var extModel = new RB_Class_ViewModel()
            {
                ClassId = base.ParmJObj.GetInt("ClassId"),
                CreateBy = UserInfo.Id,
                CreateTime = DateTime.Now,
                UpdateBy = UserInfo.Id,
                UpdateTime = DateTime.Now,
                Group_Id = this.UserInfo.Group_Id,
                ClassName = base.ParmJObj.GetStringValue("ClassName"),
                CouseId = base.ParmJObj.GetInt("CouseId"),
                Teacher_Id = base.ParmJObj.GetInt("Teacher_Id"),
                Assist_Id = base.ParmJObj.GetInt("Assist_Id"),
                ClassPersion = base.ParmJObj.GetInt("ClassPersion"),
                OpenTime = base.ParmJObj.GetDateTime("OpenTime"),
                EndOrderTime = base.ParmJObj.GetDateTime("EndOrderTime"),
                OriginalPrice = base.ParmJObj.GetDecimal("OriginalPrice"),
                SellPrice = base.ParmJObj.GetDecimal("SellPrice"),
                IsStepPrice = base.ParmJObj.GetInt("IsStepPrice"),
                ClassRoomId = base.ParmJObj.GetInt("ClassRoomId"),
                IsOpenCommission = base.ParmJObj.GetInt("IsOpenCommission"),
                CommissionType = base.ParmJObj.GetInt("CommissionType"),
                CommissionValue = base.ParmJObj.GetDecimal("CommissionValue"),
                ClassHours = base.ParmJObj.GetInt("ClassHours"),
                ClassStyle = (ClassStyleEnum)base.ParmJObj.GetInt("ClassStyle"),
                ClassStatus = ClassStatusEnum.NonOpenClass,
                InnerRemark = base.ParmJObj.GetStringValue("InnerRemark"),
                OutRemark = base.ParmJObj.GetStringValue("OutRemark"),
                School_Id = base.ParmJObj.GetInt("School_Id"),
                ClassType = base.ParmJObj.GetInt("ClassType"),
                IsSubscribe = base.ParmJObj.GetInt("IsSubscribe"),
                IsDeduction = base.ParmJObj.GetInt("IsDeduction"),
                Point = base.ParmJObj.GetInt("Point"),
                CourseClassType = (CourseClassTypeEnum)base.ParmJObj.GetInt("CourseClassType"),
                StudentNumType = (StudentNumTypeEnum)base.ParmJObj.GetInt("StudentNumType"),
                ClassHourMinute = base.ParmJObj.GetInt("ClassHourMinute"),
            };
            try
            {
                string ClassStepPriceListStr = base.ParmJObj.GetStringValue("ClassStepPriceList");
                if (!string.IsNullOrEmpty(ClassStepPriceListStr))
                {
                    extModel.ClassStepPriceList = Common.Plugin.JsonHelper.DeserializeObject<List<RB_Class_StepPrice_ViewModel>>(ClassStepPriceListStr);
                }
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "SetClass_ClassStepPriceList");
            }
            //排课方式
            try
            {
                string WeekDayListStr = base.ParmJObj.GetStringValue("WeekDayList");
                switch (extModel.ClassStyle)
                {
                    //按周排课
                    case ClassStyleEnum.Week:
                        if (!string.IsNullOrEmpty(WeekDayListStr))
                        {
                            extModel.WeekDayList = Common.Plugin.JsonHelper.DeserializeObject<List<string>>(WeekDayListStr);
                            extModel.DateJson = Common.Plugin.JsonHelper.Serialize(extModel.WeekDayList);
                        }
                        else
                        {
                            extModel.DateJson = "";
                        }
                        break;
                    //固定日期排课
                    case ClassStyleEnum.FixedDate:
                        if (!string.IsNullOrEmpty(WeekDayListStr))
                        {
                            extModel.WeekDayList = Common.Plugin.JsonHelper.DeserializeObject<List<string>>(WeekDayListStr);
                            extModel.DateJson = Common.Plugin.JsonHelper.Serialize(extModel.WeekDayList);
                        }
                        else
                        {
                            extModel.DateJson = "";
                        }
                        break;
                    //按月排课
                    case ClassStyleEnum.Month:
                        if (!string.IsNullOrEmpty(WeekDayListStr))
                        {
                            extModel.WeekDayList = Common.Plugin.JsonHelper.DeserializeObject<List<string>>(WeekDayListStr);
                            extModel.DateJson = Common.Plugin.JsonHelper.Serialize(extModel.WeekDayList);
                        }
                        else
                        {
                            extModel.DateJson = "";
                        }
                        break;
                    //网约课
                    case ClassStyleEnum.OnLine:
                        extModel.DateJson = "";
                        break;
                }
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "SetClass_WeekDayList");
            }
            try
            {
                string DefaultPlanTimeListStr = base.ParmJObj.GetStringValue("DefaultPlanTimeList");
                if (!string.IsNullOrEmpty(DefaultPlanTimeListStr))
                {
                    extModel.DefaultTimeList = Common.Plugin.JsonHelper.DeserializeObject<List<ClassTimeItem>>(DefaultPlanTimeListStr);
                }
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "SetClass_DefaultPlanTimeList");
            }
            List<string> dayList = new List<string>();
            if (extModel.DefaultTimeList != null && extModel.DefaultTimeList.Count > 0)
            {
                foreach (var rootItem in extModel.DefaultTimeList)
                {
                    if (rootItem.DateList == null || (rootItem.DateList != null && rootItem.DateList.Count == 0))
                    {
                        return ApiResult.ParamIsNull(message: "请选择日期/周");
                    }
                    if (rootItem.DateList != null && rootItem.DateList.Count > 0)
                    {
                        dayList.AddRange(rootItem.DateList);
                    }
                    foreach (var item in rootItem.TimeList)
                    {
                        string message = "";
                        if (!Common.ConvertHelper.IsTime(item.StartTime + ":00"))
                        {
                            message = "【" + item.StartTime + "】格式不正确!(参考格式为 00:00)";
                        }
                        if (!Common.ConvertHelper.IsTime(item.EndTime + ":00"))
                        {
                            if (!string.IsNullOrEmpty(message))
                            {
                                message += ",";
                            }
                            message += "【" + item.EndTime + "】格式不正确!(参考格式为 00:00)";
                        }
                        var startDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + item.StartTime + ":00");
                        var endDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + item.EndTime + ":00");
                        TimeSpan span = endDate.Subtract(startDate);
                        if (item.TimeHour <= 0)
                        {
                            item.TimeHour = Convert.ToDecimal(span.TotalMinutes / classModule.GetBasicMinutesModule(extModel.Group_Id));
                        }
                        if (!string.IsNullOrEmpty(message))
                        {
                            return ApiResult.ParamIsNull(message: message);
                        }
                    }
                }
                var tempList = dayList.GroupBy(qitem => new { qitem }).Where(g => g.Count() > 1).Select(qitem => new { qitem.Key.qitem });
                string message2 = "";
                foreach (var sItem in tempList)
                {
                    message2 += "," + sItem.qitem;
                }
                if (!string.IsNullOrEmpty(message2))
                {
                    string tempStr = "";
                    if (extModel.ClassStyle == ClassStyleEnum.Week)
                    {
                        tempStr = "每周";
                    }
                    if (extModel.ClassStyle == ClassStyleEnum.Month)
                    {
                        tempStr = "每月";
                    }
                    if (extModel.ClassStyle == ClassStyleEnum.FixedDate)
                    {
                        tempStr = "固定日期";
                    }
                    return ApiResult.ParamIsNull(message: "学习时间段" + (tempStr) + message2.TrimStart(',') + "重复!");
                }
                extModel.DefaultTimeJson = Common.Plugin.JsonHelper.Serialize(extModel.DefaultTimeList);
            }
            else
            {
                extModel.DefaultTimeJson = "";
            }
            bool flag = classModule.SetClassModule(extModel);
            if (flag)
            {
                classModule.UpdateClassEndDateModule(extModel.ClassId);
            }
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult InitData()
        {
            bool flag = classModule.InitDataModule();
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 修改班级状态
        /// </summary>
        /// <returns></returns>
        public ApiResult SetClassStatus()
        {
            var extModel = new RB_Class_ViewModel()
            {
                ClassId = base.ParmJObj.GetInt("ClassId"),
                ClassStatus = (ClassStatusEnum)base.ParmJObj.GetInt("ClassStatus"),
            };
            if (extModel.ClassId <= 0)
            {
                return ApiResult.ParamIsNull(message: "未获取到班级编号,请刷新页面重试!");
            }
            bool flag = classModule.SetClassStatusModule(extModel.ClassStatus, extModel.ClassId);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 获取班级实体
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetClass()
        {
            var ClassId = base.ParmJObj.GetInt("ClassId", 0);
            var extModel = classModule.GetClassModule(ClassId);
            var obj = new
            {
                ClassId = extModel?.ClassId ?? 0,
                ClassName = extModel?.ClassName ?? "",
                Assist_Id = extModel?.Assist_Id ?? 0,
                ClassHours = extModel?.ClassHours ?? 0,
                ClassPersion = extModel?.ClassPersion ?? 0,
                ClassPlanList = extModel?.ClassPlanList ?? new List<RB_Class_Plan_ViewModel>(),
                ClassRoomId = extModel?.ClassRoomId ?? 0,
                ClassStatus = extModel?.ClassStatus ?? ClassStatusEnum.NonOpenClass,
                ClassStyle = extModel?.ClassStyle ?? ClassStyleEnum.Week,
                ClassTimeList = extModel?.ClassTimeList ?? new List<RB_Class_Time_ViewModel>(),
                ClassType = extModel?.ClassType ?? 1,
                CommissionType = extModel?.CommissionType ?? 1,
                CommissionValue = extModel?.CommissionValue ?? 0,
                CouseId = extModel?.CouseId ?? 0,
                CourseName = extModel?.CourseName ?? "",
                DateJson = extModel?.DateJson ?? "",
                DefaultTimeJson = extModel?.DefaultTimeJson ?? "",
                DefaultPlanTimeList = extModel?.DefaultTimeList ?? new List<ClassTimeItem>(),
                DefaultTimeList = extModel?.DefaultTimeList ?? new List<ClassTimeItem>(),
                EndClassDate = Common.ConvertHelper.FormatDate(extModel?.EndClassDate),
                EndOrderTime = Common.ConvertHelper.FormatDate(extModel?.EndOrderTime),
                EndTime = Common.ConvertHelper.FormatDate(extModel?.EndTime),
                InnerRemark = extModel?.InnerRemark ?? "",
                IsOpenCommission = extModel?.IsOpenCommission ?? 0,
                IsStepPrice = extModel?.IsStepPrice ?? 0,
                NewPlanDateTime = extModel?.NewPlanDateTime ?? "",
                OpenTime = Common.ConvertHelper.FormatDate(extModel?.OpenTime),
                OrderStudentCount = extModel?.OrderStudentCount ?? 0,
                OriginalPrice = extModel?.OriginalPrice ?? 0,
                OutRemark = extModel?.OutRemark ?? "",
                SellPrice = extModel?.SellPrice ?? 0,
                Teacher_Id = extModel?.Teacher_Id ?? 0,
                TeacherName = extModel?.TeacherName ?? "",
                School_Id = extModel?.School_Id ?? 0,
                ClassStepPriceList = extModel?.ClassStepPriceList ?? new List<RB_Class_StepPrice_ViewModel>(),
                WeekDayList = extModel?.WeekDayList ?? new List<string>(),
                CompleteProgress = extModel?.CompleteProgress ?? 0,
                ClassStatusStr = extModel?.ClassStatusStr ?? "",
                ClassHourMinute = extModel?.ClassHourMinute ?? 45,
            };
            return ApiResult.Success(data: obj);
        }

        /// <summary>
        /// 删除班级
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult RemoveClass()
        {
            var ClassId = base.ParmJObj.GetInt("ClassId", 0);
            int Status = base.ParmJObj.GetInt("Status", 1);
            var flag = classModule.RemoveClassModule(ClassId, Status, out string message);
            return flag ? ApiResult.Success(message: message) : ApiResult.Failed(message: message);
        }


        /// <summary>
        /// 获取课程班级课程类型
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCourseClassTypeEnumList()
        {
            var list = Common.Plugin.EnumHelper.EnumToList(typeof(CourseClassTypeEnum));
            return ApiResult.Success(data: list);
        }

        /// <summary>
        /// 获取学生人数枚举类型
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetStudentNumTypeEnumList()
        {
            var list = Common.Plugin.EnumHelper.EnumToList(typeof(StudentNumTypeEnum));
            return ApiResult.Success(data: list);
        }
        #endregion

        #region 班级关联课程管理

        /// <summary>
        /// 添加修改班级
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetClassCourse()
        {
            JArray jarray = JArray.Parse(base.ParmJObj.GetStringValue("courseMsg"));
            List<RB_Class_Course_Extend> list = new List<RB_Class_Course_Extend>();
            if (jarray != null && jarray.Count > 0)
            {
                foreach (var jItem in jarray)
                {
                    JObject jobj = JObject.Parse(jItem.ToString());
                    var extModel = new RB_Class_Course_Extend()
                    {
                        Id = jobj.GetInt("Id"),
                        ClassId = jobj.GetInt("ClassId"),
                        CourseId = jobj.GetInt("CourseId"),
                        CourseName = jobj.GetStringValue("CourseName"),
                        CreateBy = UserInfo.Id,
                        CreateTime = DateTime.Now,
                        UpdateBy = UserInfo.Id,
                        UpdateTime = DateTime.Now,
                        Group_Id = this.UserInfo.Group_Id,
                        School_Id = this.UserInfo.School_Id,
                        Status = Common.Enum.DateStateEnum.Normal
                    };
                    list.Add(extModel);
                }
            }
            else
            {
                return ApiResult.ParamIsNull(message: "请选择要关联的课程!");
            }
            var groupList = list.GroupBy(qitem => new { qitem.CourseId, qitem.CourseName }).Where(qitem => qitem.Count() > 1).Select(qitem => new { qitem.Key.CourseId, qitem.Key.CourseName });
            string message = "";
            if (groupList != null && groupList.Count() > 0)
            {
                foreach (var item in groupList)
                {
                    message += "," + item.CourseName + "、";
                }
            }
            if (!string.IsNullOrEmpty(message))
            {
                return ApiResult.ParamIsNull(message: message.TrimStart(',').TrimEnd('、') + "重复!请删除后再提交!");
            }
            var classModel = classModule.GetClassModule(list[0].ClassId);
            if (list.Where(qitem => qitem.CourseId == classModel.CouseId).Count() > 0)
            {
                var model = list.Where(qitem => qitem.CourseId == classModel.CouseId)?.FirstOrDefault();
                return ApiResult.ParamIsNull(message: string.Format("此班级已绑定{0}课程,请删除后再提交!", (model?.CourseName ?? "")));
            }
            bool flag = classModule.SetClassCourseModule(list);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 获取班级关联课程列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetClassCourseList()
        {
            var query = new RB_Class_Course_Extend()
            {
                ClassId = base.ParmJObj.GetInt("ClassId"),
            };
            var list = classModule.GetClassCourseListModule(query);
            return ApiResult.Success(data: list.Select(qitem => new
            {
                qitem.Id,
                qitem.ClassId,
                qitem.CourseName,
                qitem.CourseId,
                qitem.ClassHours,
                qitem.SellPrice,
            }));
        }

        /// <summary>
        /// 删除班级关联课程
        /// </summary>
        /// <returns></returns>
        public ApiResult RemoveClassCourse()
        {
            var extModel = new RB_Class_Course_Extend()
            {
                Id = base.ParmJObj.GetInt("Id"),
            };
            if (extModel.Id <= 0)
            {
                return ApiResult.ParamIsNull(message: "未获取到班级关联课程编号,请刷新页面重试!");
            }
            bool flag = classModule.RemoveClassCourseModule(extModel.Id, out string message);
            return flag ? ApiResult.Success(message: message) : ApiResult.Failed(message: message);
        }
        #endregion

        #region 上课计划
        /// <summary>
        /// 获取上课计划
        /// </summary>
        /// <returns></returns>
        public ApiResult GetAllClassPlan()
        {
            var query = new RB_Class_Plan_ViewModel()
            {
                ClassId = base.ParmJObj.GetInt("ClassId"),
                QMonth = base.ParmJObj.GetStringValue("QMonth"),
                TeacherId = base.ParmJObj.GetInt("TeacherId"),
                Group_Id = base.UserInfo.Group_Id,
                School_Id = base.ParmJObj.GetInt("School_Id", -1),
            };
            var data = classModule.GetClassPlan_V2(query);
            return ApiResult.Success(data: data);
        }

        /// <summary>
        /// 获取上课计划
        /// </summary>
        /// <returns></returns>
        public ApiResult GetClassPlan()
        {
            var query = new RB_Class_ViewModel()
            {
                ClassId = base.ParmJObj.GetInt("ClassId"),
                QMonth = base.ParmJObj.GetStringValue("QMonth"),
            };
            var data = classModule.GetClassPlanModule(query.ClassId, query.QMonth);
            return ApiResult.Success(data: data);
        }

        /// <summary>
        /// 删除上课计划
        /// </summary>
        /// <returns></returns>
        public ApiResult RemoveClassPlan()
        {
            var ClassPlanId = base.ParmJObj.GetInt("ClassPlanId");
            var flag = classModule.RemoveClassPlanModule(ClassPlanId, base.UserInfo, out string message);
            return flag ? ApiResult.Success() : ApiResult.Failed(message: message);
        }

        /// <summary>
        /// 新增修改班级计划
        /// </summary>
        /// <returns></returns>
        public ApiResult SetClassPlan()
        {
            var extModel = new RB_Class_Plan_ViewModel()
            {
                ClassPlanId = base.ParmJObj.GetInt("ClassPlanId"),
                ClassId = base.ParmJObj.GetInt("ClassId"),
                ClassDate = base.ParmJObj.GetDateTime("ClassDate"),
                Status = Common.Enum.DateStateEnum.Normal,
                ClassRoomId = base.ParmJObj.GetInt("ClassRoomId"),
                TeacherId = base.ParmJObj.GetInt("TeacherId"),
                Group_Id = base.UserInfo.Group_Id,
            };
            if (classModule.CheckPlanModule(extModel))
            {
                return ApiResult.Failed(message: "已经存在【" + Common.ConvertHelper.FormatDate(extModel.ClassDate) + "】的上课安排!请删除后再操作!");
            }
            extModel.School_Id = classModule.GetClassModule(extModel.ClassId)?.School_Id ?? 0;
            try
            {
                extModel.PlanTimeList = Common.Plugin.JsonHelper.DeserializeObject<List<RB_Class_Time_ViewModel>>(base.ParmJObj.GetStringValue("PlanTimeList"));
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "SetClassPlan_PlanTimeList");
            }
            if (extModel.PlanTimeList != null && extModel.PlanTimeList.Count > 0)
            {
                foreach (var item in extModel.PlanTimeList)
                {
                    string message = "";
                    if (!Common.ConvertHelper.IsTime(item.StartTime + ":00"))
                    {
                        message = "【" + item.StartTime + "】格式不正确!(参考格式为 00:00)";
                    }
                    if (!Common.ConvertHelper.IsTime(item.EndTime + ":00"))
                    {
                        if (!string.IsNullOrEmpty(message))
                        {
                            message += ",";
                        }
                        message += "【" + item.EndTime + "】格式不正确!(参考格式为 00:00)";
                    }
                    if (!string.IsNullOrEmpty(message))
                    {
                        return ApiResult.ParamIsNull(message: message);
                    }
                }
            }
            var flag = classModule.SetClassPlanModule(extModel, base.UserInfo.Id);
            if (flag)
            {
                classModule.UpdateClassEndDateModule(extModel.ClassId);
            }
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }


        #endregion

        #region 学员信息
        /// <summary>
        /// 获取学员列表
        /// </summary>
        /// <returns></returns>
        public ApiResult GetClassStudent()
        {
            var classId = base.ParmJObj.GetInt("ClassId");
            var schoolId = 0;
            int QEffectStatus = base.ParmJObj.GetInt("QEffectStatus");
            //var schoolId = base.ParmJObj.GetInt("School_Id");
            var data = classModule.GetClassStudentListModule(classId, schoolId, base.UserInfo.Group_Id, 0, QEffectStatus: QEffectStatus);
            return ApiResult.Success(data: data);
        }


        /// <summary>
        /// 获取某一天的上课计划列表
        /// </summary>
        /// <returns></returns>
        public ApiResult GetDayClassPlan()
        {
            var classId = base.ParmJObj.GetInt("ClassId");
            var classPlanId = base.ParmJObj.GetInt("ClassPlanId");
            var schoolId = base.ParmJObj.GetInt("School_Id");
            var ClassTimeId = base.ParmJObj.GetInt("ClassTimeId");
            if (classId == 0 || classPlanId == 0)
            {
                return ApiResult.ParamIsNull();
            }
            var data = classModule.GetClassPlanListExtModule(new RB_Class_Plan_ViewModel
            {
                ClassId = classId,
                ClassPlanId = classPlanId,
                Group_Id = base.UserInfo.Group_Id,
                School_Id = schoolId,
                ClassTimeId = ClassTimeId
            }).FirstOrDefault();
            if (data == null || data.ClassPlanId == 0)
            {
                return ApiResult.Failed("数据不存在");
            }
            double totalMinutes = 0;
            var planTimeList = classModule.GetClassTimeListModule(new RB_Class_Time_ViewModel { ClassId = classId, ClassPlanId = classPlanId, Group_Id = base.UserInfo.Group_Id, School_Id = schoolId, ClassTimeId = ClassTimeId });
            if (planTimeList != null && planTimeList.Any())
            {
                foreach (var item in planTimeList)
                {
                    if (!string.IsNullOrWhiteSpace(item.StartTime) && !string.IsNullOrWhiteSpace(item.EndTime))
                    {
                        System.TimeSpan timeInfo = Convert.ToDateTime(data.ClassDate.ToString("yyyy-MM-dd") + " " + item.EndTime) - Convert.ToDateTime(data.ClassDate.ToString("yyyy-MM-dd") + " " + item.StartTime);
                        totalMinutes += timeInfo.TotalMinutes;
                    }
                }
            }
            var orderGuestList = classModule.GetOrderGuestListModule(new RB_Order_Guest_ViewModel { Group_Id = base.UserInfo.Group_Id, School_Id = 0, ClassId = data.ClassId, QEffectStatus = 1 });
            var checkLogList = classModule.GetClassCheckList(new RB_Class_Check_ViewModel
            {
                Group_Id = data.Group_Id,
                School_Id = data.School_Id,
                ClassId = data.ClassId,
                StartDate = data.ClassDate.ToString("yyyy-MM-dd HH:mm:ss"),
                EndDate = data.ClassDate.ToString("yyyy-MM-dd HH:mm:ss"),
                ClassTimeId = ClassTimeId,
            });
            List<object> guestList = new List<object>();
            foreach (var item in orderGuestList.Where(x => x.GuestState == 1 || x.GuestState == 6 || ((x.GuestState == 5 || x.GuestState == 7) && x.ChangeEffectTime.HasValue && Convert.ToDateTime(Common.ConvertHelper.FormatDate(x.ChangeEffectTime)) >= data.ClassDate)))
            {
                if (item.IsChaBan == 0 || (item.IsChaBan == 1 && data.ClassDate >= Convert.ToDateTime(Common.ConvertHelper.FormatDate(item.EffectTime))))
                {
                    guestList.Add(new
                    {
                        UserIcon = "",
                        item.Id,
                        SexStr = item.Sex == 1 ? "男" : "女",
                        item.GuestName,
                        item.Age,
                        CreateTimeStr = Common.ConvertHelper.FormatTime(item.CreateTime),
                        item.Mobile,
                        item.OrderId,
                        item.CourseName,
                        item.CourseId,
                        item.TotalHours,
                        item.CompleteHours,
                        item.StartClassHours,
                        item.IsChaBan,
                        item.EffectStatus,
                        item.EffectStatusStr,
                        EffectTime = Common.ConvertHelper.FormatDate(item.EffectTime),
                        item.UpOrderId,
                        IsCheck = (checkLogList != null && checkLogList.Any()) ? checkLogList.Where(x => x.OrderGuestId == item.Id).FirstOrDefault()?.CheckStatus ?? -1 : -1,
                        StudyNum = (checkLogList != null && checkLogList.Any()) ? checkLogList.Where(x => x.OrderGuestId == item.Id).FirstOrDefault()?.StudyNum ?? 0 : 0
                    });
                }
            }
            var classMinutes = classModule.GetClassMinutesModule(classId);
            return ApiResult.Success(data: new
            {
                data.TeacherName,
                data.RoomName,
                TotalHour = Convert.ToDecimal(totalMinutes / 60.0),
                ClassNum = Convert.ToInt32(totalMinutes / classMinutes),
                DefaultMinutes = totalMinutes,
                ClassDate = data.ClassDate.ToString("yyyy-MM-dd"),
                GuestList = guestList
            });
        }

        /// <summary>
        /// 更新学生的退课状态
        /// </summary>
        /// <returns></returns>
        public ApiResult UpdateClassStudentDropOut()
        {
            var classId = base.ParmJObj.GetInt("ClassId");
            var ids = base.ParmJObj.GetStringValue("Ids");
            var dropOutRemark = base.ParmJObj.GetStringValue("DropOutRemark");
            var studentName = base.ParmJObj.GetStringValue("StudentName");
            if (string.IsNullOrWhiteSpace(ids) || string.IsNullOrWhiteSpace(dropOutRemark) || classId == 0 || string.IsNullOrWhiteSpace(studentName))
            {
                return ApiResult.ParamIsNull("");
            }
            var classModel = classModule.GetClassListModule(new RB_Class_ViewModel { ClassId = classId, Group_Id = base.UserInfo.Group_Id }).FirstOrDefault();
            if (classModel == null)
            {
                return ApiResult.Failed("班级信息不存在");
            }
            bool result = classModule.UpdateClassStudentDropOutModule(ids, dropOutRemark, classId, base.UserInfo.Id, classModel.Group_Id, classModel.School_Id, studentName);
            return result ? ApiResult.Success() : ApiResult.Failed();
        }



        /// <summary>
        /// 邀请学生
        /// </summary>
        /// <returns></returns>
        public ApiResult AddClassStudent()
        {
            var model = Common.Plugin.JsonHelper.DeserializeObject<RB_Order_Guest_ViewModel>(RequestParm.Msg.ToString());
            if (!string.IsNullOrWhiteSpace(model.BirthDay))
            {
                model.Age = System.DateTime.Now.Year - Convert.ToDateTime(model.BirthDay).Year;
            }
            model.GuestState = 1;
            model.GuestSource = OrderSourceEnum.Employee;
            model.CreateBy = base.UserInfo.Id;
            model.UpdateBy = base.UserInfo.Id;
            model.CreateTime = System.DateTime.Now;
            model.UpdateTime = model.CreateTime;
            model.Group_Id = base.UserInfo.Group_Id;
            bool result = classModule.AddClassStudentDropOutModule(model, base.UserInfo.AccountName);
            return result ? ApiResult.Success() : ApiResult.Failed();
        }
        /// <summary>
        /// 获取教室页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetClassPlanLogPageList()
        {
            var pageModel = Common.Plugin.JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Class_Plan_ViewModel()
            {
                Group_Id = base.UserInfo.Group_Id,
                //School_Id = base.ParmJObj.GetInt("School_Id"),
                ClassId = base.ParmJObj.GetInt("ClassId"),
                TeacherId = base.ParmJObj.GetInt("TeacherId")
            };
            var list = classModule.GetClassPlanLogPageListModule(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);

            pageModel.Count = rowsCount;
            pageModel.PageData = list;
            return ApiResult.Success(data: pageModel);
        }


        /// <summary>
        /// 多人签到【后台】
        /// </summary>
        /// <returns></returns>
        public ApiResult AddClassCheck()
        {
            List<RB_Class_Check_ViewModel> list = new List<RB_Class_Check_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());
                    list.Add(new RB_Class_Check_ViewModel()
                    {
                        CheckStatus = obj.GetInt("CheckStatus"),
                        ClassDate = obj.GetDateTime("ClassDate"),
                        ClassRoomId = obj.GetInt("ClassRoomId"),
                        OrderGuestId = obj.GetInt("OrderGuestId"),
                        School_Id = obj.GetInt("School_Id"),
                        StudyNum = obj.GetInt("StudyNum"),
                        TeacherId = obj.GetInt("TeacherId"),
                        ClassId = obj.GetInt("classId"),
                        ClassTimeId = obj.GetInt("ClassTimeId"),
                    });
                }
            }
            if (list == null || !list.Any())
            {
                return ApiResult.ParamIsNull(message: "请选择签到学员!");
            }
            #region 验证是否已轧账
            string MonthStr = list.FirstOrDefault().ClassDate.ToString("yyyy-MM");
            int schoolId = list.FirstOrDefault().School_Id;
            string ValidateMsg = classModule.ValidateClassCheckFinance(MonthStr, schoolId, base.UserInfo.Group_Id);
            if (ValidateMsg != "")
            {
                return ApiResult.Failed(ValidateMsg);
            }
            #endregion

            //获取班级的学员信息
            var orderGuestList = classModule.GetOrderGuestListModule(new RB_Order_Guest_ViewModel { Group_Id = base.UserInfo.Group_Id, ClassId = list.FirstOrDefault().ClassId, QEffectStatus = 1 });
            if (list.Count() != orderGuestList.Where(x => x.GuestState == 1).Count())
            {
                // return ApiResult.Failed("签到总人数错误，请先检查信息");
            }

            //判断今天有课没有
            var planList = classModule.GetClassPlanModelRepository(new RB_Class_Plan_ViewModel
            {
                Group_Id = base.UserInfo.Group_Id,
                ClassId = list.FirstOrDefault().ClassId,
                QClassDateStr = Common.ConvertHelper.FormatDate(list.FirstOrDefault().ClassDate),
            });
            if (planList == null || !planList.Any())
            {
                return ApiResult.Failed("今日无课程，无须签到");
            }

            //判断当天是否有已签到数据
            var checkLogList = classModule.GetClassCheckList(new RB_Class_Check_ViewModel
            {
                Group_Id = base.UserInfo.Group_Id,
                ClassId = list.FirstOrDefault().ClassId,
                StartDate = list.FirstOrDefault().ClassDate.ToString("yyyy-MM-dd HH:mm:ss"),
                EndDate = list.FirstOrDefault().ClassDate.ToString("yyyy-MM-dd HH:mm:ss"),
                ClassTimeId = list.FirstOrDefault().ClassTimeId,
            });

            foreach (var item in list)
            {
                var signModel = checkLogList?.Where(qitem => qitem.ClassDate.ToString("yyyy-MM-dd") == item.ClassDate.ToString("yyyy-MM-dd") && qitem.ClassId == item.ClassId && qitem.OrderGuestId == item.OrderGuestId)?.FirstOrDefault();
                if (signModel != null && signModel.ClassCheckId > 0)
                {
                    item.ClassCheckId = signModel.ClassCheckId;
                    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.AddClassCheckModule(list);
            if (result)
            {
                classModule.SetClassProcessModule(list.FirstOrDefault().ClassId);
            }
            return result ? ApiResult.Success() : ApiResult.Failed("签到失败");
        }

        /// <summary>
        /// 签到
        /// </summary>
        /// <returns></returns>
        public ApiResult AddClassCheckOne()
        {
            List<RB_Class_Check_ViewModel> list = new List<RB_Class_Check_ViewModel>();

            var exModel = new RB_Class_Check_ViewModel()
            {
                CheckStatus = base.ParmJObj.GetInt("CheckStatus"),
                ClassDate = base.ParmJObj.GetDateTime("ClassDate"),
                ClassRoomId = base.ParmJObj.GetInt("ClassRoomId"),
                OrderGuestId = base.ParmJObj.GetInt("OrderGuestId"),
                School_Id = base.ParmJObj.GetInt("School_Id"),
                StudyNum = base.ParmJObj.GetInt("StudyNum"),
                TeacherId = base.ParmJObj.GetInt("TeacherId"),
                ClassId = base.ParmJObj.GetInt("classId"),
                ClassTimeId = base.ParmJObj.GetInt("ClassTimeId", 0),
            };
            exModel.ClassDate = Convert.ToDateTime(exModel.ClassDate.ToString("yyyy-MM-dd 00:00:00"));
            if (exModel.ClassTimeId == 0)
            {
                return ApiResult.Failed("上课时间ID不能等于0");
            }
            list.Add(exModel);
            if (list == null || !list.Any())
            {
                return ApiResult.ParamIsNull("");
            }

            //获取班级的学员信息
            var orderGuestList = classModule.GetOrderGuestListModule(new RB_Order_Guest_ViewModel { Group_Id = base.UserInfo.Group_Id, ClassId = exModel.ClassId });

            //判断今天有课没有
            var planList = classModule.GetClassPlanModelRepository(new RB_Class_Plan_ViewModel
            {
                Group_Id = base.UserInfo.Group_Id,
                ClassId = exModel.ClassId,
                QClassDateStr = Common.ConvertHelper.FormatDate(exModel.ClassDate),
            });
            if (planList == null || !planList.Any())
            {
                return ApiResult.Failed("今日无课程，无须签到");
            }

            //判断当天是否有已签到数据
            var checkLogList = classModule.GetClassCheckList(new RB_Class_Check_ViewModel { Group_Id = base.UserInfo.Group_Id, ClassId = list.FirstOrDefault().ClassId, ClassTimeId = exModel.ClassTimeId, StartDate = exModel.ClassDate.ToString("yyyy-MM-dd HH:mm:ss"), EndDate = exModel.ClassDate.ToString("yyyy-MM-dd HH:mm:ss") });

            foreach (var item in list)
            {
                var signModel = checkLogList?.Where(qitem => qitem.ClassTimeId == item.ClassTimeId && qitem.ClassId == item.ClassId && qitem.OrderGuestId == item.OrderGuestId)?.FirstOrDefault();
                if (signModel != null && signModel.ClassCheckId > 0)
                {
                    item.ClassCheckId = signModel.ClassCheckId;
                    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.AddClassCheckModule(list);
            if (result)
            {
                classModule.SetClassProcessModule(exModel.ClassId);
            }
            return result ? ApiResult.Success() : ApiResult.Failed("签到失败");
        }



        /// <summary>
        /// 获取缺课分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAbsentPage()
        {
            var pageModel = Common.Plugin.JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Student_Makeup_ViewModel()
            {
                MakeUpStatus = base.ParmJObj.GetInt("MakeUpStatus"),
                GuestName = base.ParmJObj.GetStringValue("GuestName"),
                ClassName = base.ParmJObj.GetStringValue("ClassName"),
                CourseName = base.ParmJObj.GetStringValue("CourseName"),
                TeacherName = base.ParmJObj.GetStringValue("TeacherName"),
                RoomName = base.ParmJObj.GetStringValue("RoomName"),
                StartDate = base.ParmJObj.GetStringValue("StartDate"),
                EndDate = base.ParmJObj.GetStringValue("EndDate"),
            };
            query.Group_Id = base.UserInfo.Group_Id;
            List<object> result = new List<object>();
            var list = classModule.GetStudentMakeupPageModule(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);
            foreach (var item in list)
            {
                result.Add(new
                {
                    item.Id,
                    item.ClassCheckId,
                    item.OrderGuestId,
                    item.GuestName,
                    item.GuestState,
                    item.GuestStateStr,
                    item.ClassId,
                    item.ClassName,
                    item.CourseName,
                    item.TeacherName,
                    item.RoomName,
                    ClassDate = Common.ConvertHelper.FormatDate(item.ClassDate),
                    item.MakeUpStatus,
                    item.MakeUpStatusStr,
                    item.StartTime,
                    item.EndTime,
                    DealByName = UserReidsCache.GetUserLoginInfo(item.DealBy)?.AccountName,
                    DealTime = Common.ConvertHelper.FormatTime(item.DealTime)
                });
            }
            pageModel.Count = rowsCount;
            pageModel.PageData = result;
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 修改补课状态
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMakeUpStatus()
        {
            int Id = base.ParmJObj.GetInt("Id");
            int MakeUpStatus = base.ParmJObj.GetInt("MakeUpStatus");
            int ClassCheckId = base.ParmJObj.GetInt("ClassCheckId");
            int GuestId = base.ParmJObj.GetInt("GuestId");
            bool flag = classModule.SetMakeUpStatusModule(Id, MakeUpStatus, ClassCheckId, GuestId, base.UserInfo);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 获取班级日志
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetClassLogPageList()
        {
            var pageModel = Common.Plugin.JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Class_Log_ViewModel()
            {
                Group_Id = base.UserInfo.Group_Id,
                School_Id = base.ParmJObj.GetInt("School_Id"),
                ClassId = base.ParmJObj.GetInt("ClassId"),
            };
            query.Group_Id = base.UserInfo.Group_Id;
            var list = classModule.GetClassLogPageListRepository(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);
            foreach (var item in list)
            {
                if (item.CreateBy > 0)
                {
                    item.CreateByName = UserReidsCache.GetUserLoginInfo(item.CreateBy)?.AccountName ?? "";
                }
            }
            var resultList = list.Select(x => new
            {
                LogTypeStr = EnumHelper.ToName(x.LogType),
                x.LogContent,
                CreateYear = x.CreateTime.ToString("yyyy"),
                CreateMonth = x.CreateTime.ToString("MM"),
                CreateDay = x.CreateTime.ToString("dd"),
                CreatHour = x.CreateTime.ToString("HH:mm:ss"),
                x.CreateByName
            });
            pageModel.Count = rowsCount;
            pageModel.PageData = resultList;
            return ApiResult.Success(data: pageModel);
        }

        #endregion

        #region 获取学员信息
        public ApiResult GetStudentList()
        {
            var schoolId = base.ParmJObj.GetInt("SchoolId", -1);
            var data = classModule.GetStudentListRepository(new Model.ViewModel.User.RB_Student_ViewModel { School_Id = schoolId, Group_Id = base.UserInfo.Group_Id });
            return ApiResult.Success(data: data);
        }
        #endregion

        #region 枚举相关列表
        /// <summary>
        /// 获取班级状态列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetClassStatusList()
        {
            var list = Common.Plugin.EnumHelper.EnumToList(typeof(ClassStatusEnum));
            if (list != null)
            {
                list.Insert(0, new EnumItem()
                {
                    Id = 0,
                    Name = "不限"
                });
            }
            return ApiResult.Success(data: list);
        }
        #endregion

        #region 老师教案
        /// <summary>
        /// 新增修改老师备案
        /// </summary>
        /// <returns></returns>
        public ApiResult SetClassLessPlan()
        {
            var query = Common.Plugin.JsonHelper.DeserializeObject<Class_LessonPlan_ViewModel>(RequestParm.Msg.ToString());
            query.Group_Id = base.UserInfo.Group_Id;
            query.CreateBy = base.UserInfo.Id;
            query.UpdateBy = base.UserInfo.Id;
            query.UpdateTime = System.DateTime.Now;
            query.CreateTime = System.DateTime.Now;
            if (query.LessonPlanList == null || !query.LessonPlanList.Any())
            {
                return ApiResult.Failed("请填写教案指导项目");
            }
            if (query.ClassId == 0)
            {
                return ApiResult.Failed("请选择班级信息");
            }
            if (query.ClassPlanId == 0)
            {
                return ApiResult.Failed("请选择班级排课信息");
            }
            foreach (var item in query.LessonPlanList)
            {
                if (item.LessonPlanProjectsList == null || !item.LessonPlanProjectsList.Any())
                {
                    return ApiResult.Failed("请填写教案指导项目");
                }
                //else
                //{
                //   item.LessonPlanProjectsList.ForEach(x => x.ProjectContent = (x.ProjectContentList != null && x.ProjectContentList.Any()) ? JsonHelper.Serialize(x.ProjectContentList) : "");
                //}
                if (item.LessonPlanDetailsList == null || !item.LessonPlanDetailsList.Any())
                {
                    return ApiResult.Failed("请填写教案详情");
                }
                else
                {

                    item.LessonPlanDetailsList.ForEach(x => x.ProjectPic = (x.ProjectPicList != null && x.ProjectPicList.Any()) ? JsonConvert.SerializeObject(x.ProjectPicList) : "");
                }
            }
            bool flag = classModule.SetClassLessPlan(query);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }




        /// <summary>
        /// 新增修改老师备案
        /// </summary>
        /// <returns></returns>
        public ApiResult UpdateClassLessPlan()
        {
            var query = Common.Plugin.JsonHelper.DeserializeObject<Class_LessonPlan_ViewModel>(RequestParm.Msg.ToString());
            query.Group_Id = base.UserInfo.Group_Id;
            query.CreateBy = base.UserInfo.Id;
            query.UpdateBy = base.UserInfo.Id;
            query.UpdateTime = System.DateTime.Now;
            query.CreateTime = System.DateTime.Now;

            if (!string.IsNullOrWhiteSpace(query.ClassEndTime))
            {
                if (Convert.ToDateTime(query.ClassEndTime) > System.DateTime.Now)
                {
                    return ApiResult.Failed("当前还未下课不能填写课后总结");
                }
            }

            if (query.LessonPlanList != null && query.LessonPlanList.Any())
            {
                int totalInfo = 0;
                foreach (var item in query.LessonPlanList)
                {
                    totalInfo += item.LessonPlanDetailsList.Where(x => !string.IsNullOrWhiteSpace(x.Summary)).Count();
                }
                if (totalInfo == 0)
                {
                    return ApiResult.Failed("课后总结请至少填写一项");
                }
            }
            else
            {
                return ApiResult.Failed("老师教案信息为空必须更新");
            }

            bool flag = classModule.UpdateClassLessPlan(query);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }



        public ApiResult GetClassLessPlan()
        {
            var extModel = new RB_Class_LessonPlan_ViewModel()
            {
                ClassPlanId = base.ParmJObj.GetInt("ClassPlanId"),
                ClassId = base.ParmJObj.GetInt("ClassId"),
                Group_Id = base.UserInfo.Group_Id,
                School_Id = base.ParmJObj.GetInt("School_Id"),
                IsTemplate = -1
            };

            Class_LessonPlan_ViewModel model = new Class_LessonPlan_ViewModel();
            //获取班级上课新以及老师名称
            var planDate = classModule.GetClassPlanListModule(new RB_Class_Plan_ViewModel { Group_Id = base.UserInfo.Group_Id, ClassId = extModel.ClassId, ClassPlanId = extModel.ClassPlanId }).FirstOrDefault();
            if (planDate == null || planDate.ClassPlanId == 0)
            {
                return ApiResult.Failed("班级上课计划不存在");
            }
            var planTiemList = classModule.GetClassTimeListModule(new RB_Class_Time_ViewModel { Group_Id = base.UserInfo.Group_Id, ClassId = extModel.ClassId, ClassPlanId = extModel.ClassPlanId });
            model.TeacherName = planDate.TeacherName;
            model.WorkDate = planDate.ClassDate.ToString("yyyy年MM月dd日");
            model.BeiKeStatus = planDate.BeiKeStatus;
            model.FanKuiStatus = planDate.FanKuiStatus;
            model.ParentFanKuiStatus = planDate.ParentFanKuiStatus;


            model.WeekStr = StringHelper.GetJapanWeekChar(planDate.ClassDate);
            DateTime startTime = System.DateTime.Now;
            DateTime endTime = System.DateTime.Now;
            DateTime maxStarttime = System.DateTime.Now;
            int planTimeNum = 0;
            int jiangeTime = 0;
            if (planTiemList != null && planTiemList.Any())
            {
                planTimeNum = planTiemList.Count();
                planTiemList.ForEach(x => x.NewPlanDateTime = planDate.ClassDate.ToString("yyyy-MM-dd") + " " + x.StartTime);
                planTiemList.ForEach(x => x.NewEndPlanDateTime = planDate.ClassDate.ToString("yyyy-MM-dd") + " " + x.EndTime);


                model.DayTime = planTiemList.Min(x => Convert.ToDateTime(x.NewPlanDateTime)).ToString("HH:mm");
                startTime = planTiemList.Min(x => Convert.ToDateTime(x.NewPlanDateTime));
                maxStarttime = planTiemList.Max(x => Convert.ToDateTime(x.NewPlanDateTime));
                endTime = planTiemList.Min(x => Convert.ToDateTime(x.NewEndPlanDateTime));
                jiangeTime = Convert.ToInt32(maxStarttime.Subtract(startTime).TotalMinutes);
                model.RestTime = maxStarttime.Subtract(endTime).TotalMinutes.ToString();
                model.DayTime = model.DayTime + "~" + planTiemList.Max(x => Convert.ToDateTime(x.NewEndPlanDateTime)).ToString("HH:mm");
                model.ClassStartTime = planTiemList.Min(x => Convert.ToDateTime(x.NewPlanDateTime)).ToString("yyyy-MM-dd HH:mm:00");
                model.ClassEndTime = planTiemList.Max(x => Convert.ToDateTime(x.NewEndPlanDateTime)).ToString("yyyy-MM-dd HH:mm:00");
            }
            extModel.ClassDate = planDate.ClassDate;
            var lessonPlanList = classModule.GetLessonPlanListRepository(extModel);

            #region 查询备课评分信息
            if (lessonPlanList != null && lessonPlanList.Any())
            {
                lessonPlanList.ForEach(x => x.ClassPlanId = planDate.ClassPlanId);
                var query = new RB_Class_LessonComment_ViewModel()
                {
                    ClassId = base.ParmJObj.GetInt("ClassId"),
                    Group_Id = base.UserInfo.Group_Id,
                    ClassPlanId = base.ParmJObj.GetInt("ClassPlanId"),
                };
                query.Group_Id = base.UserInfo.Group_Id;
                query.ClassDate = planDate.ClassDate;
                var list = classModule.GetLessonCommentList(query);
                model.TotalScore = (list != null && list.Any()) ? list.Where(x => x.Score > 0).Sum(x => x.Score) : 0;
            }
            #endregion
            model.ClassId = extModel.ClassId;
            model.ClassPlanId = extModel.ClassPlanId;
            model.School_Id = extModel.School_Id;
            model.Group_Id = extModel.Group_Id;
            if (lessonPlanList != null && lessonPlanList.Any())
            {
                string lessonPlanIds = string.Join(",", lessonPlanList.Select(x => x.LessonPlanId));
                var detailsList = classModule.GetLessonPlanDetailsListRepository(new RB_Class_LessonPlanDetails_ViewModel { Group_Id = base.UserInfo.Group_Id, LessonPlanIds = lessonPlanIds });
                var projectList = classModule.GetLessonPlanProjectsListRepository(new RB_Class_LessonPlanProjects_ViewModel { Group_Id = base.UserInfo.Group_Id, LessonPlanIds = lessonPlanIds });
                model.CourseNum = lessonPlanList.FirstOrDefault()?.CourseNum ?? 0;
                model.LessonPlan = lessonPlanList.FirstOrDefault()?.LessonPlan;
                model.CreateBy = lessonPlanList.FirstOrDefault()?.CreateBy ?? 0;
                model.UpdateBy = lessonPlanList.FirstOrDefault()?.UpdateBy ?? 0;
                model.CreateTime = lessonPlanList.FirstOrDefault()?.CreateTime ?? System.DateTime.Now;
                model.UpdateTime = lessonPlanList.FirstOrDefault()?.UpdateTime ?? System.DateTime.Now;
                model.IsTemplate = lessonPlanList.FirstOrDefault()?.IsTemplate ?? 0;
                model.LessonPlanList = new List<RB_Class_LessonPlan_ViewModel>();
                model.LessonPlanList = lessonPlanList;


                if (model.LessonPlanList != null && model.LessonPlanList.Any())
                {

                    int lessPlanDetailsId = model.LessonPlanList[0].LessonPlanId;
                    foreach (var item in model.LessonPlanList)
                    {
                        if (!string.IsNullOrWhiteSpace(item.ProjectPic))
                        {
                            item.ProjectPicList = JsonConvert.DeserializeObject<List<string>>(item.ProjectPic);
                        }
                        else
                        {
                            item.ProjectPicList = new List<string>();
                        }

                        item.LessonPlanDetailsList = new List<RB_Class_LessonPlanDetails_ViewModel>();
                        item.LessonPlanProjectsList = new List<RB_Class_LessonPlanProjects_ViewModel>();
                        item.LessonPlanDetailsList = detailsList.Where(x => x.LessonPlanId == item.LessonPlanId).ToList();
                        int tempDuration = 0;

                        if (lessPlanDetailsId != item.LessonPlanId)
                        {
                            tempDuration = jiangeTime;
                        }
                        if (item.LessonPlanDetailsList != null && item.LessonPlanDetailsList.Any())
                        {
                            foreach (var itemDetails in item.LessonPlanDetailsList)
                            {
                                tempDuration += itemDetails.Duration;
                                itemDetails.DurationEndTime = startTime.AddMinutes(tempDuration).ToString("HH:mm");
                            }
                        }

                        item.LessonPlanProjectsList = projectList.Where(x => x.LessonPlanId == item.LessonPlanId).ToList();

                        // item.LessonPlanProjectsList.ForEach(x => x.ProjectContentList = (string.IsNullOrWhiteSpace(x.ProjectContent) ? new List<string>() : Common.Plugin.JsonHelper.DeserializeObject<List<string>>(x.ProjectContent)));
                        model.IsEditSummary += item.LessonPlanDetailsList.Where(x => !string.IsNullOrWhiteSpace(x.Summary)).Count();

                    }
                }
            }
            else
            {
                model.LessonPlanList = new List<RB_Class_LessonPlan_ViewModel>
                {
                    new RB_Class_LessonPlan_ViewModel { CourseName = "备课信息", LessonPlanDetailsList = new List<RB_Class_LessonPlanDetails_ViewModel>(), LessonPlanProjectsList = new List<RB_Class_LessonPlanProjects_ViewModel>() },
                    //new RB_Class_LessonPlan_ViewModel { CourseName = "理解篇", LessonPlanDetailsList = new List<RB_Class_LessonPlanDetails_ViewModel>(), LessonPlanProjectsList = new List<RB_Class_LessonPlanProjects_ViewModel>() }
                };
            }

            #region 追加章节信息

            var hours = classModule.GetCurrentPlanStudyHoursRepository(model.ClassPlanId) + 1;
            if (hours != -1)
            {
                var classObj = classModule.GetClassModule(model.ClassId);

                var courseOjb = new CourseModule().GetCourseModule(classObj.CouseId);

                var chapter = new CourseModule().GetMatchHoursChapterModule(classObj.CouseId, hours);
                if (chapter != null && chapter.Count > 0)
                {
                    model.Chapter = chapter;
                }
                model.CourseName = courseOjb.CourseName;
            }

            #endregion

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

        public ApiResult GetClassLessPlanList()
        {
            var extModel = new RB_Class_LessonPlan_ViewModel()
            {
                CreateBy = base.UserInfo.Id,
                Group_Id = base.UserInfo.Group_Id,
                // School_Id = base.ParmJObj.GetInt("School_Id"),
                IsTemplate = 1
            };
            var lessonPlanList = classModule.GetLessonPlanListRepository(extModel);

            List<Class_LessonPlan_ViewModel> List = new List<Class_LessonPlan_ViewModel>();

            if (lessonPlanList != null && lessonPlanList.Any())
            {
                string lessonPlanIds = string.Join(",", lessonPlanList.Select(x => x.LessonPlanId));
                var detailsList = classModule.GetLessonPlanDetailsListRepository(new RB_Class_LessonPlanDetails_ViewModel { Group_Id = base.UserInfo.Group_Id, School_Id = extModel.School_Id, LessonPlanIds = lessonPlanIds });
                var projectList = classModule.GetLessonPlanProjectsListRepository(new RB_Class_LessonPlanProjects_ViewModel { Group_Id = base.UserInfo.Group_Id, School_Id = extModel.School_Id, LessonPlanIds = lessonPlanIds });

                foreach (var classPlanItem in lessonPlanList.GroupBy(x => x.ClassPlanId))
                {
                    Class_LessonPlan_ViewModel model = new Class_LessonPlan_ViewModel
                    {
                        ClassId = extModel.ClassId,
                        ClassPlanId = classPlanItem.Key,
                        School_Id = extModel.School_Id,
                        Group_Id = extModel.Group_Id,
                        CourseNum = lessonPlanList.Where(x => x.ClassPlanId == classPlanItem.Key).FirstOrDefault()?.CourseNum ?? 0,
                        LessonPlan = lessonPlanList.Where(x => x.ClassPlanId == classPlanItem.Key).FirstOrDefault()?.LessonPlan,
                        CreateBy = lessonPlanList.Where(x => x.ClassPlanId == classPlanItem.Key).FirstOrDefault()?.CreateBy ?? 0,
                        UpdateBy = lessonPlanList.Where(x => x.ClassPlanId == classPlanItem.Key).FirstOrDefault()?.UpdateBy ?? 0,
                        CreateTime = lessonPlanList.Where(x => x.ClassPlanId == classPlanItem.Key).FirstOrDefault()?.CreateTime ?? System.DateTime.Now,
                        UpdateTime = lessonPlanList.Where(x => x.ClassPlanId == classPlanItem.Key).FirstOrDefault()?.UpdateTime ?? System.DateTime.Now,
                        IsTemplate = lessonPlanList.Where(x => x.ClassPlanId == classPlanItem.Key).FirstOrDefault()?.IsTemplate ?? 0,
                        LessonPlanList = new List<RB_Class_LessonPlan_ViewModel>()
                    };
                    model.LessonPlanList = lessonPlanList.Where(x => x.ClassPlanId == classPlanItem.Key).ToList();
                    foreach (var item in model.LessonPlanList)
                    {
                        item.LessonPlanDetailsList = new List<RB_Class_LessonPlanDetails_ViewModel>();
                        item.LessonPlanProjectsList = new List<RB_Class_LessonPlanProjects_ViewModel>();
                        item.LessonPlanDetailsList = detailsList.Where(x => x.LessonPlanId == item.LessonPlanId).ToList();
                        if (item.LessonPlanDetailsList != null && item.LessonPlanDetailsList.Any())
                        {
                            item.LessonPlanDetailsList.ForEach(x => x.ProjectPicList = (string.IsNullOrWhiteSpace(x.ProjectPic) ? new List<string>() : JsonConvert.DeserializeObject<List<string>>(x.ProjectPic)));
                        }
                        item.LessonPlanProjectsList = projectList.Where(x => x.LessonPlanId == item.LessonPlanId).ToList();
                        // item.LessonPlanProjectsList.ForEach(x => x.ProjectContentList = (string.IsNullOrWhiteSpace(x.ProjectContent) ? new List<string>() : Common.Plugin.JsonHelper.DeserializeObject<List<string>>(x.ProjectContent)));
                    }
                    List.Add(model);
                }
            }
            return ApiResult.Success("", List);
        }

        /// <summary>
        /// 获取上课计划
        /// </summary>
        /// <returns></returns>
        public ApiResult GetTeacherPlan()
        {
            var query = new RB_Class_ViewModel()
            {
                Group_Id = base.UserInfo.Group_Id,
                Teacher_Id = base.ParmJObj.GetInt("Teacher_Id", 0),
                StartTime = base.ParmJObj.GetStringValue("StartTime"),
                EndTime = base.ParmJObj.GetStringValue("EndTime"),
            };
            if (query.Teacher_Id == 0)
            {
                if (base.UserInfo.AccountType == Common.Enum.User.AccountTypeEnum.Teacher)
                {
                    query.Teacher_Id = base.UserInfo.AccountId;
                    if (query.Teacher_Id == 0)
                    {
                        return ApiResult.Failed("请传入老师id");
                    }
                }
            }

            var data = classModule.GetTeacherPlanModule(query);

            List<object> result = new List<object>();
            DateTime startTime = Convert.ToDateTime(query.StartTime);
            DateTime endTime = Convert.ToDateTime(query.EndTime);

            TimeSpan sp = endTime.Subtract(startTime);

            for (int i = 0; i <= sp.Days; i++)
            {
                int IsLessonStatus = 0;//0-未备课，1-部分，2-全部
                List<object> planList = new List<object>();
                List<object> planListResult = new List<object>();
                var plan = data.Where(x => x.ClassDate.ToString("yyyy-MM-dd") == startTime.AddDays(i).ToString("yyyy-MM-dd"));
                string DayTime = string.Empty;

                foreach (var itemGroup in plan.GroupBy(x => new { x.TeacherId }))
                {
                    List<object> planListTeacher = new List<object>();
                    foreach (var item in plan.Where(x => x.TeacherId == itemGroup.Key.TeacherId))
                    {

                        if (plan.Where(x => x.LessonPlanNum > 0).Count() < plan.Count() && plan.Where(x => x.LessonPlanNum > 0).Count() > 0)
                        {
                            IsLessonStatus = 1;
                        }
                        else if (plan.Where(x => x.LessonPlanNum > 0).Count() == plan.Count())
                        {
                            IsLessonStatus = 2;
                        }
                        else
                        {
                            IsLessonStatus = 0;
                        }

                        foreach (var itemTime in item.PlanTimeList)
                        {
                            int IsPlanLessonStatus = 0;//0-未备课，1-部分，2-全部
                            if (plan.Where(x => x.LessonPlanNum > 0 && x.ClassPlanId == itemTime.ClassPlanId).Count() < plan.Where(x => x.ClassPlanId == itemTime.ClassPlanId).Count() && plan.Where(x => x.LessonPlanNum > 0 && x.ClassPlanId == itemTime.ClassPlanId).Count() > 0)
                            {
                                IsPlanLessonStatus = 1;
                            }
                            else if (plan.Where(x => x.LessonPlanNum > 0 && x.ClassPlanId == itemTime.ClassPlanId).Count() == plan.Where(x => x.ClassPlanId == itemTime.ClassPlanId).Count())
                            {
                                IsPlanLessonStatus = 2;
                            }
                            else
                            {
                                IsPlanLessonStatus = 0;
                            }
                            planList.Add(new
                            {
                                IsPlanLessonStatus,
                                item.ClassPlanId,
                                item.ClassId,
                                item.TeacherId,
                                item.LessonPlanNum,
                                item.School_Id,
                                item.ClassName,
                                itemTime.StartTime,
                                itemTime.EndTime,
                                item.TeacherName,
                                item.UserIcon,
                                GuestStr = (item.GuestList != null && item.GuestList.Any()) ? string.Join(",", item.GuestList.Select(x => x.GuestName)) : ""
                            });


                            planListTeacher.Add(new
                            {
                                IsPlanLessonStatus,
                                item.ClassPlanId,
                                item.ClassId,
                                item.TeacherId,
                                item.LessonPlanNum,
                                item.School_Id,
                                item.ClassName,
                                itemTime.StartTime,
                                itemTime.EndTime,
                                item.TeacherName,
                                item.UserIcon,
                                GuestStr = (item.GuestList != null && item.GuestList.Any()) ? string.Join(",", item.GuestList.Select(x => x.GuestName)) : ""
                            });

                        }

                        if (item.PlanTimeList != null && item.PlanTimeList.Any())
                        {
                            item.PlanTimeList.ForEach(x => x.NewPlanDateTime = item.ClassDate.ToString("yyyy-MM-dd") + " " + x.StartTime);
                            DayTime = item.PlanTimeList.Min(x => Convert.ToDateTime(x.NewPlanDateTime)).ToString("HH:ss");
                            item.PlanTimeList.ForEach(x => x.NewPlanDateTime = item.ClassDate.ToString("yyyy-MM-dd") + " " + x.EndTime);
                            DayTime = DayTime + "~" + item.PlanTimeList.Max(x => Convert.ToDateTime(x.NewPlanDateTime)).ToString("HH:ss");
                        }
                    }

                    planListResult.Add(new
                    {
                        itemGroup.Key.TeacherId,
                        TeacherName = plan.Where(x => x.TeacherId == itemGroup.Key.TeacherId).FirstOrDefault()?.TeacherName ?? "",
                        planListTeacher
                    });
                }

                result.Add(new
                {
                    planListResult,
                    IsLessonStatus = (planList != null && planList.Any()) ? IsLessonStatus : -1,
                    DayTime,
                    DateYear = startTime.AddDays(i).ToString("yyyy"),
                    DateMonth = startTime.AddDays(i).ToString("MM"),
                    DateDay = startTime.AddDays(i).ToString("dd"),
                    WeekStr = StringHelper.GetJapanWeekChar(startTime.AddDays(i)),
                    PlanList = planList
                });
            }
            return ApiResult.Success(data: result);
        }




        /// <summary>
        /// 客户反馈
        /// </summary>
        /// <returns></returns>
        public ApiResult GetUpdateClassLessPlanSummary()
        {
            var query = Common.Plugin.JsonHelper.DeserializeObject<Class_LessonPlan_ViewModel>(RequestParm.Msg.ToString());
            query.Group_Id = base.UserInfo.Group_Id;
            query.CreateBy = base.UserInfo.Id;
            query.UpdateBy = base.UserInfo.Id;
            query.UpdateTime = System.DateTime.Now;
            query.CreateTime = System.DateTime.Now;

            if (!string.IsNullOrWhiteSpace(query.ClassEndTime))
            {
                if (Convert.ToDateTime(query.ClassEndTime) > System.DateTime.Now)
                {
                    return ApiResult.Failed("当前还未下课不能填写课后总结");
                }
            }
            int totalInfo = 0;
            if (query.LessonPlanList != null && query.LessonPlanList.Any())
            {
                totalInfo += query.LessonPlanList.Where(x => !string.IsNullOrWhiteSpace(x.Summary)).Count();
            }
            if (totalInfo == 0)
            {
                return ApiResult.Failed("课后总结请至少填写一项");
            }
            query.LessonPlanList.ForEach(x => x.ProjectPic = (x.ProjectPicList != null && x.ProjectPicList.Any()) ? JsonConvert.SerializeObject(x.ProjectPicList) : "");

            bool flag = classModule.GetUpdateClassLessPlanSummary(query);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }


        /// <summary>
        /// 获取上课计划
        /// </summary>
        /// <returns></returns>
        public ApiResult GetNewTeacherPlan()
        {
            var query = new RB_Class_ViewModel()
            {
                Group_Id = base.UserInfo.Group_Id,
                Teacher_Id = base.ParmJObj.GetInt("Teacher_Id", 0),
                StartTime = base.ParmJObj.GetStringValue("StartTime"),
                EndTime = base.ParmJObj.GetStringValue("EndTime"),
            };
            if (query.Teacher_Id == 0)
            {
                if (base.UserInfo.AccountType == Common.Enum.User.AccountTypeEnum.Teacher)
                {
                    query.Teacher_Id = base.UserInfo.AccountId;
                    if (query.Teacher_Id == 0)
                    {
                        return ApiResult.Failed("请传入老师id");
                    }
                }
            }

            var data = classModule.GetTeacherPlanModule(query);

            List<object> result = new List<object>();
            DateTime startTime = Convert.ToDateTime(query.StartTime);
            DateTime endTime = Convert.ToDateTime(query.EndTime);

            TimeSpan sp = endTime.Subtract(startTime);

            for (int i = 0; i <= sp.Days; i++)
            {
                int IsLessonStatus = 0;//0-未备课，1-部分，2-全部
                List<object> planList = new List<object>();
                List<object> planListResult = new List<object>();
                var plan = data.Where(x => x.ClassDate.ToString("yyyy-MM-dd") == startTime.AddDays(i).ToString("yyyy-MM-dd"));
                string DayTime = string.Empty;

                foreach (var itemGroup in plan.GroupBy(x => new { x.TeacherId, x.ClassId }))
                {
                    List<object> planListTeacher = new List<object>();
                    foreach (var item in plan.Where(x => x.TeacherId == itemGroup.Key.TeacherId && x.ClassId == itemGroup.Key.ClassId))
                    {

                        if (plan.Where(x => x.BeiKeStatus > 0).Count() < plan.Count() && plan.Where(x => x.BeiKeStatus > 0).Count() > 0)
                        {
                            IsLessonStatus = 1;
                        }
                        else if (plan.Where(x => x.BeiKeStatus > 0).Count() == plan.Count())
                        {
                            IsLessonStatus = 2;
                        }
                        else
                        {
                            IsLessonStatus = 0;
                        }

                        foreach (var itemTime in item.PlanTimeList)
                        {
                            int IsPlanLessonStatus = 0;//0-未备课，1-部分，2-全部
                            if (plan.Where(x => x.BeiKeStatus > 0 && (x.ClassPlanId == itemTime.ClassPlanId || x.ClassDate == Convert.ToDateTime(Common.ConvertHelper.FormatDate(itemTime.NewPlanDateTime)))).Count() < plan.Where(x => (x.ClassPlanId == itemTime.ClassPlanId || x.ClassDate == Convert.ToDateTime(Common.ConvertHelper.FormatDate(itemTime.NewPlanDateTime)))).Count() && plan.Where(x => x.BeiKeStatus > 0 && (x.ClassPlanId == itemTime.ClassPlanId || x.ClassDate == Convert.ToDateTime(Common.ConvertHelper.FormatDate(itemTime.NewPlanDateTime)))).Count() > 0)
                            {
                                IsPlanLessonStatus = 1;
                            }
                            else if (plan.Where(x => x.BeiKeStatus > 0 && (x.ClassPlanId == itemTime.ClassPlanId || x.ClassDate == Convert.ToDateTime(Common.ConvertHelper.FormatDate(itemTime.NewPlanDateTime)))).Count() == plan.Where(x => (x.ClassPlanId == itemTime.ClassPlanId || x.ClassDate == Convert.ToDateTime(Common.ConvertHelper.FormatDate(itemTime.NewPlanDateTime)))).Count())
                            {
                                IsPlanLessonStatus = 2;
                            }
                            else
                            {
                                IsPlanLessonStatus = 0;
                            }

                            planList.Add(new
                            {
                                IsPlanLessonStatus,
                                item.ClassPlanId,
                                item.ClassId,
                                item.TeacherId,
                                item.LessonPlanNum,
                                item.School_Id,
                                item.ClassName,
                                itemTime.StartTime,
                                itemTime.EndTime,
                                item.TeacherName,
                                item.UserIcon,
                                item.Ranks,
                                GuestStr = (itemTime.GuestList != null && itemTime.GuestList.Any()) ? string.Join(",", itemTime.GuestList.Where(x => x.IsCheck == 0).Select(x => x.GuestName)) : "",
                                AllGuestStr = (itemTime.GuestList != null && itemTime.GuestList.Any()) ? string.Join(",", itemTime.GuestList.Select(x => x.GuestName)) : ""
                            });


                            planListTeacher.Add(new
                            {
                                IsPlanLessonStatus,
                                item.ClassPlanId,
                                item.ClassId,
                                item.TeacherId,
                                item.LessonPlanNum,
                                item.School_Id,
                                item.ClassName,
                                itemTime.StartTime,
                                itemTime.EndTime,
                                item.TeacherName,
                                item.UserIcon,
                                GuestStr = (itemTime.GuestList != null && itemTime.GuestList.Any()) ? string.Join(",", itemTime.GuestList.Where(x => x.IsCheck == 0).Select(x => x.GuestName)) : "",
                                AllGuestStr = (itemTime.GuestList != null && itemTime.GuestList.Any()) ? string.Join(",", itemTime.GuestList.Select(x => x.GuestName)) : ""
                            });

                        }

                        if (item.PlanTimeList != null && item.PlanTimeList.Any())
                        {
                            item.PlanTimeList.ForEach(x => x.NewPlanDateTime = item.ClassDate.ToString("yyyy-MM-dd") + " " + x.StartTime);
                            DayTime = item.PlanTimeList.Min(x => Convert.ToDateTime(x.NewPlanDateTime)).ToString("HH:ss");
                            item.PlanTimeList.ForEach(x => x.NewPlanDateTime = item.ClassDate.ToString("yyyy-MM-dd") + " " + x.EndTime);
                            DayTime = DayTime + "~" + item.PlanTimeList.Max(x => Convert.ToDateTime(x.NewPlanDateTime)).ToString("HH:ss");
                        }
                    }

                    planListResult.Add(new
                    {
                        LessonPlanNum = plan.Where(x => x.ClassId == itemGroup.Key.ClassId && x.TeacherId == itemGroup.Key.TeacherId).FirstOrDefault()?.BeiKeStatus ?? 0,
                        ParentFanKuiStatus = plan.Where(x => x.ClassId == itemGroup.Key.ClassId && x.TeacherId == itemGroup.Key.TeacherId).FirstOrDefault()?.ParentFanKuiStatus ?? 0,
                        LessonPlanSummaryNum = plan.Where(x => x.ClassId == itemGroup.Key.ClassId && x.TeacherId == itemGroup.Key.TeacherId).FirstOrDefault()?.FanKuiStatus ?? 0,
                        Ranks = plan.Where(x => x.ClassId == itemGroup.Key.ClassId && x.TeacherId == itemGroup.Key.TeacherId).FirstOrDefault()?.Ranks ?? -1,
                        School_Id = plan.Where(x => x.ClassId == itemGroup.Key.ClassId && x.TeacherId == itemGroup.Key.TeacherId).FirstOrDefault()?.School_Id ?? -1,
                        ClassPlanId = plan.Where(x => x.ClassId == itemGroup.Key.ClassId && x.TeacherId == itemGroup.Key.TeacherId).FirstOrDefault()?.ClassPlanId ?? -1,
                        ClassDateStr = startTime.AddDays(i).ToString("yyyy-MM-dd"),
                        itemGroup.Key.TeacherId,
                        itemGroup.Key.ClassId,
                        ClassName = plan.Where(x => x.ClassId == itemGroup.Key.ClassId).FirstOrDefault()?.ClassName ?? "",
                        TeacherName = plan.Where(x => x.TeacherId == itemGroup.Key.TeacherId).FirstOrDefault()?.TeacherName ?? "",
                        planListTeacher
                    });
                }

                result.Add(new
                {
                    planListResult,
                    IsLessonStatus = (planList != null && planList.Any()) ? IsLessonStatus : -1,
                    DayTime,
                    DateYear = startTime.AddDays(i).ToString("yyyy"),
                    DateMonth = startTime.AddDays(i).ToString("MM"),
                    DateDay = startTime.AddDays(i).ToString("dd"),
                    WeekStr = StringHelper.GetJapanWeekChar(startTime.AddDays(i)),
                    PlanList = planList
                });
            }
            return ApiResult.Success(data: result);
        }




        /// <summary>
        /// 获取老师教案评论
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetLessonCommentList()
        {
            var query = new RB_Class_LessonComment_ViewModel()
            {
                ClassPlanId = base.ParmJObj.GetInt("ClassPlanId"),
                ClassId = base.ParmJObj.GetInt("ClassId"),
                Group_Id = base.UserInfo.Group_Id,
                //School_Id = base.ParmJObj.GetInt("School_Id"),
            };
            try
            {
                string classDate = base.ParmJObj.GetStringValue("ClassDate");
                if (!string.IsNullOrWhiteSpace(classDate))
                {
                    query.ClassDate = Convert.ToDateTime(classDate);
                }
               
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "GetLessonCommentList");
            }
            query.Group_Id = base.UserInfo.Group_Id;
            var list = classModule.GetLessonCommentList(query);
            foreach (var item in list)
            {
                if (item.CreateBy > 0)
                {
                    item.CreateByName = UserReidsCache.GetUserLoginInfo(item.CreateBy)?.AccountName ?? "";
                }
            }
            return ApiResult.Success(data: list);
        }



        /// <summary>
        /// 新增/修改老师备案评论
        /// </summary>
        /// <returns></returns>
        public ApiResult SetLessonComment()
        {
            var query = Common.Plugin.JsonHelper.DeserializeObject<RB_Class_LessonComment_ViewModel>(RequestParm.Msg.ToString());
            query.Group_Id = base.UserInfo.Group_Id;
            query.CreateBy = base.UserInfo.Id;
            query.CreateTime = System.DateTime.Now;
            if (query.Score == 0)
            {
                return ApiResult.Failed("请选择评分");
            }
            if (string.IsNullOrWhiteSpace(query.Comment))
            {
                return ApiResult.Failed("评论内容不能为空");
            }
            bool flag = classModule.SetLessonComment(query);
            if (flag)
            {
                Common.Message.PushMessageModel model = new Common.Message.PushMessageModel()
                {
                    CategoryId = PushMessageCategoryEnum.LessonComment,
                    Content = query.Comment,
                    CoverImg = "",
                    CreateByName = base.UserInfo.AccountName,
                    JumpUrl = $"/course/prepareclassDetails?ClassId={query.ClassId}&ClassPlanId={query.ClassPlanId}",
                    SendTime = DateTime.Now,
                    SendType = 0,
                    Title = "教案评论",
                    Platform = 2,
                    ReceiveId = query.TeacherId.ToString(),
                };
                Common.Message.MessageHelper.SendMessage(model);
            }
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 删除教案评论
        /// </summary>
        /// <returns></returns>
        public ApiResult DelLessonComment()
        {
            int Id = base.ParmJObj.GetInt("LessonCommentId");
            var model = classModule.GetLessonCommentList(new RB_Class_LessonComment_ViewModel { LessonCommentId = Id }).FirstOrDefault();
            if (model == null || model.LessonCommentId == 0)
            {
                return ApiResult.Failed("评论信息不存在");
            }
            if (model.Score > 0)
            {
                return ApiResult.Failed("打分的评论不能删除");
            }
            bool flag = classModule.DelLessonComment(model);
            return flag ? ApiResult.Success("删除成功") : ApiResult.Failed("删除失败");
        }





        /// <summary>
        /// 判断当前用户是否已评论当前教案
        /// </summary>
        /// <returns></returns>
        public ApiResult GetNowUserLessonComment()
        {
            var query = new RB_Class_LessonComment_ViewModel()
            {
                ClassPlanId = base.ParmJObj.GetInt("ClassPlanId"),
                ClassId = base.ParmJObj.GetInt("ClassId"),
            };
            try
            {
                string classDate = base.ParmJObj.GetStringValue("ClassDate");
                if (!string.IsNullOrWhiteSpace(classDate))
                {
                    query.ClassDate = Convert.ToDateTime(classDate);
                }
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "GetLessonCommentList");
            }
            query.Group_Id = base.UserInfo.Group_Id;
            query.CreateBy = base.UserInfo.Id;
            var list = classModule.GetLessonCommentList(query);
            if (list != null && list.Any())
            {
                return ApiResult.Success("", data: new { Score = -1 });
            }
            else
            {
                return ApiResult.Success("", data: new { Score = 5 });
            }

        }
        #endregion

        #region 老师上课挂件

        [HttpGet]
        [HttpPost]
        [Microsoft.AspNetCore.Authorization.AllowAnonymous]
        public ApiResult GetClassTimeList()
        {
            var ClassRoomId = base.ParmJObj.GetInt("ClassRoomId", 0);
            if (ClassRoomId == 0)
            {
                return ApiResult.Failed("请传入教室ID");
            }
            var list = classModule.GetClassTimeByRoomId(ClassRoomId, 100000);

            if (list == null || !list.Any())
            {
                return ApiResult.Failed("暂无排课安排");
            }
            else
            {
                var tempList = list.OrderBy(x => x.NewEndPlanDateTime).Where(x => x.NewPlanDateTime.HasValue && System.DateTime.Now >= x.NewPlanDateTime.Value && x.NewEndPlanDateTime.HasValue && System.DateTime.Now < x.NewEndPlanDateTime.Value && x.NewPlanDateTime.Value.ToString("yyyy-MM-dd") == System.DateTime.Now.ToString("yyyy-MM-dd")).Take(1).ToList();
                if (tempList == null || !tempList.Any())
                {
                    tempList = list.OrderBy(x => x.NewEndPlanDateTime).Where(x => x.NewPlanDateTime.HasValue && System.DateTime.Now <= x.NewPlanDateTime.Value && x.NewPlanDateTime.Value.ToString("yyyy-MM-dd") == System.DateTime.Now.ToString("yyyy-MM-dd")).Take(1).ToList();
                }

                if (tempList != null && tempList.Any())
                {///查询最近2天的课程
                    var classPlanList = classModule.GetClassTimeByClassId(tempList.FirstOrDefault()?.ClassId ?? 0, 100000);


                    //tempList.AddRange(list.OrderBy(x => x.NewEndPlanDateTime).Where(x => x.NewPlanDateTime.HasValue && System.DateTime.Now <= x.NewPlanDateTime.Value && x.NewPlanDateTime.Value.ToString("yyyy-MM-dd") == System.DateTime.Now.AddDays(1).ToString("yyyy-MM-dd")));
                    var newClassPlanList = classPlanList.OrderBy(x => x.NewEndPlanDateTime).Where(x => x.NewPlanDateTime.HasValue && System.DateTime.Now <= x.NewPlanDateTime.Value && x.NewPlanDateTime.Value <= System.DateTime.Now.AddDays(1)).ToList();
                    List<object> result = new List<object>();
                    newClassPlanList.AddRange(tempList);
                    foreach (var item in newClassPlanList.GroupBy(x => x.NewPlanDateTime.Value.ToString("yyyy-MM-dd")))
                    {
                        result.Add(new
                        {

                            DayStr = item.Key,
                            result = newClassPlanList.OrderBy(x => x.NewPlanDateTime).Where(x => x.NewPlanDateTime.Value.ToString("yyyy-MM-dd") == item.Key).Select(x => new
                            {
                                TeacherName = x.TeacherName ?? "",
                                TeacherIcon = x.TeacherHead ?? "",
                                ClassName = x.ClassName ?? "",
                                CourseName = x.CourseName ?? "",
                                CourseNum = x.CourseNum ?? "",
                                StartTime = x.StartTime ?? "",
                                EndTime = x.EndTime ?? "",
                                x.RoomName,
                                x.ClassPlanId,
                                x.ClassId,
                                x.ClassRoomId,
                                x.Group_Id,
                                x.School_Id,
                                x.TeacherId,
                                x.ClassTimeId,
                                DateYStr = x.NewPlanDateTime.HasValue ? x.NewPlanDateTime.Value.ToString("yyyy") : "",
                                DateMStr = x.NewPlanDateTime.HasValue ? x.NewPlanDateTime.Value.ToString("MM") : "",
                                DateDStr = x.NewPlanDateTime.HasValue ? x.NewPlanDateTime.Value.ToString("dd") : "",
                                x.ClassStatus,
                                SuiPaiList = string.IsNullOrWhiteSpace(x.SuiPai) ? new List<string>() : JsonHelper.DeserializeObject<List<string>>(x.SuiPai),
                            })
                        });
                    }

                    var lastResult = new
                    {
                        tempList.FirstOrDefault()?.TeacherName,
                        tempList.FirstOrDefault()?.TeacherHead,
                        tempList.FirstOrDefault()?.ClassName,
                        tempList.FirstOrDefault()?.CourseName,
                        StartTime = tempList.FirstOrDefault()?.StartTime ?? "",
                        EndTime = tempList.FirstOrDefault()?.EndTime ?? "",
                        result
                    };
                    return ApiResult.Success(data: lastResult);
                }
                return ApiResult.Failed("暂无排课安排");
                //var result = tempList.Select(x => new
                //{
                //    TeacherName = x.TeacherName ?? "",
                //    TeacherIcon = x.TeacherHead ?? "",
                //    ClassName = x.ClassName ?? "",
                //    CourseName = x.CourseName ?? "",
                //    CourseNum = x.CourseNum ?? "",
                //    StartTime = x.StartTime ?? "",
                //    EndTime = x.EndTime ?? "",
                //    x.ClassPlanId,
                //    x.ClassId,
                //    x.ClassRoomId,
                //    x.Group_Id,
                //    x.School_Id,
                //    x.TeacherId,
                //    x.ClassTimeId,
                //    DateYStr = x.NewPlanDateTime.HasValue ? x.NewPlanDateTime.Value.ToString("yyyy") : "",
                //    DateMStr = x.NewPlanDateTime.HasValue ? x.NewPlanDateTime.Value.ToString("MM") : "",
                //    DateDStr = x.NewPlanDateTime.HasValue ? x.NewPlanDateTime.Value.ToString("dd") : "",
                //    x.ClassStatus,
                //    SuiPaiList = string.IsNullOrWhiteSpace(x.SuiPai) ? new List<string>() : JsonHelper.DeserializeObject<List<string>>(x.SuiPai),
                //});

            }

        }



        /// <summary>
        /// 更新课堂随拍照片
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult UpdateTimeSuiPai()
        {
            var extModel = Common.Plugin.JsonHelper.DeserializeObject<RB_Class_Time_ViewModel>(RequestParm.Msg.ToString());
            if (extModel.ClassTimeId == 0)
            {
                return ApiResult.Failed("请传入上课时间Id");
            }
            if (extModel.SuiPaiList != null && extModel.SuiPaiList.Any())
            {
                extModel.SuiPai = Common.Plugin.JsonHelper.Serialize(extModel.SuiPaiList);
            }
            else
            {
                return ApiResult.Failed("请上传课堂随拍图片");
            }
            bool retult = classModule.UpdateTimeSuiPai(extModel.SuiPai, extModel.ClassTimeId);
            return retult ? ApiResult.Success("上传课堂随拍成功") : ApiResult.Failed("上传课堂随拍失败");
        }
        /// <summary>
        /// 更新上课状态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult UpdateTimeClassStatus()
        {
            var extModel = Common.Plugin.JsonHelper.DeserializeObject<RB_Class_Time_ViewModel>(RequestParm.Msg.ToString());
            if (extModel.ClassTimeId == 0)
            {
                return ApiResult.Failed("请传入上课时间Id");
            }
            var oldModel = classModule.GetClassTimeListModule(new RB_Class_Time_ViewModel { ClassTimeId = extModel.ClassTimeId, Group_Id = base.UserInfo.Group_Id }).FirstOrDefault();
            if (oldModel == null || oldModel.ClassTimeId == 0)
            {
                return ApiResult.Failed("上课计划不存在");
            }
            if (oldModel.ClassStatus == 2)
            {
                return ApiResult.Failed("已下课，请勿重复操作");
            }
            //  extModel.ClassStatus = oldModel.ClassStatus + 1;
            bool retult = classModule.UpdateTimeClassStatus(extModel.ClassStatus, extModel.ClassTimeId);
            return retult ? ApiResult.Success("课堂状态更新成功") : ApiResult.Failed("课堂状态更新失败");
        }

        /// <summary>
        /// 更新上课视频
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult UpdateTimeClassVideo()
        {
            var extModel = Common.Plugin.JsonHelper.DeserializeObject<RB_Class_Time_ViewModel>(RequestParm.Msg.ToString());
            if (extModel.ClassTimeId == 0)
            {
                return ApiResult.Failed("请传入上课时间Id");
            }
            var oldModel = classModule.GetClassTimeListModule(new RB_Class_Time_ViewModel { ClassTimeId = extModel.ClassTimeId, }).FirstOrDefault();
            if (oldModel == null || oldModel.ClassTimeId == 0)
            {
                return ApiResult.Failed("上课计划不存在");
            }
            if (string.IsNullOrWhiteSpace(extModel.VideoUrl))
            {
                return ApiResult.Failed("请传入视频地址");
            }
            //  extModel.ClassStatus = oldModel.ClassStatus + 1;
            bool retult = classModule.UpdateTimeClassVideo(extModel.VideoUrl, extModel.ClassTimeId);
            return retult ? ApiResult.Success("课堂视频更新成功") : ApiResult.Failed("课堂视频更新失败");
        }



        /// <summary>
        /// 获取学员列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Microsoft.AspNetCore.Authorization.AllowAnonymous]
        public ApiResult GetStudentByClassId()
        {
            var classId = base.ParmJObj.GetInt("ClassId");
            var schoolId = 0;
            var Group_Id = base.ParmJObj.GetInt("Group_Id", 100000);
            var data = classModule.GetClassStudentListModule(classId, schoolId, Group_Id, 0);
            return ApiResult.Success(data: data);
        }

        /// <summary>
        /// 获取学员列表以及签到状态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Microsoft.AspNetCore.Authorization.AllowAnonymous]
        public ApiResult GetStudentCheckByClassId()
        {
            var classId = base.ParmJObj.GetInt("ClassId");
            var ClassTimeId = base.ParmJObj.GetInt("ClassTimeId", 0);
            var schoolId = 0;
            if (classId == 0 || ClassTimeId == 0)
            {
                return ApiResult.ParamIsNull();
            }
            var Group_Id = base.ParmJObj.GetInt("Group_Id", 100000);
            var data = classModule.GetClassStudentListModule(classId, schoolId, Group_Id, ClassTimeId);
            return ApiResult.Success(data: data);
        }
        #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.GetClassPlanStatisticalModule(query, ClassType: ClassType);
            return ApiResult.Success(data: obj);
        }

        /// <summary>
        /// 老师课时统计
        /// </summary>
        /// <returns></returns>
        public ApiResult GetTeacherClassHoursStatistical()
        {
            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,
            };

            var obj = classModule.GetTeacherClassHoursStatisticalModule(query);
            return ApiResult.Success(data: obj);
        }
        #endregion
    }
}
