using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Edu.Common.API;
using Edu.Common.Plugin;
using Edu.Model.ViewModel.Grade;
using Edu.Model.ViewModel.User;
using Edu.Module.Course;
using Edu.Module.Public;
using Edu.Module.User;
using Edu.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Edu.WebApi.Controllers.Applet
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class AppletIndexController : AppletBaseController
    {

        /// <summary>
        /// 账号管理处理类
        /// </summary>
        private readonly AccountModule accountModule = new AccountModule();

        /// <summary>
        /// 公用处理类
        /// </summary>
        private readonly PublicModule publicModule = new PublicModule();

        /// <summary>
        /// 学生管理处理类
        /// </summary>
        private readonly StudentModule studentModule = new StudentModule();

        /// <summary>
        /// 学生管理处理类
        /// </summary>
        private readonly EducationContractModule educationContractModule = new EducationContractModule();
        /// <summary>
        /// 班级管理处理类
        /// </summary>
        private readonly ClassModule classModule = new ClassModule();
        /// <summary>
        /// 课程处理类对象
        /// </summary>
        private readonly CourseModule courseModule = AOP.AOPHelper.CreateAOPObject<CourseModule>();

        #region  小程序首页
        /// <summary>
        /// 小程序首页
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetIndexInfo()
        {
            var appletUserInfo = base.AppletUserInfo;
            //判断学员是否退学
            var studentList = studentModule.GetStudentInfo(appletUserInfo.AccountId, appletUserInfo.Group_Id);
            if (studentList == null || !studentList.Any())
            {
                return ApiResult.Failed(message: $"很抱歉,由于你已经退学,无法继续使用本系统", new { Error = 3 });
            }

            RB_Student_ViewModel studentModel = new RB_Student_ViewModel();
            studentModel = studentList.Where(x => x.ClassStatus == 2).FirstOrDefault();
            if (studentModel == null || studentModel.StuId == 0)
            {
                studentModel = new RB_Student_ViewModel();
                studentModel = studentList.Where(x => x.ClassStatus == 1).FirstOrDefault();
                if (studentModel == null || studentModel.StuId == 0)
                {
                    studentModel = new RB_Student_ViewModel();
                    studentModel = studentList.Where(x => x.ClassStatus == 3).FirstOrDefault();
                }
            }

            //获取电子合同 GetStudentContractInfo
            var contractList = educationContractModule.GetStudentContractInfo(appletUserInfo.AccountId, appletUserInfo.Group_Id);
            var backClassList = educationContractModule.GetStudentBackClassInfo(appletUserInfo.AccountId, appletUserInfo.Group_Id);


            var classTimeList = classModule.GetClassTimeByClassId(studentModel.ClassId, appletUserInfo.Group_Id);
            var tempList = classTimeList.OrderBy(x => x.NewEndPlanDateTime).Where(x => x.ClassId == studentModel.ClassId && x.NewPlanDateTime.HasValue && System.DateTime.Now >= x.NewPlanDateTime.Value.AddMinutes(-10) && x.NewEndPlanDateTime.HasValue && System.DateTime.Now < x.NewEndPlanDateTime.Value.AddMinutes(30));
            if (tempList == null || !tempList.Any())
            {
                tempList = classTimeList.OrderBy(x => x.NewEndPlanDateTime).Where(x => x.ClassId == studentModel.ClassId && x.NewPlanDateTime.HasValue && System.DateTime.Now <= x.NewPlanDateTime.Value);
            }
            var classModel = tempList?.OrderBy(x => x.NewPlanDateTime).FirstOrDefault();
            if (classModel == null || classModel.ClassTimeId == 0)
            {
                classModel = new Model.ViewModel.Grade.RB_Class_Time_Extend();
            }
            var result = new
            {
                studentModel.SName,//学区
                studentModel.CourseName,//课程
                studentModel.SurplusHours,//剩余时间
                studentModel.TeacherName,//老师
                studentModel.ClassId,
                studentModel.CourseId,
                EnterPhone = Cache.User.UserReidsCache.GetUserLoginInfo(studentModel.EnterID).UserMobile,
                ContractNum = (((contractList != null && contractList.Any()) ? contractList.Count() : 0) + ((backClassList != null && backClassList.Any()) ? backClassList.Count() : 0)),//合同数
                ClassPlan = new //我的课表最新一个数据
                {
                    NewPlanDateTimeStr = (classModel.NewPlanDateTime.HasValue) ? classModel?.NewPlanDateTime.Value.ToString("yyyy-MM-dd") : "",
                    TimeStr = (classModel.NewPlanDateTime.HasValue) ? Common.ConvertHelper.GetTimeStr(classModel.NewPlanDateTime.Value) : "",
                    TimeStart = classModel.StartTime,
                    TeacherName = classModel.TeacherName,
                    TimeStatusStr = classModel.ClassStatus,

                }
            };

            return ApiResult.Success("", result);
        }
        #endregion


        #region 我的课表
        /// <summary>
        /// 老师上课计划统计
        /// </summary>
        /// <returns></returns>
        public ApiResult GetStundentPlanStatistical()
        {
            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_ViewModel query = new RB_Class_ViewModel()
            {
                StartTime = startDate,
                EndTime = endDate,
                Group_Id = base.AppletUserInfo.Group_Id,
                School_Id = -1,
                ClassId = base.ParmJObj.GetInt("ClassId"),
            };

            var list = classModule.GetStundentPlanModule(query);

            List<Model.ViewModel.Course.ChapterTree_ViewModel> chapterTreeList = new List<Model.ViewModel.Course.ChapterTree_ViewModel>();
            if (list != null && list.Any())
            {
                string rannkIds = string.Join(",", list.Select(x => x.Ranks));//查询章节信息
                chapterTreeList = new CourseModule().GetMatchChapterRepository((list.FirstOrDefault()?.CourseId ?? 0), rannkIds);
            }
            DateTime startTime = Convert.ToDateTime(query.StartTime);
            DateTime endTime = Convert.ToDateTime(query.EndTime);

            TimeSpan sp = endTime.Subtract(startTime);
            List<object> planListResult = new List<object>();
            for (int i = 0; i <= sp.Days; i++)
            {
                var plan = list.Where(x => x.ClassDate.ToString("yyyy-MM-dd") == startTime.AddDays(i).ToString("yyyy-MM-dd"));
                string DayTime = string.Empty;

                foreach (var itemGroup in plan)
                {
                    itemGroup.Chapter = chapterTreeList.Where(x => x.ChapterNo == itemGroup.Ranks.ToString() || x.ChapterNo.Contains(itemGroup.Ranks.ToString() + ".")).ToList();
                    if (itemGroup.PlanTimeList != null && itemGroup.PlanTimeList.Any())
                    {
                        itemGroup.PlanTimeList.ForEach(x => x.NewPlanDateTime = itemGroup.ClassDate.ToString("yyyy-MM-dd") + " " + x.StartTime);
                        DayTime = itemGroup.PlanTimeList.Min(x => Convert.ToDateTime(x.NewPlanDateTime)).ToString("HH:ss");
                        itemGroup.PlanTimeList.ForEach(x => x.NewPlanDateTime = itemGroup.ClassDate.ToString("yyyy-MM-dd") + " " + x.EndTime);
                        //  DayTime = DayTime + "~" + itemGroup.PlanTimeList.Max(x => Convert.ToDateTime(x.NewPlanDateTime)).ToString("HH:ss");
                    }
                    planListResult.Add(new
                    {
                        itemGroup.Chapter,
                        DateYear = startTime.AddDays(i).ToString("yyyy"),
                        DateMonth = startTime.AddDays(i).ToString("MM"),
                        DateDay = startTime.AddDays(i).ToString("dd"),
                        WeekStr = StringHelper.GetJapanWeekChar(startTime.AddDays(i)),
                        ClassDateStr = startTime.AddDays(i).ToString("yyyy-MM-dd"),
                        ClassName = plan.Where(x => x.ClassId == itemGroup.ClassId).FirstOrDefault()?.ClassName ?? "",
                        PlanTimeList = itemGroup.PlanTimeList.Select(x => new
                        {
                            x.StartTime,
                            x.EndTime,
                            TeacherName = itemGroup.TeacherName ?? "",
                            UserIcon = itemGroup.UserIcon ?? "",
                            IsCheck = x.GuestList.Where(x => x.StudentId == base.AppletUserInfo.AccountId).FirstOrDefault()?.IsCheck,
                            IsLeave = Convert.ToDateTime(x.NewPlanDateTime) > DateTime.Now ? 1 : 0
                        })
                    });
                }
            }
            return ApiResult.Success(data: planListResult);
        }

        #endregion


        #region 我的课程
        /// <summary>
        /// 获取章节树形列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetChapterTree()
        {
            var query = new Model.ViewModel.Course.RB_Course_Chapter_ViewModel()
            {
                CourseId = base.ParmJObj.GetInt("CourseId"),
            };
            if (query.CourseId <= 0)
            {
                return ApiResult.ParamIsNull(message: "请传递课程编号!");
            }
            query.Group_Id = base.AppletUserInfo.Group_Id;
            var list = courseModule.GetChapterTreeListModule(query);
            return ApiResult.Success(data: list);
        }
        #endregion


        #region 我的合同
        public ApiResult GetContractList()
        {
            //获取电子合同 GetStudentContractInfo
            var contractList = educationContractModule.GetStudentContractInfo(base.AppletUserInfo.AccountId, base.AppletUserInfo.Group_Id);
            var backClassList = educationContractModule.GetStudentBackClassInfo(base.AppletUserInfo.AccountId, base.AppletUserInfo.Group_Id);

            List<object> result = new List<object>();
            if (contractList != null && contractList.Any())
            {
                foreach (var item in contractList)
                {
                    var nowContractList = new
                    {
                        item.ContractNo,
                        item.IsCompanySeal,
                        Type = 1,
                        item.Id
                    };
                    result.Add(nowContractList);
                }
            }
            if (backClassList != null && backClassList.Any())
            {
                foreach (var item in backClassList)
                {
                    var nowContractList = new
                    {
                        Type = 2,
                        ContractNo = item.ProtocolNum,
                        item.IsCompanySeal,
                        Id = item.BackClassProtocolId
                    };
                    result.Add(nowContractList);
                }
            }
            return ApiResult.Success("", result);
        }
        #endregion

        #region 我的进度
        /// <summary>
        /// 老师上课计划统计
        /// </summary>
        /// <returns></returns>
        public ApiResult GetStundentScheduleList()
        {

            RB_Class_ViewModel query = new RB_Class_ViewModel()
            {

                EndTime = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                Group_Id = base.AppletUserInfo.Group_Id,
                School_Id = -1,
                ClassId = base.ParmJObj.GetInt("ClassId"),
            };
            var list = classModule.GetStundentScheduleList(query);

            List<Model.ViewModel.Course.ChapterTree_ViewModel> chapterTreeList = new List<Model.ViewModel.Course.ChapterTree_ViewModel>();
            if (list != null && list.Any())
            {
                string rannkIds = string.Join(",", list.Select(x => x.Ranks));//查询章节信息
                chapterTreeList = new CourseModule().GetMatchChapterRepository((list.FirstOrDefault()?.CourseId ?? 0), rannkIds);
            }
            List<object> result = new List<object>();
            foreach (var item in chapterTreeList)
            {
                //判断是否已经学习
                var planModel = list.Where(x => item.ChapterNo == x.Ranks.ToString() || item.ChapterNo.Contains(x.Ranks.ToString() + ".")).FirstOrDefault();
                int IsStudy = 0;//0-未学习,1-已学习
                if (planModel != null && planModel.ClassPlanId > 0)
                {
                    if (planModel.ClassDate < (Convert.ToDateTime(System.DateTime.Now.ToString("yyyy-MM-dd 00:00:00"))))
                    {
                        IsStudy = 1;
                    }
                }
                result.Add(new
                {
                    IsStudy,
                    ChapterTreeInfo = item,

                });
            }
            return ApiResult.Success(data: result);
        }
        #endregion

        #region 我的剩余课时
        /// <summary>
        /// 老师上课计划统计
        /// </summary>
        /// <returns></returns>
        public ApiResult GetStundentSurplus()
        {

            RB_Class_ViewModel query = new RB_Class_ViewModel()
            {
                StartTime = System.DateTime.Now.AddDays(1).ToString("yyyy-MM-dd 00:00:00"),
                Group_Id = base.AppletUserInfo.Group_Id,
                School_Id = -1,
                ClassId = base.ParmJObj.GetInt("ClassId"),
            };
            var list = classModule.GetStundentPlanModule(query);
            List<object> planListResult = new List<object>();

            foreach (var itemGroup in list)
            {
                if (itemGroup.PlanTimeList != null && itemGroup.PlanTimeList.Any())
                {
                    itemGroup.PlanTimeList.ForEach(x => x.NewPlanDateTime = itemGroup.ClassDate.ToString("yyyy-MM-dd") + " " + x.StartTime);

                    itemGroup.PlanTimeList.ForEach(x => x.NewPlanDateTime = itemGroup.ClassDate.ToString("yyyy-MM-dd") + " " + x.EndTime);
                }
                planListResult.Add(new
                {
                    WeekStr = StringHelper.GetJapanWeekChar(itemGroup.ClassDate),
                    ClassDateStr = itemGroup.ClassDate.ToString("yyyy-MM-dd"),
                    TeacherName = itemGroup.TeacherName ?? "",
                    UserIcon = itemGroup.UserIcon ?? "",
                    RoomName = itemGroup.RoomName ?? "",
                    PlanTimeList = itemGroup.PlanTimeList.Select(x => new
                    {
                        x.StartTime,
                        x.EndTime,
                        IsCheck = x.GuestList.Where(x => x.StudentId == base.AppletUserInfo.AccountId).FirstOrDefault()?.IsCheck,
                        IsLeave = Convert.ToDateTime(x.NewPlanDateTime) > DateTime.Now ? 1 : 0
                    })
                });
            }

            return ApiResult.Success(data: planListResult);
        }
        #endregion
    }
}