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

namespace Edu.WebApi.Controllers.APP
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class AppIndexController : AppBaseController
    {

        private readonly StudentModule studentModule = new StudentModule();
        private readonly ClassModule classModule = new ClassModule();
        private readonly TeacherModule teacherModule = new TeacherModule();
        private readonly ManagerModule managerModule = new ManagerModule();
        private readonly AppHomePageModule appHomePageModule = AOP.AOPHelper.CreateAOPObject<AppHomePageModule>();

        #region 首次登录后填写兴趣爱好
        /// <summary>
        /// 首次登录记录用户的兴趣爱好
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetInterest()
        {
            var query = new RB_Student_ViewModel()
            {
                Interest = base.ParmJObj.GetInt("Interest"),
                JapanBaseInfo = base.ParmJObj.GetInt("JapanBaseInfo"),
                StuSex = base.ParmJObj.GetInt("StuSex"),
                StuIcon = base.ParmJObj.GetStringValue("StuIcon"),
                Group_Id = base.AppUserInfo.Group_Id,
                School_Id = base.AppUserInfo.School_Id,
                StuId = base.AppUserInfo.Id,
            };
            bool result = studentModule.SetStudentInterest(query);
            if (result)
            {
                return ApiResult.Success("");
            }
            else
            {
                return ApiResult.Failed("兴趣爱好记录失败");
            }
        }
        #endregion


        #region 首页banner/老师信息
        [HttpPost]
        public ApiResult GetBannerIndex()
        {
            var query = new RB_HomePage_Banner()
            {
                Group_Id = base.AppUserInfo.Group_Id,
            };
            var list = appHomePageModule.GetHomePageBannerList(query).OrderBy(x => x.Sort);//banner图
            var teacherList = teacherModule.GetListByStudentId(base.AppUserInfo.Id, base.AppUserInfo.Group_Id);//老师
            //课程信息
            var planList = classModule.GetListByStudentId(base.AppUserInfo.Id, base.AppUserInfo.Group_Id);
            DateTime NextClassTime = System.DateTime.Now;
            foreach (var item in planList)
            {
                DateTime nowTime = item.ClassTimeList.Min(x => Convert.ToDateTime(x.NewPlanDateTime));
                if (nowTime < NextClassTime)
                {
                    NextClassTime = nowTime;
                }
            }
            var result = new
            {
                BannerList = list.Select(x => new { x.BannerId, x.BannerPic, x.BannerUrl }),
                TeacherList = teacherList.Select(x => new { x.TeacherName, x.TId, x.TeacherIcon, TeachTag = string.IsNullOrWhiteSpace(x.TeachTag) ? new List<string>() : JsonHelper.DeserializeObject<List<string>>(x.TeachTag), x.Nationality, x.ForeignersUrl }),
                ClassName = (planList != null && planList.Any()) ? planList.FirstOrDefault()?.ClassName : "",
                CompleteProgress = (planList != null && planList.Any()) ? planList.FirstOrDefault()?.CompleteProgress ?? 0 : 0,
                NextClassTime = (planList != null && planList.Any()) ? NextClassTime.ToString("yyyy-MM-dd HH:mm:ss") : ""
            };
            return ApiResult.Success("", result);
        }
        #endregion


        #region 首页lable(菜单)
        [HttpPost]
        public ApiResult GetLableIndex()
        {
            var query = new RB_HomePage_Lable()
            {
                Group_Id = base.AppUserInfo.Group_Id,
            };
            var list = appHomePageModule.GetHomePageLableList(query).OrderBy(x => x.Sort);
            return ApiResult.Success("", list);
        }
        #endregion



        #region 获取通讯录
        public ApiResult GetMailList()
        {

            var teacherList = teacherModule.GetListByStudentId(base.AppUserInfo.Id, base.AppUserInfo.Group_Id);//老师

            var saleList = managerModule.GetManagerListByStuId(base.AppUserInfo.Id, base.AppUserInfo.Group_Id);//销售

            var stuList = studentModule.GetListByStudentId(base.AppUserInfo.Id, base.AppUserInfo.Group_Id);//获取同班同学信息

            //账号类型(1-管理端，2,-教师端，3-助教，4-学生)
            var retult = new
            {
                TeacherList = teacherList.Select(x => new { Name = x.TeacherName, Head = x.TeacherHead, Tel = x.TeacherTel, Id = x.TId, AccountType = 2 }),
                SaleList = saleList.Select(x => new { Name = x.MName, Head = x.MHead, Tel = x.MTel, x.Sex, Id = x.MId, AccountType = 1 }),
                StuList = stuList.Select(x => new { Name = x.StuName, Head = x.StuIcon, Tel = x.StuTel, Sex = x.StuSex, Id = x.StuId, AccountType = 4 }),
            };

            return ApiResult.Success("", data: retult);
        }
        #endregion


        #region 课表
        /// <summary>
        /// 获取上课计划
        /// </summary>
        /// <returns></returns>
        public ApiResult GetStudentPlan()
        {

            var query = new Model.ViewModel.Course.RB_Class_Plan_ViewModel()
            {
                Group_Id = base.AppUserInfo.Group_Id,

                StuId = base.AppUserInfo.Id,
                StartTime = base.ParmJObj.GetStringValue("StartTime"),
                EndTime = base.ParmJObj.GetStringValue("EndTime"),
            };

            var data = classModule.GetStudentPlanModule(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-有课
                List<object> planList = 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 item in plan)
                {
                    foreach (var itemTime in item.PlanTimeList)
                    {
                        planList.Add(new
                        {
                            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 (plan.Where(x => x.LessonPlanNum > 0).Count() < plan.Count() && plan.Where(x => x.LessonPlanNum > 0).Count() > 0)
                    {
                        IsLessonStatus = 1;
                    }

                    else
                    {
                        IsLessonStatus = 0;
                    }
                    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");
                    }
                }
                result.Add(new
                {
                    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);
        }
        #endregion


        #region 约课

        /// <summary>
        /// app约课
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppointment()
        {
            var list = classModule.GetStuAppointment(base.AppUserInfo.Group_Id);

            var listStudentNumType = Common.Plugin.EnumHelper.EnumToList(typeof(StudentNumTypeEnum));
            var listCourseClassType = Common.Plugin.EnumHelper.EnumToList(typeof(CourseClassTypeEnum));
            List<object> result = new List<object>();
            foreach (var item in listStudentNumType)
            {
                List<object> courseClassTypeResult = new List<object>();
                foreach (var courseClassTypeItem in listCourseClassType)
                {
                    courseClassTypeResult.Add(new
                    {
                        courseClassTypeItem.Name,
                        courseClassTypeItem.Id,
                        OrderStudentCount = list.Where(x => (int)x.StudentNumType == item.Id && (int)x.CourseClassType == courseClassTypeItem.Id).FirstOrDefault()?.OrderStudentCount ?? 0
                    });
                }
                result.Add(new
                {
                    item.Name,
                    item.Id,
                    ChildrenList = courseClassTypeResult
                });
            }
            return ApiResult.Success("", data: result);
        }




        /// <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
    }
}
