using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Edu.Common.API;
using Edu.Common.Plugin;
using Edu.Model.CacheModel;
using Edu.Model.Entity.System;
using Edu.Module.System;
using Edu.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Edu.WebApi.Controllers.Public
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class HolidayController : BaseController
    {
        /// <summary>
        /// 节假日处理类对象
        /// </summary>
        private readonly HolidayModule holidayModule = new HolidayModule();

        /// <summary>
        /// 班级处理类对象
        /// </summary>
        private readonly Module.Course.ClassModule classModule = new Module.Course.ClassModule();

        #region 节假日管理
        /// <summary>
        /// 新增修改广告基础信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>

        [HttpPost]
        public ApiResult SetHoliday()
        {
            UserInfo userInfo = base.UserInfo;

            var startDate = base.ParmJObj.GetStringValue("StartTime");
            var endDate = base.ParmJObj.GetStringValue("EndTime");

            if (string.IsNullOrEmpty(startDate))
            {
                return ApiResult.Failed("节假日开始时间不能为空");
            }
            if (string.IsNullOrEmpty(endDate))
            {
                return ApiResult.Failed("节假日结束时间不能为空");
            }
            RB_System_Holiday dmodel = new RB_System_Holiday
            {
                DayType = base.ParmJObj.GetInt("DayType", 0),
                StartTime = Convert.ToDateTime(startDate),
                EndTime = Convert.ToDateTime(endDate)
            };
            if (dmodel.StartTime > dmodel.EndTime)
            {
                return ApiResult.Failed("节假日开始时间不能大于结束时间");
            }
            //先判断日期是否已存在
            var oldList = holidayModule.GetExistHoliday(startDate, endDate);
            if (oldList != null && oldList.Any(x => x.HolidayId != dmodel.HolidayId))
            {
                return ApiResult.Failed("节假日时间范围重合");
            }



            if (dmodel.HolidayId == 0)
            {
                dmodel.CreateDate = System.DateTime.Now;
                dmodel.Status = 0;
                dmodel.Group_Id = userInfo.Group_Id;
                dmodel.School_Id = userInfo.School_Id;
            }
            bool flag = holidayModule.SetHoliday(dmodel);
            if (flag)
            {

                if (dmodel.DayType == 1)//判断节假日是否有排课计划
                {
                    var planList = classModule.GetClassPlanList_V3(new Model.ViewModel.Course.RB_Class_Plan_ViewModel
                    {
                        Group_Id = userInfo.Group_Id,
                        StartTime = dmodel.StartTime.HasValue ? dmodel.StartTime.Value.ToString("yyyy-MM-dd 00:00:00") : "",
                        EndTime = dmodel.EndTime.HasValue ? dmodel.EndTime.Value.ToString("yyyy-MM-dd 00:00:00") : ""
                    });

                    if (planList != null && planList.Any())
                    {
                        return ApiResult.Success("班级：" + string.Join(",", planList.Select(x => x.ClassName)) + "存在排课");
                    }
                }

                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 删除节假日
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelHoliday()
        {
            var HolidayId = base.ParmJObj.GetInt("HolidayId");
            if (HolidayId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            var flag = holidayModule.DelHoliday(HolidayId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 获取节假日列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetHolidayList()
        {
            UserInfo userInfo = base.UserInfo;
            ResultPageModel pmodel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var startDate = base.ParmJObj.GetStringValue("StartTime");
            var endDate = base.ParmJObj.GetStringValue("EndTime");
            RB_System_Holiday dmodel = new RB_System_Holiday
            {
                DayType = base.ParmJObj.GetInt("DayType", 0)
            };
            try
            {
                if (!string.IsNullOrWhiteSpace(startDate))
                {
                    dmodel.StartTime = Convert.ToDateTime(startDate);
                }
                if (!string.IsNullOrWhiteSpace(endDate))
                {
                    dmodel.EndTime = Convert.ToDateTime(endDate);
                }
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "GetHolidayList");
            }
            List<RB_System_Holiday> list = holidayModule.GetPageList(pmodel.PageIndex, pmodel.PageSize, dmodel, out long count);
            pmodel.Count = Convert.ToInt32(count.ToString());
            pmodel.PageData = list.Select(x => new
            {
                x.HolidayId,
                StartTime = x.StartTime.HasValue ? x.StartTime.Value.ToString("yyyy-MM-dd") : "",
                EndTime = x.EndTime.HasValue ? x.EndTime.Value.ToString("yyyy-MM-dd") : "",
                x.DayType
            });
            return ApiResult.Success("", pmodel);
        }

        /// <summary>
        /// 获取节假日详情
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetHolidayInfo()
        {
            int HolidayId = base.ParmJObj.GetInt("HolidayId", 0);
            if (HolidayId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            var model = holidayModule.GetEntity(HolidayId);
            if (model != null)
            {
                var obj = new
                {
                    model.HolidayId,
                    StartTime = model.StartTime.HasValue ? model.StartTime.Value.ToString("yyyy-MM-dd") : "",
                    EndTime = model.EndTime.HasValue ? model.EndTime.Value.ToString("yyyy-MM-dd") : "",
                    model.DayType
                };
                return ApiResult.Success("请求成功！", obj);
            }
            else
            {

                return ApiResult.Failed("请求失败，数据不存在！");
            }
        }





        /// <summary>
        /// 批量新增节假日
        /// </summary>
        /// <returns></returns>
        public ApiResult InsertHoliday()
        {
            //SetHoliday

            string apiResult = Common.Plugin.HttpHelper.HttpGet("http://timor.tech/api/holiday/year/2020/");
            JObject parmsJob = JObject.Parse(apiResult);
            string resultCode = parmsJob.GetStringValue("code");
            string holidayList = parmsJob.GetStringValue("holiday");

            return ApiResult.Success("");
        }


        #endregion

    }
}
