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

namespace Edu.WebApi.Controllers.EduTask
{
    /// <summary>
    /// 改变流程相关申请
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class ChangePlanController : BaseController
    {
        /// <summary>
        /// 调课处理类对象
        /// </summary>
        private readonly ChangeClassPlanModule changeClassPlanModule = AOP.AOPHelper.CreateAOPObject<ChangeClassPlanModule>();

        /// <summary>
        /// 班级处理类对象
        /// </summary>
        private readonly ClassModule classModule = AOP.AOPHelper.CreateAOPObject<ClassModule>();
        /// <summary>
        /// 新增修改班级调课
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetChangeClassPlan()
        {
            var model = new RB_Change_ClassPlan_ViewModel()
            {
                Id = base.ParmJObj.GetInt("Id"),
                ClassId = base.ParmJObj.GetInt("ClassId"),
                CourseId = base.ParmJObj.GetInt("CourseId"),
                ChangeType = base.ParmJObj.GetInt("ChangeType"),
                MoveType = base.ParmJObj.GetInt("MoveType"),
                Remarks = base.ParmJObj.GetStringValue("Remarks")
            };
            var classModel = classModule.GetClassModule(model.ClassId);
            try
            {


                if (model.MoveType == 1)
                {
                    model.OldChangePlanItemList = Common.Plugin.JsonHelper.DeserializeObject<List<ChangePlanItem>>(base.ParmJObj.GetStringValue("OldChangePlanItemList"));
                    model.NewChangePlanItemList = Common.Plugin.JsonHelper.DeserializeObject<List<ChangePlanItem>>(base.ParmJObj.GetStringValue("NewChangePlanItemList"));
                }
                else
                {
                    if (model.ChangeType != 1)
                    {
                        string takeEffectTime = base.ParmJObj.GetStringValue("TakeEffectTime");
                        if (string.IsNullOrWhiteSpace(takeEffectTime))
                        {
                            return ApiResult.Failed("请选择生效日期");
                        }
                        model.TakeEffectTime = Convert.ToDateTime(takeEffectTime);
                    }

                    model.AllChangePlanModel = Common.Plugin.JsonHelper.DeserializeObject<AllChangePlanItem>(base.ParmJObj.GetStringValue("AllChangePlanItem"));
                }
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "SetChangeClassPlan");
            }
            if (model.MoveType == 1)//固定日期
            {
                if (model.ChangeType == 1)//调课
                {
                    if (model.OldChangePlanItemList.Count() != model.NewChangePlanItemList.Count())
                    {
                        return ApiResult.Failed("排课原次数与现有次数不一致");
                    }
                }
                else if (model.ChangeType == 2)
                {
                    if (model.NewChangePlanItemList == null || !model.NewChangePlanItemList.Any() || model.NewChangePlanItemList.FirstOrDefault()?.TeacherId == 0)
                    {
                        return ApiResult.Failed("请选择老师");
                    }
                }
                else if (model.ChangeType == 3)
                {
                    if (model.NewChangePlanItemList == null || !model.NewChangePlanItemList.Any() || model.NewChangePlanItemList.FirstOrDefault()?.ClassRoomId == 0)
                    {
                        return ApiResult.Failed("请选择教室");
                    }
                }
            }
            else //全局修改
            {
                if (model.ChangeType == 1)
                {
                    List<string> dayList = new List<string>();
                    if (model.AllChangePlanModel.DefaultTimeList != null && model.AllChangePlanModel.DefaultTimeList.Count > 0)
                    {
                        foreach (var rootItem in model.AllChangePlanModel.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(model.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 (model.AllChangePlanModel.ClassStyle == ClassStyleEnum.Week)
                            {
                                tempStr = "每周";
                            }
                            if (model.AllChangePlanModel.ClassStyle == ClassStyleEnum.Month)
                            {
                                tempStr = "每月";
                            }
                            if (model.AllChangePlanModel.ClassStyle == ClassStyleEnum.FixedDate)
                            {
                                tempStr = "固定日期";
                            }
                            return ApiResult.ParamIsNull(message: "学习时间段" + (tempStr) + message2.TrimStart(',') + "重复!");
                        }
                    }
                    else
                    {
                        return ApiResult.Failed("请输入排课信息");
                    }

                    if (classModel != null && classModel.ClassId > 0)
                    {  //获取课时分钟数
                        model.AllChangePlanModel.ClassHourMinute = classModel?.ClassHourMinute ?? 0;
                        //获取剩余总课时
                        model.AllChangePlanModel.ClassHours = (Convert.ToDecimal(classModel.ClassHours) - (classModule.GetClassFinishMinutesRepository(model.ClassId.ToString()).FirstOrDefault()?.FinishClassHours ?? 0));
                        model.AllChangePlanModel.TeacherId = classModel.Teacher_Id;
                        model.AllChangePlanModel.ClassRoomId = classModel.ClassRoomId;
                    }
                    else
                    {
                        return ApiResult.Failed("班级信息不存在");
                    }
                }
                else if (model.ChangeType == 2)
                {
                    if (model.AllChangePlanModel == null || model.AllChangePlanModel.TeacherId == 0)
                    {
                        return ApiResult.Failed("请选择老师");
                    }
                }
                else if (model.ChangeType == 3)
                {
                    if (model.AllChangePlanModel == null || model.AllChangePlanModel.ClassRoomId == 0)
                    {
                        return ApiResult.Failed("请选择教室");
                    }
                }
            }
            if (model.OldChangePlanItemList != null && model.OldChangePlanItemList.Any())
            {
                model.SourceData = JsonHelper.Serialize(model.OldChangePlanItemList);
            }
            else
            {
                model.SourceData = "";
            }
            if (model.MoveType == 2)//全局并且是调课的时候赋值
            {
                if (model.AllChangePlanModel != null)
                {
                    model.TargetData = JsonHelper.Serialize(model.AllChangePlanModel);
                }
                else
                {
                    model.TargetData = "";
                }
            }
            else
            {
                if (model.NewChangePlanItemList != null && model.NewChangePlanItemList.Any())
                {
                    model.TargetData = JsonHelper.Serialize(model.NewChangePlanItemList);
                }
                else
                {
                    model.TargetData = "";
                }
            }
            if (model.Id == 0)
            {
                model.CreateBy = base.UserInfo.Id;
                model.CreateTime = DateTime.Now;
                model.Group_Id = base.UserInfo.Group_Id;
                model.School_Id = classModel.School_Id;
            }
            model.UpdateBy = base.UserInfo.Id;
            model.UpdateTime = DateTime.Now;
            bool flag = changeClassPlanModule.SetChangeClassPlanModule(model);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }




        public ApiResult TestUpdateClassPlan()
        {

            int id = base.ParmJObj.GetInt("Id");
            var result = changeClassPlanModule.UpdateChangeClassPlan(id);
            return ApiResult.Success("");
        }
    }
}
