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.BaseData.Services.Services.FM;

namespace APT.BaseData.Services.DomainServices
{
    /// <summary>
    /// 教育培训
    /// </summary>
    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;
        }

        /// <summary>
        /// 部门培训计划审批通过
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public bool departmentTrainPlanAgree(string id)
        {
            var model = GetEntity<T_SE_DEP_TRAIN_PLAN>(id);
            model.STATUS = PFStandardStatus.Archived;
            // 全部审批完成后，将数据插入年度培训计划子表，并发送安环部负责人
            var dt = DateTime.Now;
            var yearTrainPlanDetail = new List<T_SE_YEAR_TRAIN_PLAN_DETAIL>();
            var yearTrainPlanContent = new List<T_SE_YEAR_TRAIN_PLAN_CONTENT>();
            var depPlan = GetEntity<T_SE_DEP_TRAIN_PLAN>(id, new string[] { "Nav_DepTrainPlanDetail.Nav_DepTrainPlanContent" });
            var yearTrainPlan = GetEntity<T_SE_YEAR_TRAIN_PLAN>(t => t.PLAN_YEAR == depPlan.PLAN_YEAR);
            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);
                });
            });
            UnifiedCommit(() =>
            {
                UpdateEntityNoCommit(model);
                if (addyearTrainPlan)
                    AddEntityNoCommit(yearTrainPlan);
                if (yearTrainPlanDetail != null && yearTrainPlanDetail.Any())
                    BantchSaveEntityNoCommit(yearTrainPlanDetail);
                if (yearTrainPlanDetail != null && yearTrainPlanDetail.Any())
                    BantchSaveEntityNoCommit(yearTrainPlanContent);
            });
            return true;
        }
        /// <summary>
        /// 部门培训计划审批通过
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public bool yearTrainPlanAgree(string id)
        {
            var yearPlan = GetEntity<T_SE_YEAR_TRAIN_PLAN>(id,new string[] { "Nav_YearTrainPlanDepartment" });
            yearPlan.STATUS = PFStandardStatus.Archived;
            var orgId = yearPlan.ORG_ID;
            // 触发给发送部门的安全员或负责人确认
            var allRoleUser = GetEntities<T_FM_USER>(t => t.APPROVE_ROLE_ID != null, new BaseFilter(orgId));
            List<T_FM_NOTIFICATION_TASK> noticeTasks = null;
            var allSendUserIds = new List<Guid>();
            var allSendUserNames = new List<string>();
            var allSendTitle = new List<string>();
            var allSendDataIds = new List<Guid>();

            var allSendUserIds1 = new List<Guid>();
            var allSendUserNames1 = new List<string>();
            var allSendTitle1 = new List<string>();
            var allSendDataIds1 = new List<Guid>();

            var allSendTitle2 = new List<string>();

            var sendDepartMent = yearPlan.Nav_YearTrainPlanDepartment;
            var safeRoleId = GetEntity<T_PF_APPROVAL_ROLE>(e => e.NAME.Contains("部门安全员")).ID;
            var chargeRoleId = GetEntity<T_PF_APPROVAL_ROLE>(e => e.NAME.Contains("部门负责人")).ID;
            var safeDepRoleId = GetEntity<T_PF_APPROVAL_ROLE>(e => e.NAME.Contains("安环部负责人")).ID;
            var safeDepRoleId1 = GetEntity<T_PF_APPROVAL_ROLE>(e => e.NAME.Contains("安环部安全员")).ID;

            var isAH = false;
            //2023/08/30 触发当月的培训
            List<T_SE_TRAIN_NOTIFY> trainNotifys = new List<T_SE_TRAIN_NOTIFY>();
            List<T_SE_TRAIN_NOTIFY_CONTENT_REL> trainNotifyContents = new List<T_SE_TRAIN_NOTIFY_CONTENT_REL>();
            var planNoticeData = GetEntities<T_SE_YEAR_TRAIN_PLAN_DETAIL>(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;
        }
    }
}
