using Edu.Common.Enum;
using Edu.Common.Enum.Duty;
using Edu.Common.Enum.System;
using Edu.Common.Message;
using Edu.Model.CacheModel;
using Edu.Model.ViewModel.Duty;
using Edu.Model.ViewModel.User;
using Edu.Repository.Duty;
using Edu.Repository.User;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VT.FW.AOP.CustomerAttribute;
using VT.FW.DB;

namespace Edu.Module.Duty
{
    /// <summary>
    /// 值班计划处理类
    /// </summary>
    public class DutyPlanModule
    {
        /// <summary>
        /// 值班计划仓储层对象
        /// </summary>
        private readonly RB_Duty_PlanRepository duty_PlanRepository = new RB_Duty_PlanRepository();

        /// <summary>
        /// 值班班次仓储层对象
        /// </summary>
        private readonly RB_Duty_PlanDetailsRepository duty_PlanDetailsRepository = new RB_Duty_PlanDetailsRepository();

        /// <summary>
        /// 账号仓储层对象
        /// </summary>
        private readonly RB_AccountRepository accountRepository = new RB_AccountRepository();

        /// <summary>
        /// 值班事项仓储层对象
        /// </summary>
        private readonly RB_Duty_ItemRepository duty_ItemRepository = new RB_Duty_ItemRepository();

        /// <summary>
        /// 值班内容仓储层对象
        /// </summary>
        private readonly RB_Duty_ContentRepository duty_ContentRepository = new RB_Duty_ContentRepository();

        /// <summary>
        /// 访客仓储层对象
        /// </summary>
        private readonly RB_VisitorRepository visitorRepository = new RB_VisitorRepository();

        /// <summary>
        /// 班次仓储层对象
        /// </summary>
        private readonly RB_Duty_FrequencyRepository duty_FrequencyRepository = new RB_Duty_FrequencyRepository();

        /// <summary>
        /// 获取值班计划分页列表【管理端】
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Duty_Plan_ViewModel> GetDutyPlanPageModule(int pageIndex, int pageSize, out long rowsCount, RB_Duty_Plan_ViewModel query)
        {
            var list = duty_PlanRepository.GetDutyPlanPageRepository(pageIndex, pageSize, out rowsCount, query);
            if (list != null && list.Count > 0)
            {
                var ids = string.Join(",", list.Select(qitem => qitem.Id));
                List<RB_Duty_PlanDetails_ViewModel> planDetails = new List<RB_Duty_PlanDetails_ViewModel>();
                if (!string.IsNullOrEmpty(ids))
                {
                    planDetails = GetDutyPlanDetailsListModule(new RB_Duty_PlanDetails_ViewModel() { QPlanIds = ids, QDutyStatus = query.QDutyStatus, QAttendanceStatus = query.QAttendanceStatus }, IsQueryDutyMan: true);
                }
                foreach (var item in list)
                {
                    item.PlanDetails = planDetails?.Where(qitem => qitem.PlanId == item.Id)?.ToList() ?? new List<RB_Duty_PlanDetails_ViewModel>();
                }
            }
            return list;
        }

        /// <summary>
        /// 获取我的值班计划分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Duty_Plan_ViewModel> GetMyDutyPlanPageModule(int pageIndex, int pageSize, out long rowsCount, RB_Duty_Plan_ViewModel query)
        {
            var list = duty_PlanRepository.GetMyDutyPlanPageRepository(pageIndex, pageSize, out rowsCount, query);
            if (list != null && list.Count > 0)
            {
                var ids = string.Join(",", list.Select(qitem => qitem.Id));
                string schoolIds = string.Join(",", list.Select(qitem => qitem.School_Id));
                string shiftIds = "";
                List<RB_Duty_PlanDetails_ViewModel> planDetails = new List<RB_Duty_PlanDetails_ViewModel>();

                List<RB_Duty_Item_ViewModel> dutyItemList = new List<RB_Duty_Item_ViewModel>();
                List<RB_Duty_Content_ViewModel> dutyContentList = new List<RB_Duty_Content_ViewModel>();
                if (!string.IsNullOrEmpty(ids))
                {
                    planDetails = GetDutyPlanDetailsListModule(new RB_Duty_PlanDetails_ViewModel() { QPlanIds = ids, QDutyStatus=-1 }, IsQueryDutyMan: true);
                    dutyContentList = duty_ContentRepository.GetDutyContentListRepository(new RB_Duty_Content_ViewModel() { QPlanIds = ids });
                }
                if (planDetails != null && planDetails.Count > 0)
                {
                    shiftIds = string.Join(",", planDetails.Select(qitem => qitem.Shift));
                }
                if (!string.IsNullOrEmpty(schoolIds) && !string.IsNullOrEmpty(shiftIds))
                {
                    dutyItemList = duty_ItemRepository.GetDutyItemListRepository(new RB_Duty_Item_ViewModel()
                    {
                        ItemSchools = schoolIds,
                        Shifts = shiftIds
                    });
                }

                foreach (var item in list)
                {
                    item.PlanDetails = planDetails?.Where(qitem => qitem.PlanId == item.Id)?.ToList() ?? new List<RB_Duty_PlanDetails_ViewModel>();
                    item.WorkContentList = new List<RB_Duty_PlanWork_ViewModel>();
                    if (item.PlanDetails != null && item.PlanDetails.Count > 0)
                    {
                        foreach (var subItem in item.PlanDetails)
                        {
                            subItem.WorkContentList = new List<RB_Duty_PlanWork_ViewModel>();
                            var tempContentList = dutyContentList.Where(qitem => qitem.PlanType == 1 && qitem.PlanId == item.Id && qitem.PlanShift == subItem.Shift && qitem.CreateBy == subItem.DutyMan)?.ToList();
                            if (tempContentList != null && tempContentList.Count > 0)
                            {
                                foreach (var dItem in tempContentList)
                                {
                                    var dutyItem = dutyItemList?.Where(qitem => qitem.Shifts.Contains(subItem.Shift.ToString()) && qitem.Id == dItem.ItemId && qitem.ItemSchools.Contains(item.School_Id.ToString()))?.FirstOrDefault();
                                    int isFinish = 0;
                                    if (dutyItem!=null&&dutyItem.ItemType == ItemTypeEnum.Choice)
                                    {
                                        isFinish = dItem.WorkIsFinish;
                                    }
                                    else if (dutyItem!=null&&dutyItem.ItemType == ItemTypeEnum.FillIn)
                                    {
                                        if (!string.IsNullOrEmpty(dItem.WorkContent))
                                        {
                                            isFinish = 1;
                                        }
                                    }
                                    subItem.WorkContentList.Add(new RB_Duty_PlanWork_ViewModel()
                                    {
                                        Id = dItem.Id,
                                        ItemId = dutyItem?.Id ?? 0,
                                        ItemType = dutyItem?.ItemType ?? ItemTypeEnum.Choice,
                                        ItemName = dutyItem?.ItemName ?? "",
                                        WorkContent = dItem?.WorkContent ?? "",
                                        IsChecked = isFinish
                                    });
                                }
                            }
                            else
                            {
                                foreach (var dutyItem in dutyItemList.Where(qitem => qitem.ItemSchools.Contains(item.School_Id.ToString()) && qitem.Shifts.Contains(subItem.Shift.ToString())))
                                {
                                    int isFinish = 0;
                                    var dItem = dutyContentList.Where(qitem => qitem.PlanType == 1 && qitem.PlanId == item.Id
                                    && qitem.PlanShift == subItem.Shift && qitem.ItemId == dutyItem.Id && qitem.CreateBy == subItem.DutyMan)?.FirstOrDefault();
                                    if (dutyItem.ItemType == ItemTypeEnum.Choice)
                                    {
                                        isFinish = dItem?.WorkIsFinish ?? 0;
                                    }
                                    else if (dutyItem.ItemType == ItemTypeEnum.FillIn)
                                    {
                                        if (!string.IsNullOrEmpty(dItem?.WorkContent))
                                        {
                                            isFinish = 1;
                                        }
                                    }
                                    subItem.WorkContentList.Add(new RB_Duty_PlanWork_ViewModel()
                                    {
                                        Id = dItem?.Id ?? 0,
                                        ItemId = dutyItem?.Id ?? 0,
                                        ItemType = dutyItem?.ItemType ?? ItemTypeEnum.Choice,
                                        ItemName = dutyItem?.ItemName ?? "",
                                        WorkContent = dItem?.WorkContent ?? "",
                                        IsChecked = isFinish
                                    });
                                }
                            }
                            subItem.BurstCount = dutyContentList?.Where(qitem => qitem.PlanType == 3 && qitem.PlanId == item.Id && qitem.CreateBy == subItem.DutyMan)?.Count() ?? 0;
                            if (subItem.Status == DutyStatusEnum.DutyFinished)
                            {
                                subItem.HandoverCount = dutyContentList?.Where(qitem => qitem.PlanType == 2 && qitem.PlanId == item.Id && qitem.CreateBy == subItem.DutyMan)?.Count() ?? 0;
                            }
                        }
                    }
                    item.TotalBurstCount = item.PlanDetails.Sum(qitem => qitem.BurstCount);
                    item.TotalHandoverCount = item.PlanDetails.Sum(qitem => qitem.HandoverCount);
                }
            }
            return list;
        }

        /// <summary>
        /// 计算班次值班是否完成
        /// </summary>
        /// <param name="planDate"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public DutyStatusEnum CalcDutyPlanStatusModule(DateTime planDate, string startTime, string endTime)
        {
            DutyStatusEnum dutyStatus = DutyStatusEnum.NoStart;
            var dutyStartTime = Convert.ToDateTime(Common.ConvertHelper.FormatDate(planDate) + " " + startTime);
            var dutyEndTime = Convert.ToDateTime(Common.ConvertHelper.FormatDate(planDate) + " " + endTime);
            var dt = DateTime.Now.AddMinutes(30);
            if (dt > dutyEndTime)
            {
                dutyStatus = Common.Enum.Duty.DutyStatusEnum.DutyFinished;
            }
            else if (dt >= dutyStartTime && DateTime.Now <= dutyEndTime)
            {
                dutyStatus = Common.Enum.Duty.DutyStatusEnum.DutyIng;
            }
            else
            {
                dutyStatus = Common.Enum.Duty.DutyStatusEnum.NoStart;
            }
            return dutyStatus;
        }

        /// <summary>
        /// 获取值班班次详情列表
        /// </summary>
        /// <param name="query"></param>
        /// <param name="IsQueryDutyMan">true-查询人员</param>
        /// <returns></returns>
        public List<RB_Duty_PlanDetails_ViewModel> GetDutyPlanDetailsListModule(RB_Duty_PlanDetails_ViewModel query, bool IsQueryDutyMan = false)
        {
            var list = duty_PlanDetailsRepository.GetDutyPlanDetailsListRepository(query);
            if (IsQueryDutyMan && list != null && list.Count > 0)
            {
                var ids = string.Join(",", list.Select(qitem => qitem.DutyMan));
                List<Employee_ViewModel> empList = new List<Employee_ViewModel>();
                if (!string.IsNullOrEmpty(ids))
                {
                    empList = accountRepository.GetEmployeeListRepository(new Model.ViewModel.User.Employee_ViewModel() { QIds = ids });
                }
                foreach (var item in list)
                {
                    var empModel = empList?.Where(qitem => qitem.Id == item.DutyMan)?.FirstOrDefault();
                    item.DutyManName = empModel?.EmployeeName ?? "";
                    item.DutyManIcon = empModel?.UserIcon ?? "";
                    if (string.IsNullOrEmpty(item.StartTime) && !string.IsNullOrEmpty(item.ConfigStartTime))
                    {
                        item.StartTime = item.ConfigStartTime;
                    }
                    if (string.IsNullOrEmpty(item.EndTime) && !string.IsNullOrEmpty(item.ConfigEndTime))
                    {
                        item.EndTime = item.ConfigEndTime;
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 检查值班计划是否存在
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public bool CheckExistsDutyPlanModule(RB_Duty_Plan_ViewModel query)
        {
            return duty_PlanRepository.CheckExistsDutyPlanRepository(query);
        }

        /// <summary>
        /// 新增修改值班计划
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool SetDutyPlanModule(RB_Duty_Plan_ViewModel model, UserInfo userInfo)
        {
            bool flag = false;
            if (model.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    { nameof(RB_Duty_Plan_ViewModel.Date), model.Date},
                    { nameof(RB_Duty_Plan_ViewModel.School_Id), model.School_Id},
                    { nameof(RB_Duty_Plan_ViewModel.UpdateBy), model.UpdateBy},
                    { nameof(RB_Duty_Plan_ViewModel.UpdateTime), model.UpdateTime},
                };
                flag = duty_PlanRepository.Update(fileds, new WhereHelper(nameof(RB_Duty_Plan_ViewModel.Id), model.Id));
            }
            else
            {
                var newId = duty_PlanRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
            }

            //原班次列表
            var oldPlanDetailsList = GetDutyPlanDetailsListModule(new RB_Duty_PlanDetails_ViewModel()
            {
                PlanId = model.Id
            });
            List<PushMessageModel> messageList = new List<PushMessageModel>();
            //原没有班次信息
            if (oldPlanDetailsList == null || (oldPlanDetailsList != null && oldPlanDetailsList.Count == 0))
            {
                if (model.PlanDetails != null && model.PlanDetails.Count > 0)
                {
                    foreach (var item in model.PlanDetails)
                    {
                        item.PlanId = model.Id;
                        duty_PlanDetailsRepository.Insert(item);
                        messageList.Add(new PushMessageModel()
                        {
                            CategoryId = PushMessageCategoryEnum.UserDuty,
                            Content = string.Format("您有{0}的值班信息，请注意查收!", Common.ConvertHelper.FormatDate(model.Date)),
                            CoverImg = "",
                            CreateByName = userInfo.AccountName,
                            JumpUrl = "/home",
                            ReceiveId = item.DutyMan.ToString(),
                            SendTime = DateTime.Now,
                            SendType = 0,
                            Title = "值班信息",
                            Platform = 2
                        });
                    }
                }
            }
            else
            {
                //现在没有值班信息了【直接删除以前的值班信息】
                if (model.PlanDetails == null || (model.PlanDetails != null && model.PlanDetails.Count == 0))
                {
                    duty_PlanDetailsRepository.DeletePlanDetailsRepository(model.Id);
                    foreach (var item in model.PlanDetails)
                    {
                        messageList.Add(new PushMessageModel()
                        {
                            CategoryId = PushMessageCategoryEnum.UserDuty,
                            Content = string.Format("您在{0}的值班，已被取消!", Common.ConvertHelper.FormatDate(model.Date)),
                            CoverImg = "",
                            CreateByName = userInfo.AccountName,
                            JumpUrl = "",
                            ReceiveId = item.DutyMan.ToString(),
                            SendTime = DateTime.Now,
                            SendType = 0,
                            Title = "值班取消",
                            Platform = 2
                        });
                    }
                }
                //找出差异的数据
                var deleteList = oldPlanDetailsList.Where(qitem => !model.PlanDetails.Any(oldItem => qitem.Id == oldItem.Id)).ToList();
                foreach (var dItem in deleteList)
                {
                    if (dItem.Id > 0)
                    {
                        duty_PlanDetailsRepository.Delete(dItem.Id);
                    }
                    messageList.Add(new PushMessageModel()
                    {
                        CategoryId = PushMessageCategoryEnum.UserDuty,
                        Content = string.Format("您在{0}的值班，已被取消!", Common.ConvertHelper.FormatDate(model.Date)),
                        CoverImg = "",
                        CreateByName = userInfo.AccountName,
                        JumpUrl = "",
                        ReceiveId = dItem.DutyMan.ToString(),
                        SendTime = DateTime.Now,
                        SendType = 0,
                        Title = "值班取消",
                        Platform = 2
                    });
                }
                foreach (var item in model.PlanDetails)
                {
                    item.PlanId = model.Id;
                    if (item.Id == 0)
                    {
                        duty_PlanDetailsRepository.Insert(item);
                        messageList.Add(new PushMessageModel()
                        {
                            CategoryId = PushMessageCategoryEnum.UserDuty,
                            Content = string.Format("您有{0}的值班信息，请注意查收!", Common.ConvertHelper.FormatDate(model.Date)),
                            CoverImg = "",
                            CreateByName = userInfo.AccountName,
                            JumpUrl = "/home",
                            ReceiveId = item.DutyMan.ToString(),
                            SendTime = DateTime.Now,
                            SendType = 0,
                            Title = "值班信息",
                            Platform = 2
                        });
                    }
                    else
                    {
                        duty_PlanDetailsRepository.Update(item);
                    }
                }
            }
            if (messageList != null && messageList.Count > 0)
            {
                Common.Message.MessageHelper.SendMessage(messageList);
            }
            return flag;
        }

        /// <summary>
        /// 根据编号获取计划详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public RB_Duty_Plan_ViewModel GetDutyPlanModule(int Id)
        {
            RB_Duty_Plan_ViewModel model = duty_PlanRepository.GetEntity<RB_Duty_Plan_ViewModel>(Id);
            if (model != null && model.Id > 0)
            {
                model.PlanDetails = GetDutyPlanDetailsListModule(new RB_Duty_PlanDetails_ViewModel() { PlanId = model.Id ,QDutyStatus=-1});
            }
            return model;
        }

        /// <summary>
        /// 删除值班计划
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool RemoveDutyPlanModule(int Id, UserInfo userInfo)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                { nameof(RB_Duty_Plan_ViewModel.Status),(int) DateStateEnum.Delete}
            };
            var flag = duty_PlanRepository.Update(fileds, new WhereHelper(nameof(RB_Duty_Plan_ViewModel.Id), Id));
            if (flag)
            {
                var dutyModel = GetDutyPlanModule(Id);
                if (dutyModel != null && dutyModel.PlanDetails != null && dutyModel.PlanDetails.Count > 0)
                {
                    List<PushMessageModel> messageList = new List<PushMessageModel>();
                    foreach (var item in dutyModel.PlanDetails)
                    {
                        messageList.Add(new PushMessageModel()
                        {
                            CategoryId = PushMessageCategoryEnum.UserDuty,
                            Content = string.Format("您在{0}的值班，已被取消!", Common.ConvertHelper.FormatDate(dutyModel.Date)),
                            CoverImg = "",
                            CreateByName = userInfo.AccountName,
                            JumpUrl = "",
                            ReceiveId = item.DutyMan.ToString(),
                            SendTime = DateTime.Now,
                            SendType = 0,
                            Title = "值班取消",
                            Platform = 2
                        });
                    }
                    if (messageList != null && messageList.Count > 0)
                    {
                        Common.Message.MessageHelper.SendMessage(messageList);
                    }
                }
            }
            return flag;
        }

        /// <summary>
        /// 用户值班
        /// </summary>
        /// <param name="Id">值班编号</param>
        /// <param name="Shift">值班班次</param>
        /// <param name="userId">用户信息</param>
        /// <param name="isQueryWork">是否查询工作内容-TRUE(查询)</param>
        /// <returns></returns>
        public Dictionary<string, object> OnDutyModule(int Id, int Shift, int userId, bool isQueryWork = false)
        {
            Dictionary<string, object> result = new Dictionary<string, object>();
            var model = GetMyDutyPlanPageModule(1, 1, out _, new RB_Duty_Plan_ViewModel() { Id = Id, QDutyMan = userId.ToString(), QShift = Shift })?.FirstOrDefault();
            if (model == null)
            {
                return result;
            }
            //当前班次
            var currentModel = new RB_Duty_PlanDetails_ViewModel();
    
            if (model.PlanDetails != null && model.PlanDetails.Count > 0)
            {
                //查找当前人员索引
                int currentIndex = CalcCurrentDutyManIndexModule_V2(model);
 
                //当前班次
                currentModel = model.PlanDetails[currentIndex];
            }

            if (!isQueryWork)
            {
                result.Add("Id", model?.Id);
                result.Add("PlanDate", Common.ConvertHelper.FormatDate(model?.Date));
                result.Add("WeekDay", Common.ConvertHelper.GetWeekDay(model?.Date));

                result.Add("CheckTime", currentModel?.CheckTimeStr);
                result.Add("CheckLateTime", currentModel?.CheckLateTime);
                if (currentModel?.CheckTimeStr != "未打卡")
                {
                    result.Add("CheckLateTimeStr", (currentModel?.CheckLateTime > 0 ? string.Format("[迟到{0}分钟]", currentModel.CheckLateTime) : "[正常]"));
                }
                else
                {
                    result.Add("CheckLateTimeStr", "");
                }
                
                result.Add("FinishTime", currentModel?.FinishTimeStr);
                result.Add("FinishLateTime", currentModel?.FinishLateTime);
                if (currentModel?.FinishTimeStr != "未打卡")
                {
                    result.Add("FinishLateTimeStr", (currentModel?.FinishLateTime > 0 ? string.Format("[早退{0}分钟]", currentModel.FinishLateTime) : "[正常]"));
                }
                else
                {
                    result.Add("FinishLateTimeStr", "");
                }
                   
                result.Add("SchoolName", model?.SchoolName);
                result.Add("ShiftName", currentModel?.ShiftName);
                result.Add("StartTime", currentModel?.StartTime);
                result.Add("EndTime", currentModel?.EndTime);
                result.Add("DutyManName", currentModel?.DutyManName);
                result.Add("DutyManIcon", currentModel?.DutyManIcon);
                result.Add("Status", currentModel?.Status);
                result.Add("StatusStr", currentModel?.StatusStr);
                result.Add("DutyMan", currentModel?.DutyMan);
            }
            else
            {
                var dutyItemList = duty_ItemRepository.GetDutyItemListRepository(new RB_Duty_Item_ViewModel()
                {
                    ItemSchools = model.School_Id.ToString(),
                    Shifts = currentModel.Shift.ToString(),
                });
                var PlanList = dutyItemList ?? new List<RB_Duty_Item_ViewModel>();
                //获取所有的值班内容
                var contentList = duty_ContentRepository.GetDutyContentListRepository(new RB_Duty_Content_ViewModel() { PlanId = model.Id });
                List<Employee_ViewModel> empList = new List<Employee_ViewModel>();
                if (contentList != null)
                {
                    string accountIdStr = string.Join(",", contentList.Select(qitem => qitem.CreateBy));
                    if (!string.IsNullOrEmpty(accountIdStr))
                    {
                        empList = accountRepository.GetEmployeeListRepository(new Model.ViewModel.User.Employee_ViewModel() { QIds = accountIdStr });
                    }
                }
                foreach (var item in contentList)
                {
                    if (!string.IsNullOrEmpty(item.FileURL))
                    {
                        try
                        {
                            item.FileList = Common.Plugin.JsonHelper.DeserializeObject<List<string>>(item.FileURL);
                        }
                        catch (Exception ex)
                        {
                            Common.Plugin.LogHelper.Write(ex, "OnDutyModule_FileList");
                        }
                    }
                }
                List<object> pList = new List<object>();
                var currentPlanContetList = contentList.Where(qitem => qitem.PlanShift == Shift && qitem.PlanType == 1 && qitem.CreateBy==userId)?.ToList();
                if (currentPlanContetList == null || (currentPlanContetList != null && currentPlanContetList.Count == 0))
                {
                    foreach (var dayItem in dutyItemList)
                    {
                        duty_ContentRepository.Insert(new Model.Entity.Duty.RB_Duty_Content()
                        {
                            CreateBy = userId,
                            CreateTime = DateTime.Now,
                            FileURL = "",
                            Group_Id = model.Group_Id,
                            Id = 0,
                            ItemId = dayItem.Id,
                            OtherContent = "",
                            OtherRemark = "",
                            PlanId = model.Id,
                            PlanShift = Shift,
                            PlanType = 1,
                            Status = DateStateEnum.Normal,
                            UpdateBy = userId,
                            UpdateTime = DateTime.Now,
                            WorkContent = "",
                            WorkIsFinish = 0,
                            ItemType = (int)dayItem.ItemType
                        });
                    }
                    contentList = duty_ContentRepository.GetDutyContentListRepository(new RB_Duty_Content_ViewModel() { PlanId = model.Id });
                    currentPlanContetList = contentList.Where(qitem => qitem.PlanShift == Shift && qitem.PlanType == 1)?.ToList();
                }

                if (currentModel.Status == DutyStatusEnum.DutyFinished)
                {
                    foreach (var item in currentPlanContetList.Where(qitem=>qitem.CreateBy==userId))
                    {
                        var c_itemModel = dutyItemList?.Where(qitem => qitem.Id == item.ItemId)?.FirstOrDefault();
                        if (c_itemModel != null)
                        {
                            var itemType = c_itemModel.ItemType;
                            int workIsFinish = 0;
                            if (itemType == ItemTypeEnum.FillIn)
                            {
                                if (!string.IsNullOrEmpty(item?.WorkContent))
                                {
                                    workIsFinish = 1;
                                }
                            }
                            else
                            {
                                workIsFinish = item?.WorkIsFinish ?? 0;
                            }
                            List<string> ItemImgList = new List<string>();
                            if (!string.IsNullOrEmpty(c_itemModel.ItemImg))
                            {
                                ItemImgList = Common.Plugin.JsonHelper.DeserializeObject<List<string>>(c_itemModel.ItemImg);
                            }
                            var pObj = new
                            {
                                Id = item?.Id ?? 0,
                                item?.ItemId,
                                ItemName = c_itemModel?.ItemName ?? "",
                                ItemType = c_itemModel?.ItemType ?? ItemTypeEnum.FillIn,
                                IsChecked = workIsFinish,
                                WorkContent = item?.WorkContent ?? "",
                                item.FileList,
                                ItemImgList
                            };
                            pList.Add(pObj);
                        }
                    }
                }
                else
                {
                    foreach (var item in PlanList)
                    {
                        var c_workModel = currentPlanContetList?.Where(qitem => qitem.ItemId == item.Id&&qitem.CreateBy==userId)?.FirstOrDefault();
                        var itemType = item.ItemType;
                        int workIsFinish = 0;
                        if (itemType == ItemTypeEnum.FillIn)
                        {
                            if (!string.IsNullOrEmpty(c_workModel?.WorkContent))
                            {
                                workIsFinish = 1;
                            }
                        }
                        else
                        {
                            workIsFinish = c_workModel?.WorkIsFinish ?? 0;
                        }
                        List<string> ItemImgList = new List<string>();
                        if (!string.IsNullOrEmpty(item.ItemImg))
                        {
                            ItemImgList = Common.Plugin.JsonHelper.DeserializeObject<List<string>>(item.ItemImg);
                        }
                        var pObj = new
                        {
                            Id = c_workModel?.Id ?? 0,
                            ItemId = item.Id,
                            item.ItemName,
                            item.ItemType,
                            IsChecked = workIsFinish,
                            WorkContent = c_workModel?.WorkContent ?? "",
                            ItemImgList,
                            c_workModel?.FileList
                        };
                        pList.Add(pObj);
                    }
                }

                result.Add("WorkList", pList);
                //突发事项列表
                List<object> EmergenciesList = new List<object>();
                foreach (var item in model.PlanDetails)
                {
                    if (item.Id != currentModel.Id)
                    {
                        var tempEmergenciesList = contentList?.Where(qitem => qitem.PlanType == 3 && qitem.PlanId == item.PlanId && qitem.PlanShift == item.Shift && qitem.CreateBy != userId)?.ToList() ?? new List<RB_Duty_Content_ViewModel>();
                        if (tempEmergenciesList != null && tempEmergenciesList.Count > 0)
                        {
                            tempEmergenciesList.ForEach(item => item.IsOperate = 0);
                            foreach (var subItem in tempEmergenciesList)
                            {
                                subItem.IsOperate = 0;
                                subItem.CreateByName = empList?.Where(qitem => qitem.Id == subItem.CreateBy)?.FirstOrDefault()?.EmployeeName ?? "";
                            }
                            EmergenciesList.AddRange(tempEmergenciesList);
                        }
                    }
                    else
                    {
                        var tempEmergenciesList = contentList?.Where(qitem => qitem.PlanType == 3 && qitem.PlanId == item.PlanId && qitem.PlanShift == item.Shift && qitem.CreateBy == userId)?.ToList() ?? new List<RB_Duty_Content_ViewModel>();
                        if (tempEmergenciesList != null && tempEmergenciesList.Count > 0)
                        {
                            foreach (var subItem in tempEmergenciesList)
                            {
                                subItem.IsOperate = 1;
                                subItem.CreateByName = empList?.Where(qitem => qitem.Id == subItem.CreateBy)?.FirstOrDefault()?.EmployeeName ?? "";
                            }
                            EmergenciesList.AddRange(tempEmergenciesList);
                        }
                    }
                }
                result.Add("EmergenciesList", EmergenciesList);

                //交接事项
                List<object> HandoverList = new List<object>();
                foreach (var item in model.PlanDetails)
                {
                    if (item.Id != currentModel.Id)
                    {
                        if (item.Status == DutyStatusEnum.DutyFinished)
                        {
                            var tempHandOverList = contentList?.Where(qitem => qitem.PlanType == 2 && qitem.PlanId == item.PlanId && qitem.PlanShift == item.Shift && qitem.CreateBy != userId)?.ToList() ?? new List<RB_Duty_Content_ViewModel>();
                            if (tempHandOverList != null && tempHandOverList.Count > 0)
                            {
                                foreach (var subItem in tempHandOverList)
                                {
                                    subItem.IsOperate = 0;
                                    subItem.CreateByName = empList?.Where(qitem => qitem.Id == subItem.CreateBy)?.FirstOrDefault()?.EmployeeName ?? "";
                                }
                                HandoverList.AddRange(tempHandOverList);
                            }
                        }
                    }
                    else
                    {
                        var tempHandOverList = contentList?.Where(qitem => qitem.PlanType == 2 && qitem.PlanId == item.PlanId && qitem.PlanShift == item.Shift && qitem.CreateBy == userId)?.ToList() ?? new List<RB_Duty_Content_ViewModel>();
                        if (tempHandOverList != null && tempHandOverList.Count > 0)
                        {
                            foreach (var subItem in tempHandOverList)
                            {
                                subItem.IsOperate = 1;
                                subItem.CreateByName = empList?.Where(qitem => qitem.Id == subItem.CreateBy)?.FirstOrDefault()?.EmployeeName ?? "";
                            }
                            HandoverList.AddRange(tempHandOverList);
                        }
                    }
                }
                result.Add("HandoverList", HandoverList);
            }
            return result;
        }

        /// <summary>
        /// 用户值班
        /// </summary>
        /// <param name="Id">值班编号</param>
        /// <param name="Shift">值班班次</param>
        /// <param name="userId">用户信息</param>
        /// <param name="isQueryWork">是否查询工作内容-TRUE(查询)</param>
        /// <returns></returns>
        public Dictionary<string, object> OnDutyModule_V2(int Id, int Shift, int userId, bool isQueryWork = false)
        {
            Dictionary<string, object> result = new Dictionary<string, object>();
            var model = GetMyDutyPlanPageModule(1, 1, out _, new RB_Duty_Plan_ViewModel() { Id = Id, QDutyMan = userId.ToString(), QShift = Shift })?.FirstOrDefault();
            if (model == null)
            {
                return result;
            }
            //当前班次
            var currentModel = new RB_Duty_PlanDetails_ViewModel();
            List<RB_Duty_Content_ViewModel> otherContentList = new List<RB_Duty_Content_ViewModel>();

            otherContentList = duty_ContentRepository.GetDutyContentListRepository(new RB_Duty_Content_ViewModel()
            {
                HandoverDlandetails=model.DetailId.ToString()
            });
            if (model.PlanDetails != null && model.PlanDetails.Count > 0)
            {
                //查找当前人员索引
                int currentIndex = CalcCurrentDutyManIndexModule_V2(model);
                //当前班次
                currentModel = model.PlanDetails[currentIndex];
            }

            if (!isQueryWork)
            {
                result.Add("Id", model?.Id);
                result.Add("PlanDate", Common.ConvertHelper.FormatDate(model?.Date));
                result.Add("WeekDay", Common.ConvertHelper.GetWeekDay(model?.Date));

                result.Add("CheckTime", currentModel?.CheckTimeStr);
                result.Add("CheckLateTime", currentModel?.CheckLateTime);
                if (currentModel?.CheckTimeStr != "未打卡")
                {
                    result.Add("CheckLateTimeStr", (currentModel?.CheckLateTime > 0 ? string.Format("[迟到{0}分钟]", currentModel.CheckLateTime) : "[正常]"));
                }
                else
                {
                    result.Add("CheckLateTimeStr", "");
                }

                result.Add("FinishTime", currentModel?.FinishTimeStr);
                result.Add("FinishLateTime", currentModel?.FinishLateTime);
                if (currentModel?.FinishTimeStr != "未打卡")
                {
                    result.Add("FinishLateTimeStr", (currentModel?.FinishLateTime > 0 ? string.Format("[早退{0}分钟]", currentModel.FinishLateTime) : "[正常]"));
                }
                else
                {
                    result.Add("FinishLateTimeStr", "");
                }

                result.Add("SchoolName", model?.SchoolName);
                result.Add("ShiftName", currentModel?.ShiftName);
                result.Add("StartTime", currentModel?.StartTime);
                result.Add("EndTime", currentModel?.EndTime);
                result.Add("DutyManName", currentModel?.DutyManName);
                result.Add("DutyManIcon", currentModel?.DutyManIcon);
                result.Add("Status", currentModel?.Status);
                result.Add("StatusStr", currentModel?.StatusStr);
                result.Add("DutyMan", currentModel?.DutyMan);
            }
            else
            {
                var dutyItemList = duty_ItemRepository.GetDutyItemListRepository(new RB_Duty_Item_ViewModel()
                {
                    ItemSchools = model.School_Id.ToString(),
                    Shifts = currentModel.Shift.ToString(),
                });
                foreach (var dItem in dutyItemList)
                {
                    if (!string.IsNullOrEmpty(dItem.ItemImg))
                    {
                        dItem.ItemImgList = Common.Plugin.JsonHelper.DeserializeObject<List<string>>(dItem.ItemImg);
                    }
                    else
                    {
                        dItem.ItemImgList = new List<string>();
                    }
                }
                var PlanList = dutyItemList ?? new List<RB_Duty_Item_ViewModel>();
                //获取所有的值班内容
                var contentList = duty_ContentRepository.GetDutyContentListRepository(new RB_Duty_Content_ViewModel() { PlanId = model.Id });
                List<Employee_ViewModel> empList = new List<Employee_ViewModel>();
                if (contentList != null)
                {
                    var tempStr = "";
                    string accountIdStr = string.Join(",", contentList.Select(qitem => qitem.CreateBy));
                    string accountIdStr2 = string.Join(",", otherContentList.Select(qitem => qitem.CreateBy));
                    if (!string.IsNullOrEmpty(accountIdStr))
                    {
                        tempStr += accountIdStr;
                    }
                    if (!string.IsNullOrEmpty(accountIdStr2))
                    {
                        tempStr += "," + accountIdStr2;
                    }
                    if (!string.IsNullOrEmpty(tempStr))
                    {
                        empList = accountRepository.GetEmployeeListRepository(new Model.ViewModel.User.Employee_ViewModel() { QIds = tempStr.TrimStart(',').TrimEnd(',') });
                    } 
                }
                foreach (var item in contentList)
                {
                    if (!string.IsNullOrEmpty(item.FileURL))
                    {
                        try
                        {
                            item.FileList = Common.Plugin.JsonHelper.DeserializeObject<List<string>>(item.FileURL);
                        }
                        catch (Exception ex)
                        {
                            Common.Plugin.LogHelper.Write(ex, "OnDutyModule_V2_FileList");
                        }
                    }
                }
                List<object> pList = new List<object>();
                var currentPlanContetList = contentList.Where(qitem => qitem.PlanShift == Shift && qitem.PlanType == 1 && qitem.CreateBy == userId)?.ToList();
                if (currentPlanContetList == null || (currentPlanContetList != null && currentPlanContetList.Count == 0))
                {
                    foreach (var dayItem in dutyItemList.Where(qitem=>qitem.DutyCategory==1&& qitem.DutyType==2))
                    {
                        duty_ContentRepository.Insert(new Model.Entity.Duty.RB_Duty_Content()
                        {
                            CreateBy = userId,
                            CreateTime = DateTime.Now,
                            FileURL = "",
                            Group_Id = model.Group_Id,
                            Id = 0,
                            ItemId = dayItem.Id,
                            OtherContent = "",
                            OtherRemark = "",
                            PlanId = model.Id,
                            PlanShift = Shift,
                            PlanType = 1,
                            Status = DateStateEnum.Normal,
                            UpdateBy = userId,
                            UpdateTime = DateTime.Now,
                            WorkContent = "",
                            WorkIsFinish = 0,
                            ItemType = (int)dayItem.ItemType
                        });
                    }
                    contentList = duty_ContentRepository.GetDutyContentListRepository(new RB_Duty_Content_ViewModel() { PlanId = model.Id });
                    currentPlanContetList = contentList.Where(qitem => qitem.PlanShift == Shift && qitem.PlanType == 1)?.ToList();
                }

                if (currentModel.Status == DutyStatusEnum.DutyFinished)
                {
                    foreach (var item in currentPlanContetList.Where(qitem => qitem.CreateBy == userId))
                    {
                        var c_itemModel = dutyItemList?.Where(qitem => qitem.Id == item.ItemId)?.FirstOrDefault();
                        if (c_itemModel != null)
                        {
                            var itemType = c_itemModel.ItemType;
                            int workIsFinish = 0;
                            if (itemType == ItemTypeEnum.FillIn)
                            {
                                if (!string.IsNullOrEmpty(item?.WorkContent))
                                {
                                    workIsFinish = 1;
                                }
                            }
                            else
                            {
                                workIsFinish = item?.WorkIsFinish ?? 0;
                            }
                            List<string> ItemImgList = new List<string>();
                            if (!string.IsNullOrEmpty(c_itemModel.ItemImg))
                            {
                                ItemImgList = Common.Plugin.JsonHelper.DeserializeObject<List<string>>(c_itemModel.ItemImg);
                            }
                            var pObj = new
                            {
                                Id = item?.Id ?? 0,
                                item?.ItemId,
                                ItemName = c_itemModel?.ItemName ?? "",
                                ItemType = c_itemModel?.ItemType ?? ItemTypeEnum.FillIn,
                                IsChecked = workIsFinish,
                                WorkContent = item?.WorkContent ?? "",
                                item.FileList,
                                ItemImgList
                            };
                            pList.Add(pObj);
                        }
                    }
                }
                else
                {
                    foreach (var item in PlanList.Where(qitem=>qitem.DutyCategory==1&&qitem.DutyType==2))
                    {
                        var c_workModel = currentPlanContetList?.Where(qitem => qitem.ItemId == item.Id && qitem.CreateBy == userId)?.FirstOrDefault();
                        var itemType = item.ItemType;
                        int workIsFinish = 0;
                        if (itemType == ItemTypeEnum.FillIn)
                        {
                            if (!string.IsNullOrEmpty(c_workModel?.WorkContent))
                            {
                                workIsFinish = 1;
                            }
                        }
                        else
                        {
                            workIsFinish = c_workModel?.WorkIsFinish ?? 0;
                        }
                        List<string> ItemImgList = new List<string>();
                        if (!string.IsNullOrEmpty(item.ItemImg))
                        {
                            ItemImgList = Common.Plugin.JsonHelper.DeserializeObject<List<string>>(item.ItemImg);
                        }
                        var pObj = new
                        {
                            Id = c_workModel?.Id ?? 0,
                            ItemId = item.Id,
                            item.ItemName,
                            item.ItemType,
                            IsChecked = workIsFinish,
                            WorkContent = c_workModel?.WorkContent ?? "",
                            ItemImgList,
                            c_workModel?.FileList
                        };
                        pList.Add(pObj);
                    }
                }

                result.Add("WorkList", pList);
                result.Add("WorkRuleList", dutyItemList.Where(qitem => qitem.DutyCategory == 1 && qitem.DutyType == 1).Select(qitem => new
                {
                    qitem.Id,
                    qitem.ItemImgList,
                    qitem.ItemName
                }));
                //突发事项列表
                List<object> EmergenciesList = new List<object>();
                foreach (var item in model.PlanDetails)
                {
                    if (item.Id != currentModel.Id)
                    {
                        var tempEmergenciesList = contentList?.Where(qitem => qitem.PlanType == 3 && qitem.PlanId == item.PlanId && qitem.PlanShift == item.Shift && qitem.CreateBy != userId)?.ToList() ?? new List<RB_Duty_Content_ViewModel>();
                        if (tempEmergenciesList != null && tempEmergenciesList.Count > 0)
                        {
                            tempEmergenciesList.ForEach(item => item.IsOperate = 0);
                            foreach (var subItem in tempEmergenciesList)
                            {
                                subItem.IsOperate = 0;
                                subItem.CreateByName = empList?.Where(qitem => qitem.Id == subItem.CreateBy)?.FirstOrDefault()?.EmployeeName ?? "";
                            }
                            EmergenciesList.AddRange(tempEmergenciesList);
                        }
                    }
                    else
                    {
                        var tempEmergenciesList = contentList?.Where(qitem => qitem.PlanType == 3 && qitem.PlanId == item.PlanId && qitem.PlanShift == item.Shift && qitem.CreateBy == userId)?.ToList() ?? new List<RB_Duty_Content_ViewModel>();
                        if (tempEmergenciesList != null && tempEmergenciesList.Count > 0)
                        {
                            foreach (var subItem in tempEmergenciesList)
                            {
                                subItem.IsOperate = 1;
                                subItem.CreateByName = empList?.Where(qitem => qitem.Id == subItem.CreateBy)?.FirstOrDefault()?.EmployeeName ?? "";
                            }
                            EmergenciesList.AddRange(tempEmergenciesList);
                        }
                    }
                }
                result.Add("EmergenciesList", EmergenciesList);
                result.Add("EmergenciesRuleList", dutyItemList.Where(qitem => qitem.DutyCategory == 2 && qitem.DutyType == 1).Select(qitem => new
                {
                    qitem.Id,
                    qitem.ItemImgList,
                    qitem.ItemName
                }));

                //交接事项
                List<object> HandoverList = new List<object>();
                foreach (var item in model.PlanDetails)
                {
                    if (item.Id != currentModel.Id)
                    {
                        if (item.Status == DutyStatusEnum.DutyFinished)
                        {
                            var tempHandOverList = contentList?.Where(qitem => qitem.PlanType == 2 && qitem.PlanId == item.PlanId && qitem.PlanShift == item.Shift && qitem.CreateBy != userId)?.ToList() ?? new List<RB_Duty_Content_ViewModel>();
                            if (tempHandOverList != null && tempHandOverList.Count > 0)
                            {
                                foreach (var subItem in tempHandOverList)
                                {
                                    subItem.IsOperate = 0;
                                    subItem.CreateByName = empList?.Where(qitem => qitem.Id == subItem.CreateBy)?.FirstOrDefault()?.EmployeeName ?? "";
                                }
                                HandoverList.AddRange(tempHandOverList);
                            }
                        }
                    }
                    else
                    {
                        var tempHandOverList = contentList?.Where(qitem => qitem.PlanType == 2 && qitem.PlanId == item.PlanId && qitem.PlanShift == item.Shift && qitem.CreateBy == userId)?.ToList() ?? new List<RB_Duty_Content_ViewModel>();
                        if (tempHandOverList != null && tempHandOverList.Count > 0)
                        {
                            foreach (var subItem in tempHandOverList)
                            {
                                subItem.IsOperate = 1;
                                subItem.CreateByName = empList?.Where(qitem => qitem.Id == subItem.CreateBy)?.FirstOrDefault()?.EmployeeName ?? "";
                            }
                            HandoverList.AddRange(tempHandOverList);
                        }
                    }
                }
                //上一天最后一个班次交接内容
                if (otherContentList != null && otherContentList.Count > 0)
                {
                    foreach (var hItem in otherContentList)
                    {
                        try
                        {
                            if (!string.IsNullOrEmpty(hItem.FileURL))
                            {
                                hItem.FileList = Common.Plugin.JsonHelper.DeserializeObject<List<string>>(hItem.FileURL);
                            }
                            else
                            {
                                hItem.FileList = new List<string>();
                            }
                        }
                        catch (Exception ex)
                        {
                            Common.Plugin.LogHelper.Write(ex, "OnDutyModule_V2_FileList");
                        }
                        hItem.IsOperate = 2;
                        hItem.CreateByName = empList?.Where(qitem => qitem.Id == hItem.CreateBy)?.FirstOrDefault()?.EmployeeName ?? "";
                        hItem.CreateTimeStr2 = Common.ConvertHelper.FormatDate(hItem.CreateTime) + " " + hItem.CreateTimeStr;
                        HandoverList.Insert(0,hItem);
                    }
                }
                result.Add("HandoverList", HandoverList);
                result.Add("HandoverRuleList", dutyItemList.Where(qitem => qitem.DutyCategory == 3 && qitem.DutyType == 1).Select(qitem => new
                {
                    qitem.Id,
                    qitem.ItemImgList,
                    qitem.ItemName
                }));
            }
            return result;
        }

        /// <summary>
        /// 计算当前值班人员索引
        /// </summary>
        /// <param name="planDate">值班日期</param>
        /// <param name="PlanDetails">值班班次列表</param>
        /// <param name="dutyManId">值班人</param>
        /// <returns></returns>
        public int CalcCurrentDutyManIndexModule_V2(RB_Duty_Plan_ViewModel model)
        {
            //当前值班人员索引
            int currentIndex = 0;
            for (var i = 0; i < model.PlanDetails.Count; i++)
            {
                if (model.DetailId == model.PlanDetails[i].Id)
                {
                    currentIndex = i;
                }
            }
            return currentIndex;
        }


        /// <summary>
        /// 计算当前值班人员索引
        /// </summary>
        /// <param name="planDate">值班日期</param>
        /// <param name="PlanDetails">值班班次列表</param>
        /// <param name="dutyManId">值班人</param>
        /// <returns></returns>
        public Dictionary<string, List<RB_Duty_PlanDetails_ViewModel>> CalcCurrentDutyManIndexModule_V3(RB_Duty_Plan_ViewModel model)
        {
            Dictionary<string, List<RB_Duty_PlanDetails_ViewModel>> plans = new Dictionary<string, List<RB_Duty_PlanDetails_ViewModel>>()
            {
                {"previous",new  List<RB_Duty_PlanDetails_ViewModel>()  },
                {"current",new  List<RB_Duty_PlanDetails_ViewModel>()  },
                {"next",new  List<RB_Duty_PlanDetails_ViewModel>()  },
            };
            var shiftList= model.PlanDetails.GroupBy(qitem => new { qitem.Shift }).Select(qitem => new { qitem.Key.Shift }).ToList();
            for (var i = 0; i < shiftList.Count(); i++)
            {
                var subList = model.PlanDetails.Where(qitem => qitem.Shift == shiftList[i].Shift)?.ToList();
                if (subList != null && subList.Where(qitem => qitem.Id == model.DetailId).Count() > 0)
                {
                    plans["current"] = subList.Where(qitem => qitem.Id == model.DetailId).ToList();
                    if (i - 1 >= 0)
                    {
                        plans["previous"] = model.PlanDetails.Where(qitem => qitem.Shift == shiftList[i - 1].Shift)?.ToList();
                    }
                    if (i + 1 < shiftList.Count())
                    {
                        plans["next"] = model.PlanDetails.Where(qitem => qitem.Shift == shiftList[i + 1].Shift)?.ToList();
                    }
                }
            }
            return plans;
        }

        /// <summary>
        /// 获取值班详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public object GetDutyInfoModule(int Id)
        {
            object result = new object();
            var model = GetMyDutyPlanPageModule(1, 1, out _, new RB_Duty_Plan_ViewModel() { Id = Id })?.FirstOrDefault();
            if (model == null)
            {
                return result;
            }
            //获取所有的值班内容
            var contentList = duty_ContentRepository.GetDutyContentListRepository(new RB_Duty_Content_ViewModel() { PlanId = model.Id });
            foreach (var item in contentList)
            {
                if (!string.IsNullOrEmpty(item.FileURL))
                {
                    try
                    {
                        item.FileList = Common.Plugin.JsonHelper.DeserializeObject<List<string>>(item.FileURL);
                    }
                    catch (Exception ex)
                    {
                        Common.Plugin.LogHelper.Write(ex, "GetDutyInfoModule_FileList");
                    }
                }
            }
            List<object> dayList = new List<object>();
            foreach (var item in model.PlanDetails)
            {
                //访客列表
                var visitorList = GetVisitorPageModule(1, 100000, out _, new RB_Visitor_ViewModel() { PlanId = Id, CreateBy = item.DutyMan });
                dayList.Add(new
                {
                    item.Shift,
                    item.ShiftName,
                    item.StartTime,
                    item.EndTime,
                    CheckTime = Common.ConvertHelper.FormatTime(item.CheckTime),
                    FinishTime = Common.ConvertHelper.FormatTime(item.FinishTime),
                    item.DutyMan,

                    WorkList = contentList.Where(qitem => qitem.PlanShift == item.Shift && qitem.PlanType == 1)?.ToList(),
                    //突发事项列表
                    EmergenciesList = contentList?.Where(qitem => qitem.PlanShift == item.Shift && qitem.PlanType == 3)?.ToList() ?? new List<RB_Duty_Content_ViewModel>(),
                    //交接事项
                    HandoverList = contentList?.Where(qitem => qitem.PlanShift == item.Shift && qitem.PlanType == 2)?.ToList() ?? new List<RB_Duty_Content_ViewModel>(),
                    VisitorList = visitorList,
                });
            }
            result = new
            {
                model?.Id,
                PlanDate = Common.ConvertHelper.FormatDate(model?.Date),
                WeekDay = Common.ConvertHelper.GetWeekDay(model?.Date),
                model?.SchoolName,
                DayList = dayList,
            };
            return result;
        }


        /// <summary>
        /// 获取交接班列表
        /// </summary>
        /// <returns></returns>
        public object GetHandoverShiftListModule()
        {
            List<object> result = new List<object>(); 
            var list = GetDutyPlanDetailsListModule(new RB_Duty_PlanDetails_ViewModel() { QStartDate = Common.ConvertHelper.FormatDate(DateTime.Now) }, IsQueryDutyMan: true);
            foreach (var item in list)
            {
                result.Add(new
                {
                    item.Id,
                    Name= Common.ConvertHelper.FormatDate(item.DutyDate)+" "+ item.ConfigStartTime+" " + item.ShiftName + " "+ item.DutyManName,
                    item.PlanId,
                    item.Shift,
                    item.DutyMan,
                    item.DutyManName,
                    item.ConfigStartTime,
                    item.ConfigEndTime,
                    item.ShiftName,
                    DutyDate=Common.ConvertHelper.FormatDate(item.DutyDate),
                });
            }
            return result;
        }

        /// <summary>
        /// 值班打卡/值班交接
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="Shift"></param>
        /// <param name="DutyMan"></param>
        /// <param name="Status">Status(1-值班中，2-已完成)</param>
        /// <param name="worklist"></param>
        /// <param name="HandoverShift"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool DutyCheckModule(int Id, int Shift, int DutyMan, int Status, List<RB_Duty_Content_ViewModel> worklist,string HandoverDlandetails, out string message)
        {
            message = "";
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                { nameof(RB_Duty_PlanDetails_ViewModel.Status),Status},
            };
            DateTime dt = DateTime.Now;
            var DutyFrequency=duty_FrequencyRepository.GetDutyFrequencyListRepository(new RB_Duty_Frequency_ViewModel() { Id = Shift }).FirstOrDefault();
            var startTime = Convert.ToDateTime(Common.ConvertHelper.FormatDate(dt) + " " + DutyFrequency?.StartTime);
            var endTime = Convert.ToDateTime(Common.ConvertHelper.FormatDate(dt) + " " + DutyFrequency?.EndTime);
            if (Status == 1)
            {
                fileds.Add(nameof(RB_Duty_PlanDetails_ViewModel.CheckTime), dt);
                fileds.Add(nameof(RB_Duty_PlanDetails_ViewModel.StartTime), DutyFrequency?.StartTime);
                int minute = Common.ConvertHelper.CalcMinutes(startTime, dt);
                if (minute > 0)
                {
                    fileds.Add(nameof(RB_Duty_PlanDetails_ViewModel.CheckLateTime), minute);
                }
                else
                {
                    fileds.Add(nameof(RB_Duty_PlanDetails_ViewModel.CheckLateTime), 0);
                }
            }
            if (Status == 2)
            {
                var dutyModel = duty_PlanRepository.GetEntity(Id);
                if (dutyModel.Date >= Common.Config.DutyDate)
                {
                    var workContentList = duty_ContentRepository.GetDutyContentListRepository(new RB_Duty_Content_ViewModel() { PlanId = Id, PlanShift = Shift, PlanType = 1, CreateBy = DutyMan }).ToList();
                    if (workContentList != null && workContentList.Count > 0)
                    {
                        foreach (var item in workContentList)
                        {
                            if (item.ItemType == 1 && item.WorkIsFinish == 0)
                            {
                                message = string.Format("请检查【{0}】,已完成请点击“确认完成”按钮!", item.ItemName);
                                return false;
                            }
                            if (item.ItemType == 2 && (string.IsNullOrEmpty(item.WorkContent)))
                            {
                                message = string.Format("请填写【{0}】的完成情况!", item.ItemName);
                                return false;
                            }
                        }
                    }
                }
                if (dt < startTime)
                {
                    message = "还未到下班时间,不能打卡!";
                    return false;
                }
                if (Common.ConvertHelper.CalcMinutes(endTime, dt) > Common.Config.MoreThanMinutes)
                {
                    message = string.Format("已超过下班时间【{0}】分钟,不能打卡!", Common.Config.MoreThanMinutes);
                    return false;
                }
                fileds.Add(nameof(RB_Duty_PlanDetails_ViewModel.FinishTime), dt);
                fileds.Add(nameof(RB_Duty_PlanDetails_ViewModel.EndTime), DutyFrequency?.EndTime);
                int minute = Common.ConvertHelper.CalcMinutes(dt, endTime);
                if (minute > 0)
                {
                    fileds.Add(nameof(RB_Duty_PlanDetails_ViewModel.FinishLateTime), minute);
                }
                else
                {
                    fileds.Add(nameof(RB_Duty_PlanDetails_ViewModel.FinishLateTime), 0);
                }
            }
            List<WhereHelper> list = new List<WhereHelper>()
            {
                new WhereHelper(nameof(RB_Duty_PlanDetails_ViewModel.PlanId), Id),
                new WhereHelper(nameof(RB_Duty_PlanDetails_ViewModel.DutyMan), DutyMan),
                new WhereHelper(nameof(RB_Duty_PlanDetails_ViewModel.Shift), Shift)
            };
            var flag = duty_PlanDetailsRepository.Update(fileds, list);
            if (flag && worklist != null)
            {
                flag = duty_ContentRepository.InsertBatch(worklist);
            }
            if (!string.IsNullOrEmpty(HandoverDlandetails))
            {
                flag = duty_ContentRepository.UpdateHandoverShiftRepository(HandoverDlandetails, new RB_Duty_Content_ViewModel()
                {
                    PlanId = Id,
                    PlanShift = Shift,
                    CreateBy = DutyMan
                });
            }
            return flag;
        }


        /// <summary>
        /// 更新用户【未值班】状态
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool UpdateNoDutyModule(int Id)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                { nameof(RB_Duty_PlanDetails_ViewModel.Status), (int)DutyStatusEnum.NoDuty },
            };
            List<WhereHelper> list = new List<WhereHelper>()
            {
                new WhereHelper(nameof(RB_Duty_PlanDetails_ViewModel.Id), Id),
            };
            var flag = duty_PlanDetailsRepository.Update(fileds, list);
            return flag;
        }

        /// <summary>
        /// 更新用户【值班完成】状态
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool UpdateDutyFinishedModule(int Id)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                { nameof(RB_Duty_PlanDetails_ViewModel.Status), (int)DutyStatusEnum.DutyFinished },
                { nameof(RB_Duty_PlanDetails_ViewModel.FinishTime), null},
            };
            List<WhereHelper> list = new List<WhereHelper>()
            {
                new WhereHelper(nameof(RB_Duty_PlanDetails_ViewModel.Id), Id),
            };
            var flag = duty_PlanDetailsRepository.Update(fileds, list);
            return flag;
        }

        /// <summary>
        /// 新增修改值班事项
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetDutyContentModule(RB_Duty_Content_ViewModel model)
        {
            bool flag = false;
            if (model.PlanType == 1)
            {
                model.OtherContent = "";
                model.OtherRemark = "";
                if (model.WorkIsFinish == 0)
                {
                    if (!string.IsNullOrEmpty(model.WorkContent) || !string.IsNullOrEmpty(model.FileURL))
                    {
                        model.WorkIsFinish = 1;
                    }
                }
            }
            else
            {
                model.WorkContent = "";
                model.ItemId = 0;
                model.WorkIsFinish = 0;
            }
            if (model.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    { nameof(RB_Duty_Content_ViewModel.PlanShift),model.PlanShift},
                    { nameof(RB_Duty_Content_ViewModel.PlanType),model.PlanType},
                    { nameof(RB_Duty_Content_ViewModel.PlanId),model.PlanId},
                    { nameof(RB_Duty_Content_ViewModel.FileURL),model.FileURL},
                    { nameof(RB_Duty_Content_ViewModel.OtherContent),model.OtherContent},
                    { nameof(RB_Duty_Content_ViewModel.OtherRemark),model.OtherRemark},
                    { nameof(RB_Duty_Content_ViewModel.WorkContent),model.WorkContent},
                    { nameof(RB_Duty_Content_ViewModel.WorkIsFinish),model.WorkIsFinish},
                    { nameof(RB_Duty_Content_ViewModel.ItemId),model.ItemId},
                    { nameof(RB_Duty_Content_ViewModel.UpdateBy),model.UpdateBy},
                    { nameof(RB_Duty_Content_ViewModel.UpdateTime),model.UpdateTime},
                };
                flag = duty_ContentRepository.Update(fileds, new WhereHelper(nameof(RB_Duty_Content_ViewModel.Id), model.Id));
            }
            else
            {
                var newId = duty_ContentRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
            }
            return flag;
        }

        /// <summary>
        /// 删除值班内容
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool RemoveDutyContentModule(int Id)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                { nameof(RB_Duty_Content_ViewModel.Status),(int)DateStateEnum.Delete},
            };
            var flag = duty_ContentRepository.Update(fileds, new WhereHelper(nameof(RB_Duty_Content_ViewModel.Id), Id));
            return flag;
        }

        /// <summary>
        /// 获取访客分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Visitor_ViewModel> GetVisitorPageModule(int pageIndex, int pageSize, out long rowsCount, RB_Visitor_ViewModel query)
        {
            return visitorRepository.GetVisitorPageRepository(pageIndex, pageSize, out rowsCount, query);
        }

        /// <summary>
        /// 新增修改访客
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetVisitorModule(RB_Visitor_ViewModel model)
        {
            bool flag = false;
            if (model.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    { nameof(RB_Visitor_ViewModel.Name), model.Name},
                    { nameof(RB_Visitor_ViewModel.Tel), model.Tel},
                    { nameof(RB_Visitor_ViewModel.WeChatNum), model.WeChatNum},
                    { nameof(RB_Visitor_ViewModel.CourseName), model.CourseName},
                    { nameof(RB_Visitor_ViewModel.StudyTime), model.StudyTime},
                    { nameof(RB_Visitor_ViewModel.LevelType), model.LevelType},
                    { nameof(RB_Visitor_ViewModel.Evaluate), model.Evaluate},
                    { nameof(RB_Visitor_ViewModel.Remark), model.Remark},
                    { nameof(RB_Visitor_ViewModel.VisitorStatus), model.VisitorStatus},
                    { nameof(RB_Visitor_ViewModel.Age), model.Age},
                };
                flag = visitorRepository.Update(fileds, new WhereHelper(nameof(RB_Visitor_ViewModel.Id), model.Id));
            }
            else
            {
                model.VisitTimes = GetVisitorCountModule(model);
                var newId = visitorRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
            }
            return flag;
        }

        /// <summary>
        /// 修改访客删除状态
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="Status"></param>
        /// <returns></returns>
        public bool RemoveVisitorModule(int Id, int Status)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                { nameof(RB_Visitor_ViewModel.Status), Status},
            };
            var flag = visitorRepository.Update(fileds, new WhereHelper(nameof(RB_Visitor_ViewModel.Id), Id));
            return flag;
        }

        /// <summary>
        /// 根据编号获取访客信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public RB_Visitor_ViewModel GetVisitorModule(int Id)
        {
            return visitorRepository.GetEntity<RB_Visitor_ViewModel>(Id);
        }

        /// <summary>
        /// 修改访客状态
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdateVisitorModule(RB_Visitor_ViewModel model)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                { nameof(RB_Visitor_ViewModel.VisitorStatus), model.VisitorStatus},
                { nameof(RB_Visitor_ViewModel.Evaluate), model.Evaluate},
                { nameof(RB_Visitor_ViewModel.Remark), model.Remark},
            };
            var flag = visitorRepository.Update(fileds, new WhereHelper(nameof(RB_Visitor_ViewModel.Id), model.Id));
            return flag;
        }

        /// <summary>
        /// 获取访客访问次数
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int GetVisitorCountModule(RB_Visitor_ViewModel model)
        {
            return visitorRepository.GetVisitorCountRepository(model);
        }

        /// <summary>
        /// 更新值班【未值班，值班未打卡】状态
        /// </summary>
        public void UpdateDutyModule()
        {
            double addhours = 1.5;
            var list = GetDutyPlanPageModule(1, 20, out _, new Model.ViewModel.Duty.RB_Duty_Plan_ViewModel()
            {
                QDutyStatus = 0,
                QEndDate = Common.ConvertHelper.FormatDate(DateTime.Now.AddDays(1))
            });
            if (list != null && list.Count > 0)
            {
                foreach (var item in list)
                {
                    foreach (var subItem in item.PlanDetails)
                    {
                        var endTime = Convert.ToDateTime((Common.ConvertHelper.FormatDate(item.Date) + " " + subItem.EndTime)).AddHours(addhours);
                        if (subItem.Status == Common.Enum.Duty.DutyStatusEnum.NoStart && endTime < DateTime.Now)
                        {
                            UpdateNoDutyModule(subItem.Id);
                        }
                    }
                }
            }

            var list2 = GetDutyPlanPageModule(1, 20, out _, new Model.ViewModel.Duty.RB_Duty_Plan_ViewModel()
            {
                QDutyStatus = 1,
                QEndDate = Common.ConvertHelper.FormatDate(DateTime.Now)
            });
            foreach (var item in list2)
            {
                foreach (var subItem in item.PlanDetails)
                {
                    var endTime = Convert.ToDateTime((Common.ConvertHelper.FormatDate(item.Date) + " " + subItem.EndTime)).AddHours(addhours);
                    if (subItem.Status == Common.Enum.Duty.DutyStatusEnum.DutyIng && endTime < DateTime.Now)
                    {
                        UpdateDutyFinishedModule(subItem.Id);
                    }
                }
            }
        }
    }
}
