using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.BaseData.Services.Services.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.FO;
using APT.MS.Domain.Enums;
using APT.Utility;
using InfluxData.Net.InfluxDb.Models.Responses;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace APT.FO.WebApi.Controllers.Api.FO
{
    [Route("api/FO/FOCurrentClassRecord")]
    public class CurrentClassRecordController : AuthorizeApiController<T_FO_CURRENT_CLASS_RECORD>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMDepartmentService DepartmentService { get; set; }


        public CurrentClassRecordController(IFMNotificationTaskService notificationTaskService, IFMDepartmentService departmentService)
        {
            NotificationTaskService = notificationTaskService;
            DepartmentService = departmentService;
        }
        /// <summary>
        /// 交接班保存
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_FO_CURRENT_CLASS_RECORD entity)
        {
            {
                return SafeExecute<bool>(() =>
                {
                    var updateRecord = GetEntity<T_FO_CURRENT_CLASS_RECORD>(entity.ID);
                    var users = entity.Nav_Users;
                    var isManual = false;
                    T_FM_NOTIFICATION_TASK finishNotice = null;
                    if (updateRecord != null && updateRecord.SHIFT_STATUS != (int)FOShiftStatusEnum.待处理 && updateRecord.SHIFT_STATUS != (int)FOShiftStatusEnum.班组长拒绝 && users.Count > 1)
                    {
                        var errorNotification = GetEntity<T_FM_NOTIFICATION_TASK>(t => t.ID == entity.TaskID);
                        if (errorNotification.SOURCE_FORMCODE == "FO005")
                        {
                            errorNotification.NOTICE_TITLE = errorNotification.NOTICE_TITLE + "签到";
                            errorNotification.SOURCE_FORMCODE = "FO005_SHOWPRINT";
                            UpdateEntity(errorNotification);
                        }
                        throw new Exception("对应岗位人员已填写，请刷新确认!");
                    }
                    if (entity.SHIFT_STATUS == (int)FOShiftStatusEnum.签到中 || entity.SHIFT_STATUS == (int)FOShiftStatusEnum.审批中 || entity.SHIFT_STATUS == (int)FOShiftStatusEnum.归档)
                    {
                        finishNotice = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID, entity.ID, "FO005_SHOWPRINT");
                        UpdateEntity(finishNotice);
                        throw new Exception("你已提交,不能修改!");
                    }
                    var currUser = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                    var currFMUser = GetEntity<T_FM_USER>((Guid)currUser, "Nav_Person.Nav_Post", "Nav_Department.Nav_Parent");
                    if (currFMUser != null)
                    {
                        var team = GetEntity<T_FM_TEAM>(t => t.DEPARTMENT_ID == currFMUser.DEPARTMENT_ID);

                        if (entity.CLASS_TEAM_ID == Guid.Empty || entity.CLASS_TEAM_ID == null)
                        {
                            if (team != null)
                            {
                                entity.CLASS_TEAM_ID = team.ID;
                            }
                        }
                        if (entity.CLASS_TEAM_ID == Guid.Empty || entity.DEPARTMENT_POST_ID == null)
                        {
                            entity.DEPARTMENT_POST_ID = currFMUser.Nav_Person.POST_ID;
                        }
                        if (entity.NAME == null)
                        {
                            isManual = true;
                            entity.NAME = DateTime.Now.ToShortDateString() + team.NAME + "-" + currFMUser.Nav_Person.Nav_Post.NAME + "当班工作记录";
                            entity.RECORD_DATE = DateTime.Now;
                        }
                        if (entity.CHARGE_USER_ID == null || entity.CHARGE_USER_ID == Guid.Empty)
                        {
                            entity.CHARGE_USER_ID = currFMUser.Nav_Department.USER_ID;
                        }
                        if (entity.DEPARTMENT_ID == null || entity.DEPARTMENT_ID == Guid.Empty)
                        {
                            entity.DEPARTMENT_ID = currFMUser.Nav_Department.Nav_Parent.ID;
                        }
                    }
                    entity.EDITOR_ID = currUser;

                    var files = entity.Nav_Files;
                    if(files != null)
                    {
                        foreach (var file in files)
                        {
                            if (file.CURRENT_CLASS_RECORD_ID == Guid.Empty)
                            {
                                file.CURRENT_CLASS_RECORD_ID = entity.ID;
                            }
                        }
                    }
                    var labour = entity.Nav_LabourSupplies;
                    T_FM_NOTIFICATION_TASK sendNotice = null;
                    List<T_FM_NOTIFICATION_TASK> notifications = null;
                    T_FO_CURRENT_CLASS_RECORD_USER currUserRecord = null;
                    if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                    {
                        if (entity.TaskID != Guid.Empty)
                        {
                            finishNotice = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID, entity.ID, "FO005_SHOWPRINT");
                        }
                        if (users == null||users.Count()==0)
                        {
                            users = new List<T_FO_CURRENT_CLASS_RECORD_USER>();
                            currUserRecord = new T_FO_CURRENT_CLASS_RECORD_USER()
                            {
                                CURRENT_CLASS_RECORD_ID = entity.ID,
                                USER_ID = (Guid)currUser,
                                ORG_ID = entity.ORG_ID,
                                USER_SHIFT_STATUS = 0
                            };
                            users.Add(currUserRecord);
                        }
                        else
                        {
                            currUserRecord = users.FirstOrDefault(t => t.USER_ID == currUser);
                        }
                        if (currUserRecord.USER_SHIFT_STATUS == (int)FOUserShiftStatusEnum.已处理)
                        {
                            throw new Exception("已经交由班长审核,不能重复通知!");
                        }
                        currUserRecord.USER_SHIFT_STATUS = (int)FOUserShiftStatusEnum.已处理;
                        var usersCount = users.Count(t => t.USER_SHIFT_STATUS == (int)FOUserShiftStatusEnum.待处理);
                        if (usersCount == 0)
                        {
                            var changeRecord = GetEntity<T_FO_CHANGE_SHIFT_RECORD>(t => t.CURRENT_CLASS_RECORD_ID == entity.ID);
                            if (changeRecord != null)
                            {
                                throw new Exception("已创建交接班记录!");
                            }
                            if (entity.CHARGE_USER_ID != currUser && (entity.CURRENT_CLASS_STATUS == (int)FOShiftRecordStatusEnum.不正常 || entity.DEVICE_STATUS == (int)FOShiftRecordStatusEnum.不正常 || entity.ENVIRONMENT_STATUS == (int)FOShiftRecordStatusEnum.不正常 || entity.SUPPLIES_STATUS == (int)FOShiftRecordStatusEnum.不正常))
                            {
                                entity.SHIFT_STATUS = (int)FOShiftStatusEnum.审批中;
                                sendNotice = NotificationTaskService.InsertUserNoticeTaskModel(entity.NAME + "审核", entity.ID, entity.ORG_ID, (Guid)entity.CHARGE_USER_ID, GetEntity<T_FM_USER>(entity.CHARGE_USER_ID.Value).NAME, DateTime.Now, entity.RECORD_DATE.AddHours(1.5), 1, "FO005_SHOWPRINT");
                            }
                            else
                            {
                                entity.SHIFT_STATUS = (int)FOShiftStatusEnum.归档;
                                entity.AUDIT_DATE = DateTime.Now;
                                var currCalendar = this.GetEntity<T_FM_CALENDAR_CLASS>(t => t.CLASS_ID == entity.CLASS_ID);
                                if (currCalendar != null)
                                {
                                    var currCalendarID = currCalendar.CALENDAR_ID;
                                    var currDepartmentConfig = GetEntity<T_FM_DEPARTMENT_CALENDAR_CONFIG_TEAM>(t => t.TEAM_ID == entity.CLASS_TEAM_ID&&t.IS_DELETED==false, "Nav_DepartmentCalendarConfig");
                                    if (currDepartmentConfig.Nav_DepartmentCalendarConfig == null)
                                    {
                                        throw new Exception("未找到排班数据!");
                                    }
                                    if (currDepartmentConfig.Nav_DepartmentCalendarConfig.IS_HANDOVER == true)
                                    {
                                        var searchFilter = new BaseFilter(entity.ORG_ID);
                                        searchFilter.SelectField = new string[] { "TEAM_ID", "PERSON_ID", "Nav_Person.Nav_Post", "Nav_Person.Nav_User", "Nav_DepartmentScheduling" };
                                        var nextClassUsersAll = GetEntities<T_FM_DEPARTMENT_SCHEDULING_DETAIL>(i => i.DEPARTMENT_SCHEDULING_ID == entity.NEXT_CLASS_TEAM_ID && i.Nav_Person.Nav_Post.ID == entity.DEPARTMENT_POST_ID, searchFilter).ToList();
                                        if (nextClassUsersAll == null)
                                        {
                                            this.ThrowError("050001");
                                        }
                                        if (nextClassUsersAll.Any())
                                        {
                                            CreateChangeShiftRecord(entity, users, files, nextClassUsersAll);
                                        }
                                        else
                                        {
                                            entity.REMARK = "未能找到接班人员";
                                        }
                                    }
                                }
                                else if (isManual)
                                {
                                    CreateChangeShiftRecord(entity, users, files, null);
                                }
                            }
                        }
                        else
                        {
                            BaseFilter filter = new BaseFilter(entity.ORG_ID);
                            if (entity.SHIFT_STATUS == (int)FOShiftStatusEnum.班组长拒绝)
                            {
                                notifications = GetEntities<T_FM_NOTIFICATION_TASK>(t => t.CREATE_TIME > DateTime.Now.AddDays(-30) && t.SOURCE_FORMCODE == "FO005_SHOWPRINT" && t.SOURCE_DATA_ID == entity.ID && t.USER_ID != currUser && t.NOTICE_TITLE.Contains("签到"), filter).ToList();
                                foreach (var item in notifications)
                                {
                                    item.NOTICE_STATUS = (int)FMNoticeStatusEnum.未处理;
                                }
                            }
                            else
                            {
                                notifications = GetEntities<T_FM_NOTIFICATION_TASK>(t => t.CREATE_TIME > DateTime.Now.AddDays(-30) && t.SOURCE_FORMCODE == "FO005" && t.SOURCE_DATA_ID == entity.ID && t.NOTICE_STATUS == (int)FMNoticeStatusEnum.未处理 && t.USER_ID != currUser, filter).ToList();
                                foreach (var item in notifications)
                                {
                                    item.NOTICE_TITLE = item.NOTICE_TITLE + "签到";
                                    item.SOURCE_FORMCODE = "FO005_SHOWPRINT";
                                }
                            }
                            entity.SHIFT_STATUS = (int)FOShiftStatusEnum.签到中;
                        }
                    }
                    entity.Nav_Users = null;
                    entity.Nav_Files = null;
                    entity.Nav_LabourSupplies = null;
                    UnifiedCommit(() =>
                    {
                        UpdateEntityNoCommit(entity);   //保存主表
                        if (currUserRecord != null)
                            UpdateEntityNoCommit(currUserRecord);    //保存子表
                        if (labour != null && labour.Any())
                            BantchSaveEntityNoCommit(labour);    //保存子表
                        if (files != null && files.Any())
                            BantchSaveEntityNoCommit(files);
                        if (finishNotice != null)
                            UpdateEntityNoCommit(finishNotice);
                        if (sendNotice != null)
                            AddEntityNoCommit(sendNotice);
                        if (notifications != null && notifications.Any())
                            BantchUpdateEntityNoCommit(notifications, "NOTICE_TITLE", "SOURCE_FORMCODE", "NOTICE_STATUS");
                    });
                    return true;
                });
            }
        }
        /// <summary>
        /// 获取个人的岗位当班工作记录
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetCurrentClassRecord")]
        public JsonActionResult<bool> GetCurrentClassRecord([FromBody] T_FO_CURRENT_CLASS_RECORD entity)
        {
            return SafeExecute<bool>(() =>
            {
                var baseFilter = new BaseFilter(APT.Infrastructure.Api.AppContext.CurrentSession.OrgId);
                baseFilter.SelectField = new string[] { "USER_SHIFT_STATUS" };
                var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var model = this.GetEntities<T_FO_CURRENT_CLASS_RECORD_USER>(t => t.CURRENT_CLASS_RECORD_ID == entity.ID && t.USER_ID == userID, baseFilter).FirstOrDefault();
                if (model.USER_SHIFT_STATUS == 0)  //该用户在该记录中是否参与且未同意则显示同意按钮
                {
                    return true;
                }
                else
                {
                    return false;
                }
            });
        }
        /// <summary>
        /// 审批同意
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("ChargeUserAgree")]
        public JsonActionResult<bool> ChargeUserAgree([FromBody] T_FO_CURRENT_CLASS_RECORD entity)
        {
            //20220126岗位当班工作审批同意,更新审批状态.日期,意见,更新通知状态
            return SafeExecute<bool>(() =>
            {
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                if (entity.TaskID == Guid.Empty)
                {
                    throw new Exception("网络有问题!请刷新后重试!");
                }
                var baseFilter1 = new BaseFilter(orgId);
                baseFilter1.Include = new string[] { "Nav_Users.Nav_User", "Nav_Files", "Nav_Class" };
                var currRecord = this.GetEntity<T_FO_CURRENT_CLASS_RECORD>(t => t.ID == entity.ID, baseFilter1);
                var finishModel = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID, entity.ID);
                T_FM_NOTIFICATION_TASK lastTask = null;
                List<T_FO_CURRENT_CLASS_RECORD_USER> currRecordUsers = null;
                if (entity.CODE.Equals("1"))
                {
                    if (entity.CLASS_ID == null || entity.CLASS_ID == Guid.Empty)
                    {
                        currRecord.AUDIT_DATE = DateTime.Now;
                        currRecord.SHIFT_STATUS = (int)FOShiftStatusEnum.归档;
                        currRecord.REMARK = "手动创建";
                        currRecord.AUDIT_OPINION = entity.AUDIT_OPINION;
                        var users = currRecord.Nav_Users;
                        var files = currRecord.Nav_Files;
                        CreateChangeShiftRecord(currRecord, users, files, null);
                    }
                    else
                    {
                        var currCalendarID = this.GetEntity<T_FM_CALENDAR_CLASS>(t => t.CLASS_ID == entity.CLASS_ID).CALENDAR_ID;
                        var currDepartmentConfig = GetEntity<T_FM_DEPARTMENT_CALENDAR_CONFIG_TEAM>(t => t.TEAM_ID == currRecord.CLASS_TEAM_ID, "Nav_DepartmentCalendarConfig");
                        currRecord.AUDIT_DATE = DateTime.Now;
                        currRecord.SHIFT_STATUS = (int)FOShiftStatusEnum.归档;
                        currRecord.AUDIT_OPINION = entity.AUDIT_OPINION;
                        if (currDepartmentConfig.Nav_DepartmentCalendarConfig.IS_HANDOVER == true)
                        {
                            var users = currRecord.Nav_Users;
                            var files = currRecord.Nav_Files;
                            var searchFilter = new BaseFilter(orgId)
                            {
                                SelectField = new string[] { "TEAM_ID", "PERSON_ID", "Nav_Person.Nav_Post", "Nav_Person.Nav_User", "Nav_DepartmentScheduling" }
                            };
                            var nextClassUsersAll = this.GetEntities<T_FM_DEPARTMENT_SCHEDULING_DETAIL>(i => i.DEPARTMENT_SCHEDULING_ID == currRecord.NEXT_CLASS_TEAM_ID && i.Nav_Person.Nav_Post.ID == currRecord.DEPARTMENT_POST_ID, searchFilter).ToList();
                            if (nextClassUsersAll != null && nextClassUsersAll.Count > 0)
                            {
                                CreateChangeShiftRecord(currRecord, users, files, nextClassUsersAll);
                            }
                            else
                            {
                                currRecord.REMARK = "未能找到接班人员";
                            }
                        }
                    }

                }
                else
                {
                    if (string.IsNullOrEmpty(entity.AUDIT_OPINION))
                    {
                        throw new Exception("驳回时,请填写审核意见!");
                    }
                    entity.AUDIT_OPINION += "<br/>审核时间：" + DateTime.Now;
                    lastTask = GetEntity<T_FM_NOTIFICATION_TASK>(t => t.SOURCE_DATA_ID == currRecord.ID && t.NOTICE_STATUS != 0 && t.USER_ID == currRecord.EDITOR_ID);
                    currRecordUsers = currRecord.Nav_Users;
                    foreach (var user in currRecord.Nav_Users)
                    {
                        user.USER_SHIFT_STATUS = (int)FOUserShiftStatusEnum.待处理;
                    }
                    lastTask.NOTICE_STATUS = (int)FMNoticeStatusEnum.未处理;
                    lastTask.NOTICE_TITLE = "(驳回)" + lastTask.NOTICE_TITLE;
                    lastTask.SOURCE_FORMCODE = "FO005";
                    currRecord.AUDIT_DATE = DateTime.Now;
                    currRecord.SHIFT_STATUS = (int)FOShiftStatusEnum.班组长拒绝;
                    currRecord.AUDIT_OPINION = entity.AUDIT_OPINION;
                }
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(finishModel);
                    UpdateEntityNoCommit(currRecord);
                    if (currRecordUsers != null && currRecordUsers.Any())
                        BantchUpdateEntityNoCommit(currRecordUsers);
                    if (lastTask != null)
                        UpdateEntityNoCommit(lastTask);

                });
                return true;
            });
        }

        /// <summary>
        /// 签到
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("UserSignin")]
        public JsonActionResult<bool> UserSignin([FromBody] T_FO_CURRENT_CLASS_RECORD entity)
        {
            return SafeExecute<bool>(() =>
            {
                var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                var entityAlluser = GetEntities<T_FO_CURRENT_CLASS_RECORD_USER>(t => t.CURRENT_CLASS_RECORD_ID == entity.ID, new BaseFilter(orgId));
                var currUser = entityAlluser.FirstOrDefault(t => t.USER_ID == userID);
                currUser.USER_SHIFT_STATUS = (int)FOUserShiftStatusEnum.已处理;
                currUser.MODIFY_TIME = DateTime.Now;
                var todoCount = entityAlluser.Where(t => t.USER_SHIFT_STATUS == (int)FOUserShiftStatusEnum.待处理).Count();
                T_FM_NOTIFICATION_TASK finishNotice = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID, entity.ID);
                T_FM_NOTIFICATION_TASK sendNotice = null;
                T_FO_CURRENT_CLASS_RECORD model = null;
                if (todoCount == 0)
                {
                    model = GetEntity<T_FO_CURRENT_CLASS_RECORD>(entity.ID.ToString());
                    if (model.CURRENT_CLASS_STATUS == (int)FOShiftRecordStatusEnum.不正常 || model.DEVICE_STATUS == (int)FOShiftRecordStatusEnum.不正常 || model.ENVIRONMENT_STATUS == (int)FOShiftRecordStatusEnum.不正常 || model.SUPPLIES_STATUS == (int)FOShiftRecordStatusEnum.不正常)
                    {
                        model.SHIFT_STATUS = (int)FOShiftStatusEnum.审批中;
                        sendNotice = NotificationTaskService.InsertUserNoticeTaskModel(model.NAME + "审核", model.ID, orgId, (Guid)model.CHARGE_USER_ID, GetEntity<T_FM_USER>(model.CHARGE_USER_ID.Value).NAME, DateTime.Now, model.RECORD_DATE.AddHours(1.5), 1, "FO005_SHOWPRINT");
                    }
                    else
                    {
                        model.SHIFT_STATUS = (int)FOShiftStatusEnum.归档;
                        model.AUDIT_DATE = DateTime.Now;
                        var currCalendar = this.GetEntity<T_FM_CALENDAR_CLASS>(t => t.CLASS_ID == model.CLASS_ID);
                        var currCalendarID = currCalendar.CALENDAR_ID;
                        var currDepartmentConfig = GetEntity<T_FM_DEPARTMENT_CALENDAR_CONFIG_TEAM>(t => t.TEAM_ID == model.CLASS_TEAM_ID&&t.IS_DELETED==false, "Nav_DepartmentCalendarConfig");
                        if (currDepartmentConfig.Nav_DepartmentCalendarConfig.IS_HANDOVER == true)
                        {
                            var users = GetEntities<T_FO_CURRENT_CLASS_RECORD_USER>(t => t.CURRENT_CLASS_RECORD_ID == entity.ID, new BaseFilter(orgId)).ToList();
                            var files = GetEntities<T_FO_CURRENT_CLASS_RECORD_FILE>(t => t.CURRENT_CLASS_RECORD_ID == entity.ID, new BaseFilter(orgId)).ToList();
                            var searchFilter = new BaseFilter(model.ORG_ID);
                            searchFilter.SelectField = new string[] { "TEAM_ID", "PERSON_ID", "Nav_Person.Nav_Post", "Nav_Person.Nav_User", "Nav_DepartmentScheduling" };
                            var nextClassUsersAll = GetEntities<T_FM_DEPARTMENT_SCHEDULING_DETAIL>(i => i.DEPARTMENT_SCHEDULING_ID == model.NEXT_CLASS_TEAM_ID && i.Nav_Person.Nav_Post.ID == model.DEPARTMENT_POST_ID, searchFilter).ToList();
                            if (nextClassUsersAll.Any())
                            {
                                CreateChangeShiftRecord(model, users, files, nextClassUsersAll);
                            }
                            else
                            {
                                model.REMARK = "未能找到接班人员";
                            }
                        }
                    }
                }
                UnifiedCommit(() =>
                {
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                    if (currUser != null)
                        UpdateEntityNoCommit(currUser);
                    if (sendNotice != null)
                        AddEntityNoCommit(sendNotice);
                    if (model != null)
                        UpdateEntityNoCommit(model);
                });
                return true;
            });
        }

        /// <summary>
        /// 创建交接班记录
        /// </summary>
        public void CreateChangeShiftRecord(T_FO_CURRENT_CLASS_RECORD currRecord, List<T_FO_CURRENT_CLASS_RECORD_USER> users, List<T_FO_CURRENT_CLASS_RECORD_FILE> files, List<T_FM_DEPARTMENT_SCHEDULING_DETAIL> nextClassUsersAll)
        {
            T_FO_CHANGE_SHIFT_RECORD changeShiftRecord = new T_FO_CHANGE_SHIFT_RECORD();
            var noticeTitles = new List<string>();
            var noticeUserIds = new List<Guid>();
            var noticeUserNames = new List<string>();
            var noticeDataIds = new List<Guid>();
            List<T_FM_NOTIFICATION_TASK> sendChangeNotice = null;
            changeShiftRecord.ID = Guid.NewGuid();
            changeShiftRecord.NAME = currRecord.NAME.Replace("当班", "交接班");
            changeShiftRecord.DEPARTMENT_ID = (Guid)currRecord.DEPARTMENT_ID;
            changeShiftRecord.DEPARTMENT_POST_ID = (Guid)currRecord.DEPARTMENT_POST_ID;
            if (currRecord.CLASS_ID != null && currRecord.CLASS_ID != Guid.Empty)
            {
                changeShiftRecord.CLASS_ID = (Guid)currRecord.CLASS_ID;
            }
            changeShiftRecord.DEVICE_MEASURE = currRecord.DEVICE_MEASURE;
            changeShiftRecord.DEVICE_QUESTION = currRecord.DEVICE_QUESTION;
            changeShiftRecord.DEVICE_STATUS = currRecord.DEVICE_STATUS;
            changeShiftRecord.DEVICE_STORAGE = currRecord.DEVICE_STORAGE;
            changeShiftRecord.CURRENT_CLASS_STATUS = currRecord.CURRENT_CLASS_STATUS;
            changeShiftRecord.CURRENT_CLASS_QUESTION = currRecord.CURRENT_CLASS_QUESTION;
            changeShiftRecord.CURRENT_CLASS_MEASURE = currRecord.CURRENT_CLASS_MEASURE;
            changeShiftRecord.ENVIRONMENT_STATUS = currRecord.ENVIRONMENT_STATUS;
            changeShiftRecord.ENVIRONMENT_QUESTION = currRecord.ENVIRONMENT_QUESTION;
            changeShiftRecord.ENVIRONMENT_MEASURE = currRecord.ENVIRONMENT_MEASURE;
            changeShiftRecord.SUPPLIES_STATUS = currRecord.SUPPLIES_STATUS;
            changeShiftRecord.SUPPLIES_QUESTION = currRecord.SUPPLIES_QUESTION;
            changeShiftRecord.SUPPLIES_MEASURE = currRecord.SUPPLIES_MEASURE;
            changeShiftRecord.CURRENT_CLASS_RECORD_ID = currRecord.ID;
            changeShiftRecord.TEAM_ID = currRecord.CLASS_TEAM_ID;
            var shiftTime = currRecord.RECORD_DATE;
            if (shiftTime.ToString().Contains("23:59:59"))
            {
                shiftTime = shiftTime.AddSeconds(1);
            }
            changeShiftRecord.CHANGE_SHIFT_TIME = Convert.ToDateTime(shiftTime);
            changeShiftRecord.SHIFT_STATUS = (int)FOShiftStatusEnum.待处理;
            changeShiftRecord.ORG_ID = currRecord.ORG_ID;
            List<T_FO_CHANGE_SHIFT_RECORD_PRE_USER> shiftRecordPreUsers = new List<T_FO_CHANGE_SHIFT_RECORD_PRE_USER>();
            foreach (var preUser in users)
            {
                T_FO_CHANGE_SHIFT_RECORD_PRE_USER shiftRecordPreUser = new T_FO_CHANGE_SHIFT_RECORD_PRE_USER();
                shiftRecordPreUser.CHANGE_SHIFT_RECORD_ID = changeShiftRecord.ID;
                shiftRecordPreUser.USER_ID = preUser.USER_ID;
                shiftRecordPreUser.USER_SHIFT_STATUS = (int)FOUserShiftStatusEnum.已处理;
                shiftRecordPreUser.ORG_ID = currRecord.ORG_ID;
                shiftRecordPreUsers.Add(shiftRecordPreUser);

            }
            List<T_FO_CHANGE_SHIFT_RECORD_FILE> shiftRecordFiles = new List<T_FO_CHANGE_SHIFT_RECORD_FILE>();
            if (files != null && files.Any())
            {
                foreach (var file in files)
                {
                    T_FO_CHANGE_SHIFT_RECORD_FILE shiftRecordFile = new T_FO_CHANGE_SHIFT_RECORD_FILE();
                    shiftRecordFile.CHANGE_SHIFT_RECORD_ID = changeShiftRecord.ID;
                    shiftRecordFile.IMG_FILE_ID = file.IMG_FILE_ID;
                    shiftRecordFile.ORG_ID = currRecord.ORG_ID;
                    shiftRecordFiles.Add(shiftRecordFile);
                }
            }
            List<T_FO_CHANGE_SHIFT_RECORD_AFTER_USER> shiftRecordAfterUsers = new List<T_FO_CHANGE_SHIFT_RECORD_AFTER_USER>();
            if (nextClassUsersAll != null && nextClassUsersAll.Any())
            {
                foreach (var afterUser in nextClassUsersAll)
                {
                    T_FO_CHANGE_SHIFT_RECORD_AFTER_USER shiftRecordAfterUser = new T_FO_CHANGE_SHIFT_RECORD_AFTER_USER();
                    shiftRecordAfterUser.CHANGE_SHIFT_RECORD_ID = changeShiftRecord.ID;
                    shiftRecordAfterUser.USER_ID = afterUser.Nav_Person.Nav_User.ID;
                    shiftRecordAfterUser.USER_SHIFT_STATUS = (int)FOUserShiftStatusEnum.待处理;
                    shiftRecordAfterUser.ORG_ID = currRecord.ORG_ID;
                    shiftRecordAfterUsers.Add(shiftRecordAfterUser);
                    noticeTitles.Add(currRecord.NAME.Replace("当班", "交接班"));
                    noticeDataIds.Add(changeShiftRecord.ID);
                    noticeUserIds.Add(shiftRecordAfterUser.USER_ID);
                    noticeUserNames.Add(afterUser.Nav_Person.Nav_User.NAME);
                }
            }
            else
            {
                noticeTitles.Add(currRecord.NAME.Replace("当班", "交接班"));
                noticeDataIds.Add(changeShiftRecord.ID);
                noticeUserIds.Add(users.FirstOrDefault().USER_ID);
                noticeUserNames.Add("");
            }
            sendChangeNotice = NotificationTaskService.InsertUserNoticeTaskModels(noticeTitles, noticeDataIds, currRecord.ORG_ID, noticeUserIds, noticeUserNames, DateTime.Now, shiftTime.AddHours(1.5), 1, "FO012");
            UnifiedCommit(() =>
            {
                if (changeShiftRecord != null)
                    AddEntityNoCommit(changeShiftRecord);
                if (shiftRecordAfterUsers != null && shiftRecordAfterUsers.Any())
                    BantchAddEntityNoCommit(shiftRecordAfterUsers);
                if (shiftRecordPreUsers != null && shiftRecordPreUsers.Any())
                    BantchAddEntityNoCommit(shiftRecordPreUsers);
                if (sendChangeNotice != null && sendChangeNotice.Any())
                    BantchAddEntityNoCommit(sendChangeNotice);
                if(shiftRecordFiles != null && shiftRecordFiles.Any())
                    BantchAddEntityNoCommit(shiftRecordFiles);
            });
        }
        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPaged")]
        public PagedActionResult<T_FO_CURRENT_CLASS_RECORD> OrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            var result = new PagedActionResult<T_FO_CURRENT_CLASS_RECORD>();
            var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            var admiId = this.GetEntity<T_FM_USER>(t => t.CODE.Contains("admin") && t.ENABLE_STATUS == 0)?.ID;
            var currDep = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value;
            var AHDepartment = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部负责人" || t.Nav_ApproveRole.NAME == "安环部安全员").DEPARTMENT_ID;
            if (loginUserId == null || loginUserId == admiId || currDep == AHDepartment)
            {
                result = this.GetOrderPageEntities<T_FO_CURRENT_CLASS_RECORD>(null, pageFilter);
            }
            else
            {
                var loginDepartmentId = this.GetEntity<T_FM_USER>(t => t.ID == loginUserId && t.ENABLE_STATUS == 0)?.DEPARTMENT_ID;
                List<Guid> departmentId = new List<Guid>();
                departmentId.Add((Guid)loginDepartmentId);
                List<Guid> departmentIds = new List<Guid>() { currDep };
                DepartmentService.GetDepartmentIds(pageFilter.OrgId.Value, departmentId, ref departmentIds);
                if (departmentIds != null && departmentIds.Any())
                {
                    result = this.GetOrderPageEntities<T_FO_CURRENT_CLASS_RECORD>(t => (departmentIds.Contains((Guid)t.Nav_Team.DEPARTMENT_ID)), pageFilter);//|| dataIds.Contains(t.ID)
                }
                else
                    result.Data = null;
            }
            return result;
        }
    }
}

