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;
using Edu.Common.Enum.Exam;
using Edu.Common.Enum.Question;
using Edu.Common.Plugin;
using Edu.Model.ViewModel.Exam;
using Edu.Model.ViewModel.Grade;
using Edu.Model.ViewModel.LearningGarden;
using Edu.Model.ViewModel.Scroll;
using Edu.Model.ViewModel.User;
using Edu.Module.Course;
using Edu.Module.EduTask;
using Edu.Module.Public;
using Edu.Module.User;
using Edu.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace Edu.WebApi.Controllers.Applet
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class AppletCenterController : AppletBaseController
    {
        /// <summary>
        /// 账号处理类
        /// </summary>
        private readonly AccountModule accountModule = new AccountModule();
        /// <summary>
        /// 学生管理处理类
        /// </summary>
        private readonly StudentModule studentModule = new StudentModule();
        /// <summary>
        /// 订单处理类
        /// </summary>
        private readonly OrderModule orderModule = new OrderModule();
        /// <summary>
        /// 课程处理类对象
        /// </summary>
        private readonly CourseModule courseModule = AOP.AOPHelper.CreateAOPObject<CourseModule>();
        /// <summary>
        /// 滚动开班
        /// </summary>
        private readonly ScrollClassModule scrollClassModule = new ScrollClassModule();
        /// <summary>
        /// 讲师处理类对象
        /// </summary>
        private readonly TeacherModule teacherModule = AOP.AOPHelper.CreateAOPObject<TeacherModule>();


        #region 获取个人中心数据

        /// <summary>
        /// 获取我的个人中心
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMyCenterInfo()
        {
            var userInfo = base.AppletUserInfo;

            //获取学生信息
            var stuModel = studentModule.GetStudentListModule(new RB_Student_ViewModel() { Group_Id = userInfo.Group_Id, StuId = userInfo.AccountId }).FirstOrDefault();
            if (stuModel == null) 
            {
                return ApiResult.Failed("账号不存在"); 
            }
            //获取协助人员
            List<object> RAssistList = new List<object>();
            //首先获取学员的创建人 （市场经理）
            if (stuModel.CreateBy > 0)
            {
                var EnterModel = UserReidsCache.GetUserLoginInfo(stuModel.CreateBy);
                RAssistList.Add(new
                {
                    AssistId = stuModel.EnterID,
                    AssistTypeName = "市场经理",
                    EmployeeName = EnterModel.AccountName,
                    EnterModel.UserIcon,
                    Mobile = EnterModel.UserMobile
                });
            }
            var assistList = studentModule.GetStuAssistListModule(userInfo.AccountId);
            foreach (var item in assistList)
            {
                var empModel = accountModule.GetEmployeeInfo(item.AssistId);
                RAssistList.Add(new
                {
                    item.AssistId,
                    AssistTypeName = item.AssistType.ToName(),
                    EmployeeName = empModel?.EmployeeName??"",
                    UserIcon = empModel?.UserIcon??"",
                    Mobile = empModel?.Account??""
                });
            }
            //获取课程信息(正在学习中的)
            object CourseInfo = new object();
            var LearningInfo = studentModule.GetLearningCourseInfo(userInfo.AccountId, userInfo.Group_Id);
            if (LearningInfo != null)
            {
                //获取课程
                var courseModel = courseModule.GetCourseModule(LearningInfo.CourseId);
                //获取课时信息
                var guestModel = orderModule.GetOrderGusetHoursInfo(LearningInfo.GuestId, LearningInfo.ClassId);
                CourseInfo = new
                {
                    State = 1,
                    TotalHours = guestModel?.TotalHours ?? 0,
                    CompleteHours = guestModel?.CompleteHours ?? 0,
                    MakeUpHours= guestModel?.MakeUpHours??0,
                    AbsenceNum = guestModel?.AbsenceNum ?? 0,
                    LeaveNum = guestModel?.LeaveNum ?? 0,
                    CourseId = courseModel?.CourseId ?? 0,
                    CourseName = courseModel?.CourseName ?? "",
                    CourseRate = courseModel?.CourseRate.ToName() ?? "",
                    B2BIcon = courseModel?.B2BIcon ?? "",
                    B2BBackground = courseModel?.B2BBackground ?? "",
                    LearningInfo.ClassStatus,
                    ClassStatusName = LearningInfo.ClassStatus.ToName(),
                    LearningInfo.ClassName,
                    LearningInfo.ClassScrollType
                };
            }
            else 
            {
                CourseInfo = new
                {
                    State = 2//没有课程信息
                };
            }

            //获取订单合同
            var orderModel = studentModule.GetStuendOrderNum(userInfo.AccountId, userInfo.Group_Id);

            return ApiResult.Success("", new
            {
                AccountId = userInfo.Id,
                StuId = userInfo.AccountId,
                stuModel.StuName,
                stuModel.StuIcon,
                stuModel.StuSex,
                orderModel.OrderNum,
                orderModel.StudyAbroadNum,
                orderModel.ContractNum,
                AssistList = RAssistList,
                CourseInfo
            });
        }

        #endregion


        #region 学员预约

        /// <summary>
        /// 获取学员预约的基本信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetScrollAppointmentBaseInfo() {
            var userInfo = base.AppletUserInfo;
            
            var Robj = scrollClassModule.GetScrollAppointmentBaseInfo(userInfo, out string Rmsg);
            if (Rmsg == "")
            {
                return ApiResult.Success("", Robj);
            }
            else
            {
                return ApiResult.Failed(Rmsg);
            }
        }

        /// <summary>
        /// 获取学员可预约老师列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetScrollAppointmentTeacherList() {
            var userInfo = base.AppletUserInfo;
            string Date = ParmJObj.GetStringValue("Date");
            int SchoolId = ParmJObj.GetInt("SchoolId", -1);
            if (string.IsNullOrEmpty(Date)) {
                return ApiResult.ParamIsNull("请传递日期");
            }
            Date = Convert.ToDateTime(Date).ToString("yyyy-MM-dd");
            var Robj = scrollClassModule.GetScrollAppointmentTeacherList(userInfo, Date, SchoolId, out string Rmsg);
            if (Rmsg == "")
            {
                return ApiResult.Success("", Robj);
            }
            else {
                return ApiResult.Failed(Rmsg);
            }
        }

        /// <summary>
        /// 学员预约
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetScrollAppointment() {
            var userInfo = base.AppletUserInfo;
            RB_Scroll_Appointment_ViewModel demodel = JsonHelper.DeserializeObject<RB_Scroll_Appointment_ViewModel>(base.RequestParm.Msg.ToString());
            if (demodel.AccountId <= 0) {
                return ApiResult.ParamIsNull("请传递老师账号ID");
            }
            if (demodel.TeacherId <= 0) {
                return ApiResult.ParamIsNull("请传递老师编号ID");
            }
            if (demodel.Date <= DateTime.Now) {
                return ApiResult.ParamIsNull("预约日期有误");
            }
            if (string.IsNullOrEmpty(demodel.ShiftSort)) {
                return ApiResult.ParamIsNull("请传递上课时段");
            }
            #region 验证是否连续的时段

            List<int> SortList = JsonHelper.DeserializeObject<List<int>>("[" + demodel.ShiftSort + "]");
            int MinSort = SortList.Min(x => x);
            string ShiftSort = "";
            for (var i = 0; i < SortList.Count(); i++) {
                ShiftSort += (MinSort + i) + ",";
            }
            if (ShiftSort != demodel.ShiftSort + ",") {
                return ApiResult.ParamIsNull("需预约连续的时段");
            }
            #endregion

            demodel.StuId = userInfo.AccountId;
            demodel.State = Common.Enum.Course.CourseAppointStateEnum.WaitSure;
            demodel.Status = 0;
            demodel.Group_Id = userInfo.Group_Id;
            demodel.CreateBy = 0;
            demodel.CreateTime = DateTime.Now;
            demodel.UpdateBy = 0;
            demodel.UpdateTime = DateTime.Now;
            string msg = scrollClassModule.SetScrollAppointment(demodel, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 获取枚举列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCourseAppointStateEnumList()
        {
            var list = EnumHelper.EnumToList(typeof(Common.Enum.Course.CourseAppointStateEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                x.Name,
                x.Id
            }));
        }

        /// <summary>
        /// 获取讲师列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetTeacherList()
        {
            var query = new RB_Teacher_ViewModel()
            {
                IsQLeave = base.ParmJObj.GetInt("IsQLeave")
            };
            query.Group_Id = base.AppletUserInfo.Group_Id;
            query.School_Id = -1;
            var list = teacherModule.GetTeacherListModule(query);
            return ApiResult.Success(data: list);
        }

        /// <summary>
        /// 获取我的预约分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMyAppointPageList() {
            var userInfo = base.AppletUserInfo;
            ResultPageModel pmodel = JsonHelper.DeserializeObject<ResultPageModel>(base.RequestParm.Msg.ToString());
            RB_Scroll_Appointment_ViewModel demodel = JsonHelper.DeserializeObject<RB_Scroll_Appointment_ViewModel>(base.RequestParm.Msg.ToString());
            demodel.Group_Id = userInfo.Group_Id;
            demodel.StuId = userInfo.AccountId;

            var list = scrollClassModule.GetAppointPageList(pmodel.PageIndex, pmodel.PageSize, out long count, demodel);
            pmodel.Count = count;
            pmodel.PageData = list.Select(x => new
            {
                x.Id,
                Date = x.Date.ToString("yyyy-MM-dd"),
                x.AccountId,
                x.TeacherId,
                x.TeacherName,
                x.TeacherHead,
                x.StuId,
                x.StuName,
                x.CourseId,
                x.CourseName,
                x.ChapterNo,
                x.CourseTimeList,
                x.RoomId,
                x.RoomName,
                x.RoomSchoolName,
                x.State,
                StateName = x.State.ToName(),
                CreateTime = x.CreateTime.ToString("yyyy-MM-dd HH:mm")
            });
            return ApiResult.Success("", pmodel);
        }

        /// <summary>
        /// 取消预约
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult CancelAppointment() {
            var userInfo = base.AppletUserInfo;
            int AppointId = ParmJObj.GetInt("AppointId");
            if (AppointId <= 0) {
                return ApiResult.ParamIsNull("请传递预约Id");
            }

            string msg = scrollClassModule.CancelAppointment(AppointId, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed(msg);
            }
        }
        #endregion
    }
}
