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 Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.DirectoryServices.ActiveDirectory;
using System.Linq;
namespace APT.FO.WebApi.Controllers.Api.FO
{
    [Route("api/FO/FOChangeShiftRecord")]
    public class ChangeShiftRecordController : AuthorizeApiController<T_FO_CHANGE_SHIFT_RECORD>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMDepartmentService DepartmentService { get; set; }

        public ChangeShiftRecordController(IPFCodeRuleService codeRuleService, IFMNotificationTaskService notificationTaskService, IFMDepartmentService departmentService)
        {
            NotificationTaskService = notificationTaskService;
            CodeRuleService = codeRuleService;
            DepartmentService = departmentService;
        }
        /// <summary>
        /// 保存并通知
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("SaveAndNotice")]
        public JsonActionResult<bool> SaveAndNotice([FromBody] T_FO_CHANGE_SHIFT_RECORD entity)
        {
            return SafeExecute(() =>
            {
                var updateRecord = GetEntity<T_FO_CHANGE_SHIFT_RECORD>(entity.ID);
                if (updateRecord.SHIFT_STATUS != (int)FOChangeShiftStatusEnum.待处理)
                {
                    throw new Exception("对应岗位人员已填写，请刷新确认!");
                }
                var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var afterUsers = entity.Nav_AfterUsers.Where(t=>t.IS_DELETED==false);
                if (afterUsers.Count() == 0)
                {
                    throw new Exception("请选择接班人员!");
                }
                entity.Nav_PreUsers = null;
                entity.Nav_AfterUsers = null;
                entity.Nav_Files = null;
                entity.EDITOR_ID = userID;
                var currpreUsers = afterUsers.FirstOrDefault(t => t.USER_ID == userID && t.USER_SHIFT_STATUS == (int)FOUserShiftStatusEnum.待处理);
                if (currpreUsers != null)
                {
                    currpreUsers.USER_SHIFT_STATUS = (int)FOUserShiftStatusEnum.已处理;
                    T_FM_NOTIFICATION_TASK finishNotice = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID, entity.ID, "FO013_SHOWPRINT");
                    var count = afterUsers.Count(t => t.USER_SHIFT_STATUS == 0);
                    List<T_FM_NOTIFICATION_TASK> updateTasks = null;
                    if (count == 0)
                    {
                        entity.SHIFT_STATUS = (int)FOChangeShiftStatusEnum.归档;
                    }
                    else
                    {
                        entity.SHIFT_STATUS = (int)FOChangeShiftStatusEnum.接班中;
                        updateTasks = GetEntities<T_FM_NOTIFICATION_TASK>(t => t.SOURCE_DATA_ID == entity.ID && t.USER_ID != userID && t.NOTICE_STATUS == (int)FMNoticeStatusEnum.未处理, new BaseFilter(entity.ORG_ID)).ToList();
                        foreach (var task in updateTasks)
                        {
                            task.NOTICE_TITLE = task.NOTICE_TITLE + "确认";
                            task.SOURCE_FORMCODE = "FO013_SHOWPRINT";
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        UpdateEntityNoCommit(currpreUsers);
                        UpdateEntityNoCommit(entity);
                        if (finishNotice != null)
                            UpdateEntityNoCommit(finishNotice);
                        if (updateTasks != null && updateTasks.Any())
                            BantchUpdateEntityNoCommit(updateTasks);
                    });
                }
                else
                {
                    var noticeTitles = new List<string>();
                    var noticeUserIds = new List<Guid>();
                    var noticeUserNames = new List<string>();
                    var noticeDataIds = new List<Guid>();
                    entity.SHIFT_STATUS = (int)FOChangeShiftStatusEnum.接班中;
                    foreach (var user in afterUsers)
                    {
                        noticeTitles.Add(updateRecord.NAME + "确认");
                        noticeDataIds.Add(updateRecord.ID);
                        noticeUserIds.Add(user.USER_ID);
                        noticeUserNames.Add(user.Nav_User.NAME);
                        user.Nav_User = null;
                    }
                    var sendChangeNotices = NotificationTaskService.InsertUserNoticeTaskModels(noticeTitles, noticeDataIds, updateRecord.ORG_ID, noticeUserIds, noticeUserNames, DateTime.Now, DateTime.Now.AddHours(2), 1, "FO013_SHOWPRINT");
                    T_FM_NOTIFICATION_TASK finishNotice = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID, entity.ID, "FO013_SHOWPRINT");
                    UnifiedCommit(() =>
                    {
                        if (sendChangeNotices != null && sendChangeNotices.Any())
                        {
                            BantchAddEntityNoCommit(sendChangeNotices);
                        }
                        UpdateEntityNoCommit(entity);
                        if (finishNotice != null)
                            UpdateEntityNoCommit(finishNotice);
                        if (afterUsers != null && afterUsers.Any())
                        {
                            BantchSaveEntityNoCommit(afterUsers);
                        }
                    });
                }
                return true;
            });
        }


        /// <summary>
        /// 获取个人的接班记录
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetChangeShiftRecord")]
        public JsonActionResult<bool> GetPreShiftMeetingRecord([FromBody] T_FO_CHANGE_SHIFT_RECORD entity)
        {
            return SafeExecute<bool>(() =>
            {
                if (entity == null)
                {
                    return false;
                }
                var model = GetEntity<T_FO_CHANGE_SHIFT_RECORD>(entity.ID.ToString());
                //if (model.SHIFT_STATUS != (int)FOChangeShiftStatusEnum.接班中)
                //    return false;
                var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var orgID = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                var count = GetCount<T_FO_CHANGE_SHIFT_RECORD_AFTER_USER>(t => t.CHANGE_SHIFT_RECORD_ID == entity.ID && t.USER_ID == userID && t.USER_SHIFT_STATUS == 0, new BaseFilter(orgID));
                if (count > 0)  //该用户在该记录中是否参与且未同意则显示同意按钮
                {
                    return true;
                }
                else
                {
                    return false;
                }
            });
        }
        /// <summary>
        /// 同意
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("PersonalAgree")]
        public JsonActionResult<bool> PersonalAgree([FromBody] T_FO_CHANGE_SHIFT_RECORD param)
        {
            return SafeExecute<bool>(() =>
            {
                var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var orgID = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                T_FO_CHANGE_SHIFT_RECORD entity = null;
                var baseFilter = new BaseFilter(orgID);
                var afterUsers = GetEntities<T_FO_CHANGE_SHIFT_RECORD_AFTER_USER>(t => t.CHANGE_SHIFT_RECORD_ID == param.ID, new BaseFilter(orgID));
                var currpreUser = afterUsers.FirstOrDefault(t => t.USER_ID == userID && t.USER_SHIFT_STATUS == (int)FOUserShiftStatusEnum.待处理);
                if (currpreUser != null)
                {
                    currpreUser.USER_SHIFT_STATUS = (int)FOUserShiftStatusEnum.已处理;
                    var todoCount = afterUsers.Count(t => t.USER_SHIFT_STATUS == 0);
                    if (todoCount == 0)
                    {
                        entity = GetEntity<T_FO_CHANGE_SHIFT_RECORD>(param.ID);
                        if (entity != null)
                        {
                            entity.SHIFT_STATUS = (int)FOChangeShiftStatusEnum.归档;
                        }
                    }
                    NotificationTaskService.NotificationTaskFinish(param.TaskID, () =>
                    {
                        if (entity != null)
                            UpdateEntityNoCommit(entity, "SHIFT_STATUS");
                        UpdateEntityNoCommit(currpreUser, "USER_SHIFT_STATUS");
                    });
                }
                return true;
            });
        }
        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPaged")]
        public PagedActionResult<T_FO_CHANGE_SHIFT_RECORD> OrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            var result = new PagedActionResult<T_FO_CHANGE_SHIFT_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 tempDep = GetEntity<T_FM_DEPARTMENT>(currDep);
            if (tempDep!=null&& tempDep.DEPARTMENT_TYPE == (int)FMDepartmentType.班组)
            {
                currDep = (Guid)tempDep.PARENT_ID;
            }
            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_CHANGE_SHIFT_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_CHANGE_SHIFT_RECORD>(t => departmentIds.Contains((Guid)t.DEPARTMENT_ID), pageFilter);
                }
                else
                    result.Data = null;
            }
            return result;
        }
    }
}
