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.Linq;

namespace APT.FM.WebApi.Controllers.Api.FO
{
    /// <summary>
    /// FOPreOperSch
    /// </summary>
    [Route("api/FO/FOPreOperSch")]
    public class PreOperSchController : AuthorizeApiController<T_FO_PRE_OPER_SCH>
    {
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMDepartmentService DepartmentService { get; set; }
        /// <summary>
        /// FOPreOperSch
        /// </summary>
        /// <param name="codeRuleService"></param>
        public PreOperSchController(IPFCodeRuleService codeRuleService, IFMNotificationTaskService notificationTaskService, IFMDepartmentService departmentService)
        {
            CodeRuleService = codeRuleService;
            NotificationTaskService = notificationTaskService;
            DepartmentService = departmentService;
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_FO_PRE_OPER_SCH entity)
        {
            return SafeExecute<bool>(() =>
            {
                var users = entity.Nav_PreOperSchUser;
                if (users != null && users.Any())
                {
                    users = users.Where(t => t.USER_ID != null && !t.IS_DELETED).ToList();
                }
                var files = entity.Nav_PreOperSchFile;
                entity.Nav_PreOperSchUser = null;
                entity.Nav_PreOperSchFile = null;
                entity.LANUNCH_TIME=DateTime.Now;
                entity.FORM_STATUS = (int)FOTeamActivityState.草稿;
                var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                entity.LANUNCH_USER_ID = Guid.Parse(userID.ToString());
                entity.DEPARTMENT_ID = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID;
                List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                T_FO_CRUCIAL_LICENSE_JOB job = null;
                T_FO_PRE_OPER_SCH_USER applyUser = new T_FO_PRE_OPER_SCH_USER();
                applyUser.USER_ID = (Guid)userID;
                if (users != null && users.Any())
                {
                    var loginUser=users.FirstOrDefault(t => t.USER_ID == applyUser.USER_ID);
                    if (loginUser == null)
                        users.Add(applyUser);
                    if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                    {
                        entity.FORM_STATUS = (int)FOTeamActivityState.签到中;
                        //直接处理班组长已签到,并修改通知状态
                        users.ForEach(t =>
                        {
                            if (t.USER_ID == userID)
                            {
                                t.DEAL_STATUS = (int)FOUserShiftStatusEnum.已处理;
                            }
                            t.ORG_ID = entity.ORG_ID;
                            t.PRE_OPER_SCH_ID = entity.ID;
                            t.Nav_User = null;
                        });

                        //新增的消息通知
                        var noChargeUsers = users.Where(i => i.USER_ID != userID && i.IS_DELETED == false).ToList();
                        List<Guid> userIds = noChargeUsers.Select(t => t.USER_ID).Distinct().ToList();
                        DateTime dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.JobSite, entity.ORG_ID.Value, DateTime.Now, null, null);
                        if (userIds.Count() > 0)
                        {
                            var UserNames = new List<string>();
                            var user = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && userIds.Contains(t.ID), new BaseFilter(entity.ORG_ID));
                            foreach (var u in userIds)
                            {
                                var current = user.FirstOrDefault(t => t.ID == u);
                                UserNames.Add(current?.NAME);
                            }
                            //发消息
                            notices = NotificationTaskService.InsertUserNoticeTaskModels("作业方案讨论记录表", entity.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                             dtEnd, (int)FMNoticeTypeEnum.消息, "FO008_SHOWPRINT");
                        }
                        else
                        {
                            entity.FORM_STATUS = (int)FOTeamActivityState.已归档;
                            //触发工作票
                            job = InsertJob(entity);
                            if (job != null)
                            {
                                //通知
                                List<Guid> noticesUserIds = new List<Guid>();
                                noticesUserIds.Add((Guid)userID);
                                var UserNames = new List<string>();
                                var user = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && userIds.Contains(t.ID));
                                UserNames.Add(user?.NAME);
                                //发消息
                                notices = NotificationTaskService.InsertUserNoticeTaskModels("关键作业/许可作业工作票", job.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                                 dtEnd, (int)FMNoticeTypeEnum.消息, "FO017");
                            }
                        }
                    }
                    else
                    {
                        applyUser.DEAL_STATUS = (int)FOUserShiftStatusEnum.已处理;
                        applyUser.ORG_ID = entity.ORG_ID;
                        applyUser.PRE_OPER_SCH_ID = entity.ID;
                        var user = this.GetEntity<T_FM_USER>(t=>t.ID == applyUser.USER_ID && t.ENABLE_STATUS == 0, "Nav_Person");
                        applyUser.REAL_DEPARTMENT_POST_ID = user.Nav_Person.POST_ID;
                        loginUser = users.FirstOrDefault(t => t.USER_ID == applyUser.USER_ID);
                        if (loginUser == null)
                            users.Add(applyUser);
                    }
                }
                else
                {
                    applyUser.DEAL_STATUS = (int)FOUserShiftStatusEnum.已处理;
                    applyUser.ORG_ID = entity.ORG_ID;
                    applyUser.PRE_OPER_SCH_ID = entity.ID;
                    var user = this.GetEntity<T_FM_USER>(t=>t.ID == applyUser.USER_ID && t.ENABLE_STATUS == 0, "Nav_Person");
                    applyUser.REAL_DEPARTMENT_POST_ID = user.Nav_Person.POST_ID;
                    //var loginUser = users.FirstOrDefault(t => t.USER_ID == applyUser.USER_ID);
                    //if (loginUser == null)
                    //    users.Add(applyUser);
                    users.Add(applyUser);
                    entity.FORM_STATUS = (int)FOTeamActivityState.已归档;
                    //触发工作票
                    job = InsertJob(entity);
                    if (job != null)
                    {
                        DateTime dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.JobSite, entity.ORG_ID.Value, DateTime.Now, null, null);
                        //通知
                        List<Guid> noticesUserIds = new List<Guid>();
                        noticesUserIds.Add((Guid)userID);
                        var UserNames = new List<string>();
                        var userInfo = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && (Guid)userID == t.ID);
                        UserNames.Add(userInfo?.NAME);
                        //发消息
                        notices = NotificationTaskService.InsertUserNoticeTaskModels("关键作业/许可作业工作票", job.ID, entity.ORG_ID, noticesUserIds, UserNames, DateTime.Now,
                         dtEnd, (int)FMNoticeTypeEnum.消息, "FO017");
                    }
                }
                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);   //保存主表
                    if (users!=null && users.Any())
                        BantchSaveEntityNoCommit(users);    //保存子表
                    //保存新的
                    if (files!=null && files.Any())
                        this.BantchSaveEntityNoCommit(files);
                    if (notices != null && notices.Any())
                        this.BantchSaveEntityNoCommit(notices);
                });
                return true;
            });
        }

        /// <summary>
        /// 是否显示同意按钮
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("GetPreShiftMeetingRecord")]
        public JsonActionResult<bool> GetPreShiftMeetingRecord([FromBody] T_FO_PRE_OPER_SCH entity)
        {
            return SafeExecute<bool>(() =>
            {
                if (entity == null)
                    return false;
                var model = GetEntity<T_FO_PRE_OPER_SCH>(entity.ID.ToString(),false, "Nav_PreOperSchUser");
                if (model.FORM_STATUS != (int)FOTeamActivityState.签到中)
                    return false;
                if (model.Nav_PreOperSchUser != null && model.Nav_PreOperSchUser.Any())
                {
                    var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                    var count=model.Nav_PreOperSchUser.Where(t=>t.PRE_OPER_SCH_ID == entity.ID && t.USER_ID == userID && t.DEAL_STATUS == 0).Count();
                    if (count > 0)  //该用户在该记录中是否参与且未同意则显示同意按钮
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                    return false;
            });
        }
        /// <summary>
        /// 签到同意
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("PersonalAgree")]
        public JsonActionResult<bool> PersonalAgree([FromBody] T_FO_PRE_OPER_SCH entity)
        {
            return SafeExecute<bool>(() =>
            {
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                entity.ORG_ID = orgId;
                var user = this.GetEntity<T_FO_PRE_OPER_SCH_USER>(t => t.PRE_OPER_SCH_ID == entity.ID && t.USER_ID == userID, new BaseFilter(orgId));
                user.DEAL_STATUS = (int)FOUserShiftStatusEnum.已处理;
                entity.CREATER_ID = user.CREATER_ID;
                var todoCount = this.GetCount<T_FO_PRE_OPER_SCH_USER>(t => t.PRE_OPER_SCH_ID == entity.ID && t.DEAL_STATUS == 0, new BaseFilter(orgId));
                T_FO_PRE_OPER_SCH model = null;
                T_FO_CRUCIAL_LICENSE_JOB job = null;
                List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                if (todoCount == 0 || todoCount == 1)
                {
                    model = GetEntity<T_FO_PRE_OPER_SCH>(entity.ID.ToString());
                    model.FORM_STATUS = (int)FOTeamActivityState.已归档;
                    //触发工作票
                    job = InsertJob(entity);
                    if (job != null)
                    {
                        //通知
                        List<Guid> userIds = new List<Guid>();
                        userIds.Add((Guid)user.CREATER_ID);
                        var UserNames = new List<string>();
                        var users = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && userIds.Contains(t.ID));
                        UserNames.Add(users?.NAME);
                        //发消息
                        DateTime dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.JobSite, entity.ORG_ID.Value, DateTime.Now, null, null);
                        notices = NotificationTaskService.InsertUserNoticeTaskModels(entity.FILE_NAME+"关键作业/许可作业工作票", job.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                        dtEnd, (int)FMNoticeTypeEnum.消息, "FO017");
                    }
                }
                T_FM_NOTIFICATION_TASK task = null;
                //查询消息表
                if (entity.TaskID != Guid.Empty)
                {
                    task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                    task.SOURCE_FORMCODE = "FO008_SHOWPRINT";
                }
                this.UnifiedCommit(() =>
                {
                    if (model != null)
                        UpdateEntityNoCommit(model);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                    if (user != null)
                        this.UpdateEntityNoCommit(user);
                    if (job != null)
                        UpdateEntityNoCommit(job);
                    if (notices != null && notices.Any())
                        this.BantchSaveEntityNoCommit(notices);
                });
                return true;
            });
        }

        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("FullOrderPaged")]
        public PagedActionResult<T_FO_PRE_OPER_SCH> FullOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            var result = new PagedActionResult<T_FO_PRE_OPER_SCH>();
            var loginDepartmentId = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID;
            var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            var loginUserCode = APT.Infrastructure.Api.AppContext.CurrentSession.UserCode;
            //安环部负责人departmentID
            var manageDepartId = this.GetEntity<T_FM_USER>(t => t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME == "安环部负责人" && t.ENABLE_STATUS == 0)?.DEPARTMENT_ID;
            if (loginUserCode == "admin" || loginDepartmentId == manageDepartId)
            {
                result = this.GetOrderPageEntities<T_FO_PRE_OPER_SCH>(null, pageFilter);
            }
            else
            {
                List<Guid> departmentId = new List<Guid>() { loginDepartmentId.Value };
                List<Guid> departmentIds = new List<Guid>() { loginDepartmentId.Value };
                DepartmentService.GetDepartmentIds(pageFilter.OrgId.Value, departmentId, ref departmentIds);
                if (departmentIds != null && departmentIds.Any())
                {
                    result = this.GetOrderPageEntities<T_FO_PRE_OPER_SCH>(t => (t.DEPARTMENT_ID != null && departmentIds.Contains(t.DEPARTMENT_ID.Value)), pageFilter);//|| dataIds.Contains(t.ID)
                }
                else
                    result.Data = null;
            }
            return result;
        }

        private T_FO_CRUCIAL_LICENSE_JOB InsertJob(T_FO_PRE_OPER_SCH entity)
        { 
            var job = new T_FO_CRUCIAL_LICENSE_JOB();
            //取审批流水码
            var sysFilter = new SystemCodeFilter();
            sysFilter.CodeType = (int)PFCodeRuleType.关键许可作业票编号;
            sysFilter.Count = 1;
            sysFilter.OrgId = entity.ORG_ID;
            var codes = CodeRuleService.NewGenSerial(sysFilter);
            var codeList = codes.Split(new char[] { ',' });
            //主表
            job.CODE = codeList[0];
            job.ORG_ID = entity.ORG_ID;
            job.APPLY_USER_ID = entity.CREATER_ID;
            job.JOB_SCHEME_ID = entity.ID;
            job.IS_AUTO = (int)ISImportantEnum.是;
            return job;
        }
    }
}
