using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.IServices;
using APT.Infrastructure.Core;
using System;
using System.Collections.Generic;
using APT.Infrastructure.Api;
using APT.MS.Domain.Enums;
using APT.BaseData.Domain.IServices.FM;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums.PF;
using Microsoft.AspNetCore.Mvc;
using APT.MS.Domain.Entities.SE;
using System.Linq;
using APT.MS.Domain.Entities.PF;
using APT.MS.Domain.Entities.OG;
using APT.MS.Domain.Entities.SC.PT;
using APT.BaseData.Services.Services.FM;
namespace APT.BaseData.Services.DomainServices
{
    /// 
    /// 教育培训
    /// 
    public class PFApproveCallBackSEService : CommonService, IPFApproveCallBackSEService
    {
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IPFSysLogService SysLogService { get; set; }
        IFMDepartmentService DepartmentService { get; set; }
        public PFApproveCallBackSEService(IRepository repository, IPFCodeRuleService codeRuleService, IFMNotificationTaskService notificationTaskService, IPFSysLogService sysLogService, IFMDepartmentService departmentService)
            : base(repository)
        {
            CodeRuleService = codeRuleService;
            NotificationTaskService = notificationTaskService;
            SysLogService = sysLogService;
            DepartmentService = departmentService;
        }
        /// 
        /// 部门培训计划审批通过
        /// 
        /// 
        /// 
        public bool departmentTrainPlanAgree(string id)
        {
            var model = GetEntity(id);
            model.STATUS = PFStandardStatus.Archived;
            // 全部审批完成后,将数据插入年度培训计划子表,并发送安环部负责人
            var dt = DateTime.Now;
            var yearTrainPlanDetail = new List();
            var yearTrainPlanContent = new List();
            var depPlan = GetEntity(id, new string[] { "Nav_DepTrainPlanDetail.Nav_DepTrainPlanContent" });
            var yearTrainPlan = GetEntity(t => t.PLAN_YEAR == depPlan.PLAN_YEAR);
            var sendNotice = new T_FM_NOTIFICATION_TASK();
            var addyearTrainPlan = false;
            if (yearTrainPlan == null)
            {
                addyearTrainPlan = true;
                yearTrainPlan = new T_SE_YEAR_TRAIN_PLAN()
                {
                    ID = Guid.NewGuid(),
                    ORG_ID = depPlan.ORG_ID,
                    PLAN_YEAR = depPlan.PLAN_YEAR,
                };
            }
            depPlan.Nav_DepTrainPlanDetail.ForEach(t =>
            {
                var r = new T_SE_YEAR_TRAIN_PLAN_DETAIL();
                r.ID = Guid.NewGuid();
                r.YEAR_TRAIN_PLAN_ID = yearTrainPlan.ID;
                r.MOON = t.MOON;
                r.TYPE_ID = t.TYPE_ID;
                r.NAME = t.NAME;
                r.LEVEL = t.LEVEL;
                r.OBJECT = t.OBJECT;
                r.ADDRESS = t.ADDRESS;
                r.TRAIN_MODEL = t.TRAIN_MODEL;
                r.TEACHING_MATERIAL = t.TEACHING_MATERIAL;
                r.TEACHER = t.TEACHER;
                r.CHECK_TYPE_ID = t.CHECK_TYPE_ID;
                r.ORG_ID = t.ORG_ID;
                r.RESPONSIBILITY_DEP_ID = depPlan.LAUNCH_DEPARTMENT_ID;
                r.RESPONSIBILITY_USER_ID = depPlan.LAUNCH_USER_ID;
                yearTrainPlanDetail.Add(r);
                t.Nav_DepTrainPlanContent.ForEach(dc =>
                {
                    var c = new T_SE_YEAR_TRAIN_PLAN_CONTENT();
                    c.ID = Guid.NewGuid();
                    c.YEAR_TRAIN_PLAN_DETAIL_ID = r.ID;
                    c.CONTENT_ID = dc.CONTENT_ID;
                    c.ORG_ID = t.ORG_ID;
                    yearTrainPlanContent.Add(c);
                });
            });
            var orgId = yearTrainPlan.ORG_ID;
            var isFinishDep = GetEntities(t => t.PLAN_YEAR == yearTrainPlan.PLAN_YEAR && t.ID != model.ID, new BaseFilter(orgId));
            var isFinished = isFinishDep.Count(t => t.STATUS != PFStandardStatus.Archived);
            if (isFinished == 0)
            {
                var user = GetEntity(e => e.Nav_ApproveRole.NAME == "安环部负责人" && e.ENABLE_STATUS == 0);
                if (user == null)
                {
                    user = GetEntity(e => e.Nav_ApproveRole.NAME == "安环部安全员" && e.ENABLE_STATUS == 0);
                }
                yearTrainPlan.LAUNCH_DEPARTMENT_ID = user.DEPARTMENT_ID;
                yearTrainPlan.LAUNCH_TIME = DateTime.Now;
                yearTrainPlan.LAUNCH_USER_ID = user.ID;
                yearTrainPlan.STATUS = PFStandardStatus.Sign;
                yearTrainPlan.END_TIME = Convert.ToDateTime(DateTime.Now.ToString("D").ToString());
                if (user != null)
                {
                    sendNotice = NotificationTaskService.InsertUserNoticeTaskModel(yearTrainPlan.PLAN_YEAR + "年度培训计划", yearTrainPlan.ID, orgId, user.ID, user.NAME, DateTime.Now, DateTime.Now.AddDays(15), 0, "SE012");
                }
                else
                {
                    throw new Exception("未找到安环部负责人!");
                }
            }
            UnifiedCommit(() =>
            {
                UpdateEntityNoCommit(model);
                if (addyearTrainPlan)
                    AddEntityNoCommit(yearTrainPlan);
                if (yearTrainPlanDetail != null && yearTrainPlanDetail.Any())
                    BantchSaveEntityNoCommit(yearTrainPlanDetail);
                if (yearTrainPlanDetail != null && yearTrainPlanDetail.Any())
                    BantchSaveEntityNoCommit(yearTrainPlanContent);
                if (sendNotice != null)
                    AddEntityNoCommit(sendNotice);
            });
            return true;
        }
        /// 
        /// 部门培训计划审批通过
        /// 
        /// 
        /// 
        public bool yearTrainPlanAgree(string id)
        {
            var yearPlan = GetEntity(id, new string[] { "Nav_YearTrainPlanDepartment" });
            yearPlan.STATUS = PFStandardStatus.Archived;
            var orgId = yearPlan.ORG_ID;
            // 触发给发送部门的安全员或负责人确认
            var allRoleUser = GetEntities(t => t.APPROVE_ROLE_ID != null, new BaseFilter(orgId));
            List noticeTasks = null;
            var allSendUserIds = new List();
            var allSendUserNames = new List();
            var allSendTitle = new List();
            var allSendDataIds = new List();
            var allSendUserIds1 = new List();
            var allSendUserNames1 = new List();
            var allSendTitle1 = new List();
            var allSendDataIds1 = new List();
            var allSendTitle2 = new List();
            var sendDepartMent = yearPlan.Nav_YearTrainPlanDepartment;
            var safeRoleId = GetEntity(e => e.NAME.Contains("部门安全员")).ID;
            var chargeRoleId = GetEntity(e => e.NAME.Contains("部门负责人")).ID;
            var safeDepRoleId = GetEntity(e => e.NAME.Contains("安环部负责人")).ID;
            var safeDepRoleId1 = GetEntity(e => e.NAME.Contains("安环部安全员")).ID;
            var isAH = false;
            //2023/08/30 触发当月的培训
            List trainNotifys = new List();
            List trainNotifyContents = new List();
            // todo wyw 月份修改 为小于等于当前月 直接触发  防止万一审批的时候 跨月了
            var planNoticeData = GetEntities(t => t.MOON <= DateTime.Now.Month && t.Nav_YearTrainPlan.PLAN_YEAR == DateTime.Now.Year && t.RESPONSIBILITY_USER_ID != null, new BaseFilter(orgId), new string[] { "Nav_YearTrainPlan", "Nav_ResponsibilityUser", "Nav_YearTrainPlanContent" });
            foreach (var plan in planNoticeData)
            {
                plan.SEND = 1;
                T_SE_TRAIN_NOTIFY trainNotify = new T_SE_TRAIN_NOTIFY();
                trainNotify.ID = Guid.NewGuid();
                trainNotify.LAUNCH_TIME = DateTime.Now;
                if (plan.Nav_ResponsibilityUser != null)
                {
                    trainNotify.LAUNCH_DEPARTMENT_ID = plan.Nav_ResponsibilityUser.DEPARTMENT_ID;
                }
                if (plan.RESPONSIBILITY_USER_ID != null)
                {
                    trainNotify.LAUNCH_USER_ID = plan.RESPONSIBILITY_USER_ID;
                    trainNotify.RECORD_USER_ID = plan.RESPONSIBILITY_USER_ID;
                }
                trainNotify.NAME = plan.NAME;
                trainNotify.TRAIN_TYPE = plan.TYPE_ID;
                trainNotify.LEVEL = plan.LEVEL;
                trainNotify.TRAIN_ADDR = plan.ADDRESS;
                trainNotify.TRAIN_TEACHER = plan.TEACHER;
                trainNotify.TRAIN_MODEL = plan.TRAIN_MODEL;
                if (plan.CHECK_TYPE_ID != null)
                {
                    trainNotify.CHECK_TYPE_ID = plan.CHECK_TYPE_ID.Value;
                }
                trainNotify.STATUS = SETrainNotifyStatus.草稿;
                trainNotify.ORG_ID = orgId;
                trainNotify.CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                trainNotify.TRAIN_PLAN_DETAIL_ID = plan.ID;
                trainNotify.CREATE_NOTIFY_RECORD = true;
                plan.Nav_YearTrainPlanContent.ForEach(content =>
                {
                    T_SE_TRAIN_NOTIFY_CONTENT_REL trainNotifyContent = new T_SE_TRAIN_NOTIFY_CONTENT_REL
                    {
                        ID = Guid.NewGuid(),
                        ORG_ID = orgId,
                        POINT_ID = (Guid)content.CONTENT_ID,
                        NOTIFY_ID = trainNotify.ID
                    };
                    trainNotifyContents.Add(trainNotifyContent);
                });
                allSendTitle1.Add("制定培训通知-" + plan.NAME);
                allSendDataIds1.Add(trainNotify.ID);
                allSendUserIds1.Add((Guid)plan.RESPONSIBILITY_USER_ID);
                allSendUserNames1.Add(plan.Nav_ResponsibilityUser.NAME);
                trainNotifys.Add(trainNotify);
                allSendTitle2.Add("根据需要将《" + plan.NAME + "》培训通知盖章上传!");
            };
            foreach (var item in sendDepartMent)
            {
                isAH = false;
                var sendUser = allRoleUser.FirstOrDefault(t => t.DEPARTMENT_ID == item.DEPARTMENT_ID && t.APPROVE_ROLE_ID == safeRoleId);
                if (sendUser == null)
                {
                    sendUser = allRoleUser.FirstOrDefault(t => t.DEPARTMENT_ID == item.DEPARTMENT_ID && t.APPROVE_ROLE_ID == chargeRoleId);
                    if (sendUser == null)
                    {
                        isAH = true;
                        sendUser = allRoleUser.FirstOrDefault(t => t.DEPARTMENT_ID == item.DEPARTMENT_ID && t.APPROVE_ROLE_ID == safeDepRoleId);
                        if (sendUser == null)
                        {
                            sendUser = allRoleUser.FirstOrDefault(t => t.DEPARTMENT_ID == item.DEPARTMENT_ID && t.APPROVE_ROLE_ID == safeDepRoleId1);
                        }
                    }
                }
                //不用触发给安环部
                if (isAH == false)
                {
                    allSendTitle.Add("年度培训计划-待确认");
                    allSendDataIds.Add(yearPlan.ID);
                    allSendUserIds.Add(sendUser.ID);
                    allSendUserNames.Add(sendUser.NAME);
                }
            }
            noticeTasks = NotificationTaskService.InsertUserNoticeTaskModels(allSendTitle, allSendDataIds, orgId, allSendUserIds, allSendUserNames, DateTime.Now, yearPlan.END_TIME, 1, "SE011_SHOWPRINT");
            noticeTasks.AddRange(NotificationTaskService.InsertUserNoticeTaskModels(allSendTitle1, allSendDataIds1, orgId, allSendUserIds1, allSendUserNames1, DateTime.Now, DateTime.Now.AddDays(1), (int)FMFormTypeEnum.计划任务通知, "SE014"));
            noticeTasks.AddRange(NotificationTaskService.InsertUserNoticeTaskModels(allSendTitle2, allSendDataIds1, orgId, allSendUserIds1, allSendUserNames1, DateTime.Now, DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.今日提醒, "PF135"));
            UnifiedCommit(() =>
            {
                UpdateEntityNoCommit(yearPlan);
                if (noticeTasks != null && noticeTasks.Any())
                    BantchAddEntityNoCommit(noticeTasks);
                if (trainNotifys != null && trainNotifys.Any())
                    BantchAddEntityNoCommit(trainNotifys);
                if (trainNotifyContents != null && trainNotifyContents.Any())
                    BantchAddEntityNoCommit(trainNotifyContents);
            });
            return true;
        }
        /// 
        /// 认可与奖励审批流
        /// 
        /// 
        /// 
        public bool approveAndRewardAgree(string id)
        {
            var entity = GetEntity(id);
            entity.STATUS = PFStandardStatus.Archived;
            UnifiedCommit(() =>
            {
                UpdateEntityNoCommit(entity);
            });
            return true;
        }
        /// 
        /// 责任制考核方案审核
        /// 
        /// 
        /// 
        public bool safePdtAssessPlanCheck(string id)
        {
            var entity = GetEntity(id, "Nav_Files");
            entity.STATUS = PFStandardStatus.Archived;
            var postInput = GetEntities(t => t.CHECK_ID == Guid.Parse(id), new BaseFilter(entity.ORG_ID));
            foreach (var item in postInput)
            {
                item.STATUS = OGAssessPlanInputStatus.已提交;
            }
            List fileIds = new List();
            foreach (var file in entity.Nav_Files)
            {
                fileIds.Add(file.IMG_FILE_ID);
            }
            DepartmentService.AddDocument("安全生产组织保障", "考核方案审核表", entity.NAME + entity.LEVEL.GetDescription() + "安全生产责任制考核方案", "附件", "计划文件", DateTime.Now.AddYears(1), entity.ID, fileIds, entity.USER_ID);
            UnifiedCommit(() =>
            {
                if (entity != null)
                    UpdateEntityNoCommit(entity);
                if (postInput != null && postInput.Any())
                    BantchSaveEntityNoCommit(postInput);
            });
            return true;
        }
    }
}