using Edu.Cache.User;
using Edu.Common.API;
using Edu.Common.Enum.Duty;
using Edu.Common.Plugin;
using Edu.Model.ViewModel.Duty;
using Edu.Module.Duty;
using Edu.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Edu.WebApi.Controllers.Duty
{
    /// <summary>
    /// 值班计划控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class DutyPlanController : BaseController
    {
        private readonly DutyPlanModule dutyPlanModule = AOP.AOPHelper.CreateAOPObject<DutyPlanModule>();

        /// <summary>
        /// 获取值班计划分页列表【管理端】
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDutyPlanPage()
        {
            var pageModel = Common.Plugin.JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Duty_Plan_ViewModel()
            {
                QStartDate = base.ParmJObj.GetStringValue("StartDate"),
                QEndDate = base.ParmJObj.GetStringValue("EndDate"),
                IsFinish=base.ParmJObj.GetInt("IsFinish"),
                QAttendanceStatus=base.ParmJObj.GetInt("QAttendanceStatus")
            };
            if (!string.IsNullOrEmpty(base.ParmJObj.GetStringValue("QDutyStatus")))
            {
                query.QDutyStatus = base.ParmJObj.GetInt("QDutyStatus", -1);
            }
            else
            {
                query.QDutyStatus = -1;
            }
            var dutyManList = Common.Plugin.JsonHelper.DeserializeObject<List<int>>(base.ParmJObj.GetStringValue("EmployeeIds"));
            if (dutyManList != null && dutyManList.Count > 0)
            {
                query.QDutyMan = string.Join(",", dutyManList);
            }
            query.SchoolIdList = Common.Plugin.JsonHelper.DeserializeObject<List<int>>(base.ParmJObj.GetStringValue("School_Ids"));
            query.Group_Id = base.UserInfo.Group_Id;
            List<object> result = new List<object>();
            dutyPlanModule.UpdateDutyModule();
            var list = dutyPlanModule.GetDutyPlanPageModule(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);
            foreach (var item in list)
            {
                if (item.CreateBy > 0)
                {
                    item.CreateByName = UserReidsCache.GetUserLoginInfo(item.CreateBy)?.AccountName ?? "";
                }
                if (item.UpdateBy > 0)
                {
                    item.UpdateByName = UserReidsCache.GetUserLoginInfo(item.UpdateBy)?.AccountName ?? "";
                }
                result.Add(new
                {
                    item.Id,
                    PlanDate = Common.ConvertHelper.FormatDate(item.Date),
                    item.SchoolName,
                    item.School_Id,
   
                    PlanDetails = item?.PlanDetails?.Select(qitem => new
                    {
                        qitem.Id,
                        qitem.PlanId,
                        qitem.DutyMan,
                        qitem.DutyManName,
                        qitem.StartTime,
                        qitem.EndTime,
                        qitem.Shift,
                        qitem.ShiftName,
                        qitem.Status,
                        qitem.StatusStr,
                        qitem.CheckTimeStr,
                        qitem.CheckLateTime,
                        CheckLateTimeStr = (qitem.CheckTimeStr!="未打卡"?(  qitem.CheckLateTime > 0 ? string.Format("[迟到{0}分钟]", qitem.CheckLateTime) : "[正常]"):""),
                        qitem.FinishTimeStr,
                        qitem.FinishLateTime,
                        FinishLateTimeStr = (qitem.FinishTimeStr!="未打卡"?(qitem.FinishLateTime > 0 ? string.Format("[早退{0}分钟]", qitem.FinishLateTime) : "[正常]"):""),
                    })
                });
            }
            pageModel.Count = rowsCount;
            pageModel.PageData = result;
            return ApiResult.Success(data: pageModel);
        }


        /// <summary>
        /// 获取我的值班计划分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMyDutyPlanPage()
        {
            dutyPlanModule.UpdateDutyModule();
            var pageModel = Common.Plugin.JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Duty_Plan_ViewModel()
            {
                School_Id = base.ParmJObj.GetInt("School_Id"),
                QStartDate=base.ParmJObj.GetStringValue("StartDate"),
                QEndDate=base.ParmJObj.GetStringValue("EndDate")
            };
            query.QDutyMan = base.UserInfo.Id.ToString();
            query.Group_Id = base.UserInfo.Group_Id;
            List<object> result = new List<object>();
            var list = dutyPlanModule.GetMyDutyPlanPageModule(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);
            foreach (var item in list)
            {
                if (item.CreateBy > 0)
                {
                    item.CreateByName = UserReidsCache.GetUserLoginInfo(item.CreateBy)?.AccountName ?? "";
                }
                //当前班次
                var currentModel = new RB_Duty_PlanDetails_ViewModel();
                //上一个班次(交班)
                var previousModel = new List<RB_Duty_PlanDetails_ViewModel>();
                //下一个班次(接班)
                var nextModel = new List<RB_Duty_PlanDetails_ViewModel>();
                var dic = dutyPlanModule.CalcCurrentDutyManIndexModule_V3(item);
                //当前班次
                currentModel = dic["current"].FirstOrDefault();
                string jiaoBanMan = "";//交班人
                string jieBanMan = "";//接班人
                if (dic["next"] != null&& dic["next"].Count>0)
                {
                    jieBanMan = string.Join(",", dic["next"].Select(qitem => qitem.DutyManName));
                }

                if (dic["previous"] != null && dic["previous"].Count>0)
                {
                    jiaoBanMan = string.Join(",", dic["previous"].Select(qitem => qitem.DutyManName)); ;
                }
                DutyStatusEnum NewStatus = Common.Enum.Duty.DutyStatusEnum.NoStart;
                if (currentModel.Status == Common.Enum.Duty.DutyStatusEnum.NoStart)
                {
                    NewStatus = dutyPlanModule.CalcDutyPlanStatusModule(item.Date, currentModel.StartTime, currentModel.EndTime);
                }
                else
                {
                    NewStatus = currentModel.Status;
                }
                result.Add(new
                {
                    item.Id,
                    PlanDate = Common.ConvertHelper.FormatDate(item.Date),
                    item.SchoolName,
                    currentModel.Shift,
                    currentModel.ShiftName,
                    currentModel.StartTime,
                    currentModel.EndTime,
                    currentModel.DutyMan,
                    PlanList = currentModel?.WorkContentList ?? new  List<RB_Duty_PlanWork_ViewModel>(),
                    currentModel.BurstCount,
                    currentModel.HandoverCount,
                    ReciveMan= jieBanMan,
                    GiveMan= jiaoBanMan,
                    item.CreateByName,
                    currentModel.Status,
                    currentModel.StatusStr,
                    NewStatus,
                    item.TotalBurstCount,
                    item.TotalHandoverCount,
                    currentModel.CheckTimeStr,
                    currentModel.CheckLateTime,
                    CheckLateTimeStr = (currentModel.CheckTimeStr != "未打卡" ? (currentModel.CheckLateTime > 0 ? string.Format("[迟到{0}分钟]", currentModel.CheckLateTime) : "[正常]") : ""),
                    currentModel.FinishTimeStr,
                    currentModel.FinishLateTime,
                    FinishLateTimeStr = (currentModel.FinishTimeStr != "未打卡" ? (currentModel.FinishLateTime > 0 ? string.Format("[早退{0}分钟]", currentModel.FinishLateTime) : "[正常]") : ""),
                });
            }
            pageModel.Count = rowsCount;
            pageModel.PageData = result;
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 新增修改排班计划
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SaveDutyPlan()
        {
            var model = new RB_Duty_Plan_ViewModel()
            {
                Id = base.ParmJObj.GetInt("Id"),
                Date = base.ParmJObj.GetDateTime("Date"),
                School_Id = base.ParmJObj.GetInt("School_Id")
            };
            try
            {
                model.PlanDetails = Common.Plugin.JsonHelper.DeserializeObject<List<RB_Duty_PlanDetails_ViewModel>>(base.ParmJObj.GetStringValue("PlanDetails"));
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "SaveDutyPlan_PlanDetails");
            }
            model.Group_Id = base.UserInfo.Group_Id;
            model.Status = Common.Enum.DateStateEnum.Normal;
            model.CreateBy = base.UserInfo.Id;
            model.CreateTime = DateTime.Now;
            model.UpdateBy = base.UserInfo.Id;
            model.UpdateTime = DateTime.Now;
            if (dutyPlanModule.CheckExistsDutyPlanModule(model))
            {
                return ApiResult.Failed(string.Format("已经存在【{0}】的值班计划!请直接修改!", Common.ConvertHelper.FormatDate(model.Date)));
            }
            bool flag = dutyPlanModule.SetDutyPlanModule(model, base.UserInfo);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 获取排班计划详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDutyPlan()
        {
            var Id = base.ParmJObj.GetInt("Id");
            var model = dutyPlanModule.GetDutyPlanModule(Id);
            return ApiResult.Success(data: model);
        }

        /// <summary>
        /// 删除排班计划
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult RemoveDutyPlan()
        {
            var Id = base.ParmJObj.GetInt("Id");
            var model = dutyPlanModule.RemoveDutyPlanModule(Id,base.UserInfo);
            return ApiResult.Success(data: model);
        }

        /// <summary>
        /// 用户值班
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult OnDuty()
        {
            var Id = base.ParmJObj.GetInt("Id");
            var Shift = base.ParmJObj.GetInt("Shift");
            int UserId = base.UserInfo.Id;
            int DutyMan = base.ParmJObj.GetInt("DutyMan");
            if (DutyMan > 0)
            {
                UserId = DutyMan;
            }
            var obj = dutyPlanModule.OnDutyModule(Id, Shift, UserId);
            return ApiResult.Success(data: obj);
        }

        /// <summary>
        /// 用户值班
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDutyWork()
        {
            var Id = base.ParmJObj.GetInt("Id");
            var Shift = base.ParmJObj.GetInt("Shift");
            int UserId = base.UserInfo.Id;
            int DutyMan = base.ParmJObj.GetInt("DutyMan");
            if (DutyMan > 0)
            {
                UserId = DutyMan;
            }
            var obj = dutyPlanModule.OnDutyModule(Id, Shift, UserId, isQueryWork: true);
            return ApiResult.Success(data: obj);
        }

        /// <summary>
        /// 用户值班【第二版】
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult OnDuty_V2()
        {
            var Id = base.ParmJObj.GetInt("Id");
            var Shift = base.ParmJObj.GetInt("Shift");
            int UserId = base.UserInfo.Id;
            int DutyMan = base.ParmJObj.GetInt("DutyMan");
            if (DutyMan > 0)
            {
                UserId = DutyMan;
            }
            var obj = dutyPlanModule.OnDutyModule_V2(Id, Shift, UserId);
            return ApiResult.Success(data: obj);
        }

        /// <summary>
        /// 用户值班【第二版】
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDutyWork_V2()
        {
            var Id = base.ParmJObj.GetInt("Id");
            var Shift = base.ParmJObj.GetInt("Shift");
            int UserId = base.UserInfo.Id;
            int DutyMan = base.ParmJObj.GetInt("DutyMan");
            if (DutyMan > 0)
            {
                UserId = DutyMan;
            }
            var obj = dutyPlanModule.OnDutyModule_V2(Id, Shift, UserId, isQueryWork: true);
            return ApiResult.Success(data: obj);
        }

        /// <summary>
        /// 获取值班详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDutyInfo()
        {
            var Id = base.ParmJObj.GetInt("Id");
            var obj = dutyPlanModule.GetDutyInfoModule(Id);
            return ApiResult.Success(data: obj);
        }

        /// <summary>
        /// 获取交接班次列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetHandoverShiftList()
        {
            var obj = dutyPlanModule.GetHandoverShiftListModule();
            return ApiResult.Success(data: obj);
        }

        /// <summary>
        /// 值班打卡/值班交接
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DutyCheck()
        {
            var Id = base.ParmJObj.GetInt("Id");
            if (Id <= 0)
            {
                return ApiResult.ParamIsNull(message: "请传递值班编号!");
            }
            var Shift = base.ParmJObj.GetInt("Shift");
            if (Shift <= 0)
            {
                return ApiResult.ParamIsNull(message: "请传递值班班次!");
            }
            var Status = base.ParmJObj.GetInt("Status");
            //突发事件
            int IsBurst = base.ParmJObj.GetInt("IsBurst");
            //工作交接说明
            int IsHandover = base.ParmJObj.GetInt("IsHandover");
            //交接班次
            string HandoverDlandetails = base.ParmJObj.GetStringValue("HandoverDlandetails");
            List<RB_Duty_Content_ViewModel> list = new List<RB_Duty_Content_ViewModel>();
            if (Status == 2)
            {
                if (IsBurst == 1)
                {
                    list.Add(new RB_Duty_Content_ViewModel()
                    {
                        Id = 0,
                        PlanShift = Shift,
                        PlanType = 3,
                        PlanId = Id,
                        OtherContent = "无",
                        OtherRemark = "无",
                        WorkContent = "",
                        WorkIsFinish = 1,
                        ItemId = 0,
                        ItemType = 0,
                        CreateBy = base.UserInfo.Id,
                        CreateTime = DateTime.Now,
                        UpdateBy=base.UserInfo.Id,
                        UpdateTime=DateTime.Now,
                        Group_Id = base.UserInfo.Group_Id,
                    }); ;
                }
                if (IsHandover==1)
                {
                    list.Add(new RB_Duty_Content_ViewModel()
                    {
                        Id = 0,
                        PlanShift = Shift,
                        PlanType = 2,
                        PlanId = Id,
                        OtherContent = "无",
                        OtherRemark = "无",
                        WorkContent = "",
                        WorkIsFinish = 1,
                        ItemId = 0,
                        ItemType = 0,
                        CreateBy = base.UserInfo.Id,
                        CreateTime = DateTime.Now,
                        UpdateBy = base.UserInfo.Id,
                        UpdateTime = DateTime.Now,
                        Group_Id = base.UserInfo.Group_Id,
                    });
                }
            }
            var flag = dutyPlanModule.DutyCheckModule(Id, Shift, base.UserInfo.Id, Status, list, HandoverDlandetails, out string message);
            return flag ? ApiResult.Success() : ApiResult.Failed(message: message);
        }

        /// <summary>
        /// 新增修改值班事项
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetDutyContent()
        {
            var model = new RB_Duty_Content_ViewModel()
            {
                Id = base.ParmJObj.GetInt("Id"),
                PlanShift = base.ParmJObj.GetInt("PlanShift"),
                PlanType = base.ParmJObj.GetInt("PlanType"),
                PlanId = base.ParmJObj.GetInt("PlanId"),
                OtherContent = base.ParmJObj.GetStringValue("OtherContent"),
                OtherRemark = base.ParmJObj.GetStringValue("OtherRemark"),
                WorkContent = base.ParmJObj.GetStringValue("WorkContent"),
                WorkIsFinish = base.ParmJObj.GetInt("WorkIsFinish"),
                ItemId = base.ParmJObj.GetInt("ItemId"),
                ItemType=base.ParmJObj.GetInt("ItemType"),
            };
            try
            {
                model.FileList = Common.Plugin.JsonHelper.DeserializeObject<List<string>>(base.ParmJObj.GetStringValue("FileList"));
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "SetDutyContent_FileList");
            }
            if (model.FileList == null)
            {
                model.FileList = new List<string>();
            }
            if (model.FileList != null && model.FileList.Count > 0)
            {
                model.FileURL = Common.Plugin.JsonHelper.Serialize(model.FileList);
            }
            else
            {
                model.FileURL = "";
            }
            if (model.PlanType == 1 && model.ItemType==2 && string.IsNullOrEmpty(model.WorkContent))
            {
                return ApiResult.Failed(message: "请填写完成内容!");
            }
            model.Group_Id = base.UserInfo.Group_Id;
            model.Status = Common.Enum.DateStateEnum.Normal;
            model.CreateBy = base.UserInfo.Id;
            model.CreateTime = DateTime.Now;
            model.UpdateBy = base.UserInfo.Id;
            model.UpdateTime = DateTime.Now;
            bool flag = dutyPlanModule.SetDutyContentModule(model);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 删除值班内容
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult RemoveDutyContent()
        {
            var Id = base.ParmJObj.GetInt("Id");
            var model = dutyPlanModule.RemoveDutyContentModule(Id);
            return ApiResult.Success(data: model);
        }

        /// <summary>
        /// 获取访客分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetVisitorPage()
        {
            var pageModel = Common.Plugin.JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Visitor_ViewModel()
            {
                PlanId = base.ParmJObj.GetInt("PlanId"),
                KeyWords = base.ParmJObj.GetStringValue("KeyWords"),
                IsQueryAll = base.ParmJObj.GetInt("IsQueryAll"),//1-查看全部
                QReserveClassIds = base.ParmJObj.GetStringValue("QReserveClassIds"),
            };
            if (query.IsQueryAll != 1)
            {
                query.CreateBy = base.UserInfo.Id;
            }
            query.Group_Id = base.UserInfo.Group_Id;
            List<object> result = new List<object>();
            var list = dutyPlanModule.GetVisitorPageModule(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);
            foreach (var item in list)
            {
                if (item.CreateBy > 0)
                {
                    item.CreateByName = UserReidsCache.GetUserLoginInfo(item.CreateBy)?.AccountName ?? "";
                }
                result.Add(new
                {
                    item.Id,
                    item.Name,
                    item.Tel,
                    item.WeChatNum,
                    item.CourseName,
                    item.StudyTime,
                    item.LevelType,
                    item.CreateByName,
                    item.VisitorStatus,
                    item.VisitorStatusStr,
                    item.Evaluate,
                    item.VisitTimes,
                    item.Remark,
                    item.Age,
                    CreateTimeStr = Common.ConvertHelper.FormatDate(item.CreateTime)
                });
            }
            pageModel.Count = rowsCount;
            pageModel.PageData = result;
            return ApiResult.Success(data: pageModel);
        }


        /// <summary>
        /// 新增修改访客
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetVisitor()
        {
            var model = new RB_Visitor_ViewModel()
            {
                Id = base.ParmJObj.GetInt("Id"),
                Name = base.ParmJObj.GetStringValue("Name"),
                Tel = base.ParmJObj.GetStringValue("Tel"),
                WeChatNum = base.ParmJObj.GetStringValue("WeChatNum"),
                CourseName = base.ParmJObj.GetStringValue("CourseName"),
                StudyTime = base.ParmJObj.GetStringValue("StudyTime"),
                LevelType = base.ParmJObj.GetStringValue("LevelType"),
                PlanId = base.ParmJObj.GetInt("PlanId"),
                Remark = base.ParmJObj.GetStringValue("Remark"),
                Evaluate = base.ParmJObj.GetStringValue("Evaluate"),
                VisitorStatus = base.ParmJObj.GetInt("VisitorStatus"),
                Age=base.ParmJObj.GetInt("Age"),
            };
            model.Group_Id = base.UserInfo.Group_Id;
            model.Status = Common.Enum.DateStateEnum.Normal;
            model.CreateBy = base.UserInfo.Id;
            model.CreateTime = DateTime.Now;
            bool flag = dutyPlanModule.SetVisitorModule(model);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 修改访客删除状态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult RemoveVisitor()
        {
            var Id = base.ParmJObj.GetInt("Id");
            int Status = base.ParmJObj.GetInt("Status");
            var model = dutyPlanModule.RemoveVisitorModule(Id, Status);
            return ApiResult.Success(data: model);
        }

        /// <summary>
        /// 根据编号获取访客信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetVisitor()
        {
            var Id = base.ParmJObj.GetInt("Id");
            var model = dutyPlanModule.GetVisitorModule(Id);
            return ApiResult.Success(data: model);
        }

        /// <summary>
        /// 修改访客状态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult UpdateVisitor()
        {
            var model = new RB_Visitor_ViewModel()
            {
                Id = base.ParmJObj.GetInt("Id"),
                VisitorStatus = base.ParmJObj.GetInt("VisitorStatus"),
                Evaluate = base.ParmJObj.GetStringValue("Evaluate"),
                Remark = base.ParmJObj.GetStringValue("Remark"),
            };
            bool flag = dutyPlanModule.UpdateVisitorModule(model);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }
    }
}
