using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Entities;
using APT.Infrastructure.Core;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using APT.BaseData.Domain.IServices.FM;
using APT.MS.Domain.Enums;
using System.Collections.Generic;
using APT.BaseData.Domain.Enums.PF;
using APT.MS.Domain.Entities.OG;
using InfluxData.Net.InfluxDb.Models.Responses;
using Newtonsoft.Json.Schema;
using APT.MS.Domain.Entities.SC.SC;
using APT.MS.Domain.Entities.SC.PT;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Services.Services.FM;
using APT.MS.Domain.Entities.SC.OG;
using APT.MS.Domain.Entities.SC;
using ICSharpCode.SharpZipLib.Core;
using APT.MS.Domain.Entities.SE;
using Google.Protobuf.WellKnownTypes;
using APT.WebApi.Models;

namespace APT.PP.WebApi.Controllers.Api.PP
{
    /// <summary>
    /// 组织保障后台任务
    /// </summary>
    [Route("api/PP/OGController")]
    [TypeFilter(typeof(CustomActionFilterAttribute))]
    public class OGController : AuthorizeApiController<T_FM_BASE_CONFIG>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }

        public OGController(IFMNotificationTaskService notificationTaskService)
        {
            NotificationTaskService = notificationTaskService;
        }

        /// <summary>
        /// 安全教育模块所有跑批
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("OGTask")]
        public JsonActionResult<bool> OGTask([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    DateTime dtRun = DateTime.Now;
                    if (!string.IsNullOrEmpty(filter.Parameter1))
                    {
                        try
                        {
                            dtRun = Convert.ToDateTime(filter.Parameter1);
                        }
                        catch (Exception)
                        {
                            dtRun = DateTime.Now;
                        }
                    }
                    var config = GetEntity<T_OG_OGCONFIG>(t => true);


                    //每年1月10日触发安全生产责任制签订表
                    CheckSafePdtPersonalSigned(filter, config, dtRun);
                    //定时触发考核记录
                    CheckSafeAccessRecord(filter, dtRun);
                    //每年6月1日征集员工意见触发给各部门级部门安全员，同一部门安全员多于1人时只需1人提交
                    CheckCreateEmployeeCollection(filter, config, dtRun);
                    //回收意见
                    CheckEmployeeCollectionFinish(filter, dtRun);
                    //工余事件触发
                    CheckCreateEventGet(filter, config, dtRun);
                    //工余事件完成
                    CheckEventGetFinish(filter, dtRun);
                    //工余事件上报及处理汇总
                    CheckEventReportSum(filter, dtRun);
                    //创建相关方提醒
                    CreateReleatedAlert(filter, dtRun);
                }
                catch (Exception ex)
                {
                    if (!string.IsNullOrEmpty(ex.StackTrace))
                        throw new Exception("错误日志：[StackTrace]" + ex.StackTrace);
                    else
                        throw new Exception("【" + HttpContext.Request.Path + "】错误日志：[Message]" + ex.Message);
                }
                return true;
            });
        }
        private void CreateReleatedAlert(KeywordFilter filter, DateTime dt)
        {
            var baseFilter1 = new BaseFilter(filter.GetOrgId());
            var baseFilter2 = new BaseFilter(filter.GetOrgId());
            var baseFilter3 = new BaseFilter(filter.GetOrgId());

            baseFilter1.Include = new string[] { "Nav_Related.Nav_User" };
            baseFilter2.Include = new string[] { "Nav_Qualification.Nav_Related.Nav_User", "Nav_Item" };
            baseFilter3.Include = new string[] { "Nav_Related.Nav_User" };

            var compareDay = dt.AddMonths(3);
            var releated1 = GetEntities<T_OG_RELATED_AGREEMENT>(t => t.END_TIME.Value.Year == compareDay.Year && t.END_TIME.Value.Month == compareDay.Month && t.END_TIME.Value.Day == compareDay.Day, baseFilter1);
            var releated2 = GetEntities<T_OG_RELATED_QUALIFICATION_DETAIL>(t => t.VALID_PERIOD.Value.Year == compareDay.Year && t.VALID_PERIOD.Value.Month == compareDay.Month && t.VALID_PERIOD.Value.Day == compareDay.Day, baseFilter2);
            var releated3 = GetEntities<T_OG_RELATED_USER>(t => t.VALIDITY_TIME.Value.Year == compareDay.Year && t.VALIDITY_TIME.Value.Month == compareDay.Month && t.VALIDITY_TIME.Value.Day == compareDay.Day, baseFilter3);



            var allSendUserTitles = new List<string>();
            var allSendDataIds = new List<Guid>();
            var allSendUserIds = new List<Guid>();
            var allSendUserNames = new List<string>();
            if (releated1.Any())
            {
                foreach (var item in releated1)
                {
                    allSendUserTitles.Add("相关方《" + item.Nav_Related.NAME + "》合同/协议表中的" + item.NAME + "将于" + item.END_TIME.Value.ToShortDateString() + "到期，请及时处理！");
                    allSendDataIds.Add(item.ID);
                    allSendUserIds.Add((Guid)item.Nav_Related.USER_ID);
                    allSendUserNames.Add(item.Nav_Related.Nav_User.NAME);

                }
            }
            if (releated2.Any())
            {
                foreach (var item in releated2)
                {
                    allSendUserTitles.Add("相关方《" + item.Nav_Qualification.Nav_Related.NAME + "》资质情况表中的" + item.Nav_Item.NAME + "将于" + item.VALID_PERIOD.Value.ToShortDateString() + "到期，请及时处理！");
                    allSendDataIds.Add(item.ID);
                    allSendUserIds.Add((Guid)item.Nav_Qualification.Nav_Related.USER_ID);
                    allSendUserNames.Add(item.Nav_Qualification.Nav_Related.Nav_User.NAME);
                }
            }
            if (releated3.Any())
            {
                foreach (var item in releated3)
                {
                    allSendUserTitles.Add("相关方《" + item.Nav_Related.NAME + "》人员信息表中" + item.NAME + "的" + item.CERTIFICATE_NAME + "证书将于" + item.VALIDITY_TIME.Value.ToShortDateString() + "到期，请及时处理！");
                    allSendDataIds.Add(item.ID);
                    allSendUserIds.Add((Guid)item.Nav_Related.USER_ID);
                    allSendUserNames.Add(item.Nav_Related.Nav_User.NAME);
                }
            }
            if (allSendDataIds.Any())
            {
                var sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(allSendUserTitles, allSendDataIds, filter.GetOrgId(), allSendUserIds, allSendUserNames, DateTime.Now, DateTime.Now.AddDays(1).Date, (int)FMNoticeTypeEnum.今日提醒, "PF135");
                UnifiedCommit(() =>
                {
                    if (sendNotices.Any())
                        BantchAddEntityNoCommit(sendNotices);
                });
            }
        }
        public void CheckSafePdtPersonalSigned(KeywordFilter filter, T_OG_OGCONFIG config, DateTime dt)
        {
            //检查配置是否存在，并验证是否在同一天
            //var dt = DateTime.Now;
            //var config = GetEntity<T_OG_OGCONFIG>(t => true);
            DateTime startTime;
            if (config == null)
            {
                startTime = new DateTime(dt.Year, 1, 10);
            }
            else if (config.SAFE_PDT_PERSONAL_SIGNED_TRIGGER_TIME != null)
            {
                startTime = (DateTime)config.SAFE_PDT_PERSONAL_SIGNED_TRIGGER_TIME;
            }
            else
            {
                return;
            }
            if (dt.Month != startTime.Month || dt.Day != startTime.Day)
            {
                return;
            }
            var pdtCount = GetEntities<T_OG_SAFE_PDT_SIGNED>(t => t.ANNUAL == dt.Year, new BaseFilter(filter.GetOrgId())).ToList();
            //if (pdtCount.Any())
            //{
            //    return;
            //}
            var pdtList = new List<T_OG_SAFE_PDT_SIGNED>();
            var pdtListDetail = new List<T_OG_SAFE_PDT_SIGNED_POST>();
            var allSendUserTitles = new List<string>();
            var allSendDataIds = new List<Guid>();
            var allSendUserIds = new List<Guid>();
            var allSendUserNames = new List<string>();
            BaseFilter baseFilter = new BaseFilter(filter.GetOrgId());
            baseFilter.Include = new string[] { "Nav_Post.Nav_Depts.Nav_Posts", "Nav_Post.Nav_Depts.Nav_Department" };
            baseFilter.IgnoreDataRule = true;
            var standardPost = GetEntities<T_SC_STANDARD_CREATE>(t => t.TYPE == SCType.安全生产责任制 && t.STATUS == SCSystemEditStatus.已归档 && t.FILE_STATUS == SCSystemFileStatus.有效, baseFilter);

            BaseFilter userFilter = new BaseFilter(filter.GetOrgId());
            userFilter.Include = new string[] { "Nav_User.Nav_Department" };
            var allPersons = GetEntities<T_FM_PERSON>(t => t.Nav_User.ENABLE_STATUS == 0, userFilter);

            var listUser = GetEntities<T_FM_USER>(e => e.ENABLE_STATUS == 0, null, "Nav_Person");
            T_OG_SAFE_PDT_SIGNED modelPDT = null;
            T_FM_USER chargeUser = null;
            foreach (var t1 in standardPost)
            {
                //如果 年份 人员  标准化创建 有信息 就过
                modelPDT = pdtCount.FirstOrDefault(e => e.STANDARD_ID == t1.ID);
                if (modelPDT != null)
                {
                    continue;
                }

                foreach (var t2 in t1.Nav_Post.Nav_Depts)
                {
                    chargeUser = listUser.FirstOrDefault(t => t.DEPARTMENT_ID == t1.Nav_Post.DEPARTMENT_ID && t.Nav_Person.POST_ID == t1.Nav_Post.DEPOST_ID);
                    if (chargeUser == null)
                        continue;

                    //var chargeUser = GetEntity<T_FM_USER>(t => t.DEPARTMENT_ID == t1.Nav_Post.DEPARTMENT_ID && t.Nav_Person.POST_ID == t1.Nav_Post.DEPOST_ID && t.ENABLE_STATUS == 0);
                    T_OG_SAFE_PDT_SIGNED record = new T_OG_SAFE_PDT_SIGNED
                    {
                        ID = Guid.NewGuid(),
                        ORG_ID = filter.GetOrgId(),
                        STATUS = (int)PFStandardStatus.Draft,
                        TRIGGER_TYPE = OGPersonalSignedTriggerType.年度触发,//.任务触发,
                        STANDARD_ID = t1.ID,
                        FILE_CONTENT = t1.FILE_CONTENT,
                        DEPARTMENT_ID = t2.DEPARTMENT_ID,
                        ANNUAL = DateTime.Now.Year
                    };
                    if (chargeUser != null)
                    {
                        record.CHARGE_USER_ID = chargeUser.ID;
                    }
                    pdtList.Add(record);
                    var posts = t2.Nav_Posts.Select(t => t.DEPOST_ID).ToList();
                    var currPostPersons = allPersons.Where(t => t.POST_ID != null && t.Nav_User.DEPARTMENT_ID == t2.DEPARTMENT_ID && posts.Contains((Guid)t.POST_ID));
                    if (currPostPersons != null && currPostPersons.Any())
                    {
                        foreach (var item in currPostPersons)
                        {
                            T_OG_SAFE_PDT_SIGNED_POST post = new T_OG_SAFE_PDT_SIGNED_POST
                            {
                                SAFE_PDT_SIGNED_ID = record.ID,
                                ID = Guid.NewGuid(),
                                ORG_ID = filter.GetOrgId(),
                                USER_ID = item.Nav_User.ID,
                                POST_ID = item.POST_ID,
                                CHARGE_USER_ID = record.CHARGE_USER_ID
                            };
                            allSendUserTitles.Add(DateTime.Now.ToShortDateString() + "安全生产责任制个人签订表");
                            allSendDataIds.Add(record.ID);
                            allSendUserIds.Add(item.Nav_User.ID);
                            allSendUserNames.Add(item.Nav_User.NAME);
                            pdtListDetail.Add(post);
                        }
                    }
                }
            }
            var sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(allSendUserTitles, allSendDataIds, filter.GetOrgId(), allSendUserIds, allSendUserNames, DateTime.Now, DateTime.Now.AddDays(7), 1, "OG001_SHOWPRINT");
            UnifiedCommit(() =>
            {
                if (pdtList != null && pdtList.Any())
                    BantchAddEntityNoCommit(pdtList);
                if (pdtListDetail != null && pdtListDetail.Any())
                    BantchAddEntity(pdtListDetail);
                if (sendNotices != null && sendNotices.Any())
                    BantchAddEntityNoCommit(sendNotices);
            });
        }

        public JsonActionResult<bool> CheckSafeAccessRecord(KeywordFilter filter, DateTime dtNow)
        {
            return SafeExecute<bool>(() =>
            {
                //var dtNow = DateTime.Now;
                var year = dtNow.Year;
                var month = dtNow.Month;
                var day = dtNow.Day;
                //var time = dtNow.TimeOfDay;
                var week = dtNow.DayOfWeek;
                var timeSet = this.GetEntities<T_OG_SAFE_ASSESS_PLAN_INPUT>(e => e.STATUS == OGAssessPlanInputStatus.已提交 && e.IS_DELETED == false && (e.ANNUAL == year || e.ANNUAL == (year - 1)), new BaseFilter(filter.OrgId), new string[] { "Nav_SafeAssessItem", "Nav_User", "Nav_Post" }).ToList();
                if (timeSet.Count < 1)
                    return true;
                List<T_OG_SAFE_ASSESS_RECORD> monitorList = new List<T_OG_SAFE_ASSESS_RECORD>();
                List<T_OG_SAFE_ASSESS_RECORD_DETAIL> monitorDetailList = new List<T_OG_SAFE_ASSESS_RECORD_DETAIL>();
                List<T_OG_SAFE_ASSESS_RECORD_ITEM> detailContentList = new List<T_OG_SAFE_ASSESS_RECORD_ITEM>();
                List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                foreach (var item in timeSet)
                {
                    if (item.Nav_User != null && item.Nav_User.APPROVE_ROLE_ID != null && item.Nav_SafeAssessItem != null && item.Nav_SafeAssessItem.Any())
                    {
                        //年度
                        if (item.CYCLE == PTAssessmentCycleEnums.Year && item.ANNUAL == (year - 1))
                        {
                            if (month == 1 && day == 1)
                            {
                                monitorList.Add(CreateDepartMonitorNew(item, item.Nav_SafeAssessItem, PTAssessmentCycleEnums.Year, year - 1, ref notices));
                            }
                        }
                        //上半年度
                        List<int> monthTemp = new List<int>() { 1, 2, 3, 4, 5, 6 };
                        if (item.CYCLE == PTAssessmentCycleEnums.HalfYear && item.ANNUAL == year && monthTemp.Contains(item.CREATE_TIME.Value.Month))
                        {
                            if (month == 7 && day == 1)
                            {
                                monitorList.Add(CreateDepartMonitorNew(item, item.Nav_SafeAssessItem, PTAssessmentCycleEnums.HalfYear, year, ref notices));
                            }
                        }
                        //下半年度
                        monthTemp = new List<int>() { 7, 8, 9, 10, 11, 12 };
                        if (item.CYCLE == PTAssessmentCycleEnums.HalfYear && item.ANNUAL == (year - 1) && monthTemp.Contains(item.CREATE_TIME.Value.Month))
                        {
                            if (month == 1 && day == 1)
                            {
                                monitorList.Add(CreateDepartMonitorNew(item, item.Nav_SafeAssessItem, PTAssessmentCycleEnums.HalfYear, year - 1, ref notices));
                            }
                        }
                        //季度(第四季度)
                        monthTemp = new List<int>() { 12 };
                        if (item.CYCLE == PTAssessmentCycleEnums.Quarter && item.ANNUAL == (year - 1) && monthTemp.Contains(item.CREATE_TIME.Value.Month))
                        {
                            if (month == 1 && day == 1)
                            {
                                monitorList.Add(CreateDepartMonitorNew(item, item.Nav_SafeAssessItem, PTAssessmentCycleEnums.Quarter, year - 1, ref notices));
                            }
                        }
                        //季度(第1、2、3季度)
                        if (item.CYCLE == PTAssessmentCycleEnums.Quarter && item.ANNUAL == year && monthTemp.Contains(item.CREATE_TIME.Value.Month))
                        {
                            if ((month == 4 && day == 1) || (month == 7 && day == 1) || (month == 10 && (day == 28 || day == 29)))
                            {
                                monthTemp = new List<int>() { month - 1 };
                                monitorList.Add(CreateDepartMonitorNew(item, item.Nav_SafeAssessItem, PTAssessmentCycleEnums.Quarter, year, ref notices));
                            }
                        }
                        //月度
                        monthTemp = new List<int>() { month - 1 };
                        if (item.CYCLE == PTAssessmentCycleEnums.Month && item.ANNUAL == year && monthTemp.Contains(item.CREATE_TIME.Value.Month))
                        {
                            if (month != 1 && day == 1)
                            {
                                monitorList.Add(CreateDepartMonitorNew(item, item.Nav_SafeAssessItem, PTAssessmentCycleEnums.Month, year, ref notices));
                            }
                        }
                        //月度(第十二月)
                        monthTemp = new List<int>() { 12 };
                        if (item.CYCLE == PTAssessmentCycleEnums.Month && item.ANNUAL == (year - 1) && monthTemp.Contains(item.CREATE_TIME.Value.Month))
                        {
                            if (month == 1 && day == 1)
                            {
                                monitorList.Add(CreateDepartMonitorNew(item, item.Nav_SafeAssessItem, PTAssessmentCycleEnums.Month, year - 1, ref notices));
                            }
                        }
                    }
                }
                if (monitorList != null && monitorList.Any())
                {
                    monitorList.ForEach(t =>
                    {
                        if (t.Nav_Details != null && t.Nav_Details.Any())
                        {
                            t.Nav_Details.ForEach(t1 =>
                            {
                                if (t1.Nav_SafeAssessRecordItem != null && t1.Nav_SafeAssessRecordItem.Any())
                                {
                                    detailContentList.AddRange(t1.Nav_SafeAssessRecordItem);
                                    t1.Nav_SafeAssessRecordItem = null;
                                }
                            });
                            monitorDetailList.AddRange(t.Nav_Details);
                            t.Nav_Details = null;
                        }
                    });
                }

                UnifiedCommit(() =>
                {
                    if (monitorList != null && monitorList.Any())
                        BantchSaveEntityNoCommit(monitorList);
                    if (monitorDetailList != null && monitorDetailList.Any())
                        BantchAddEntityNoCommit(monitorDetailList);
                    if (detailContentList != null && detailContentList.Any())
                        BantchAddEntityNoCommit(detailContentList);
                    if (notices != null && notices.Any())
                        BantchAddEntityNoCommit(notices);
                });
                return true;
            });
        }

        /// <summary>
        /// 触发班组监测与考核记录表
        /// </summary>
        /// <param name="item"></param>
        /// <param name="details"></param>
        /// <param name="notices"></param>
        private T_OG_SAFE_ASSESS_RECORD CreateDepartMonitorNew(T_OG_SAFE_ASSESS_PLAN_INPUT item, ICollection<T_OG_SAFE_ASSESS_ITEM> details, PTAssessmentCycleEnums cycle, int year, ref List<T_FM_NOTIFICATION_TASK> notices)
        {
            var record = new T_OG_SAFE_ASSESS_RECORD();
            record.ORG_ID = item.ORG_ID;
            record.TIME = DateTime.Now;
            record.USER_ID = item.USER_ID;
            record.DEPARTMENT_ID = item.DEPARTMENT_ID;
            record.ANNUAL = year;
            record.CYCLE = cycle;
            record.STATUS = PFStandardStatus.Draft;
            var filter = new BaseFilter(item.ORG_ID);
            filter.SelectField = new string[] { "DEPOST_ID" };
            var allPosts = GetEntities<T_SC_POST_DEPOST>(t => t.POST_ID == item.POST_ID, filter).Select(t => t.DEPOST_ID);
            var userPost = new BaseFilter(item.ORG_ID);
            userPost.Include = new string[] { "Nav_User" };
            var allUserPosts = GetEntities<T_FM_PERSON>(t => allPosts.Contains((Guid)t.POST_ID) && t.DEPARTMENT_ID == item.DEPARTMENT_ID, userPost);
            var monitorDetails = new List<T_OG_SAFE_ASSESS_RECORD_DETAIL>();
            var contents = new List<T_OG_SAFE_ASSESS_RECORD_ITEM>();
            foreach (var post in allUserPosts)
            {
                T_OG_SAFE_ASSESS_RECORD_DETAIL detail = new T_OG_SAFE_ASSESS_RECORD_DETAIL();
                detail.ORG_ID = record.ORG_ID;
                detail.POST_ID = item.POST_ID;
                detail.SAFE_ASSESS_RECORD_ID = record.ID;
                detail.USER_ID = post.Nav_User.ID;
                foreach (var d in details)
                {
                    T_OG_SAFE_ASSESS_RECORD_ITEM content = new T_OG_SAFE_ASSESS_RECORD_ITEM();
                    content.ORG_ID = record.ORG_ID;
                    content.RECORD_DETAIL_ID = detail.ID;
                    content.ROW_NO = d.ROW_NO;
                    content.ASSESS_ITEM_ID = d.ID;
                    contents.Add(content);
                    detail.Nav_SafeAssessRecordItem = contents;
                    monitorDetails.Add(detail);
                }
            }
            record.Nav_Details = monitorDetails;
            string title = "";
            if (record.CYCLE == PTAssessmentCycleEnums.Day)
            {
                title = "每天";
            }
            if (record.CYCLE == PTAssessmentCycleEnums.Week)
            {
                title = "每周";
            }
            if (record.CYCLE == PTAssessmentCycleEnums.Month)
            {
                title = DateTime.Now.Month + "月";
            }
            if (record.CYCLE == PTAssessmentCycleEnums.Quarter)
            {
                int month = DateTime.Now.Month;
                if (month >= 1 && month <= 3)
                {
                    title = "第一季度";
                }
                else if (month >= 4 && month <= 6)
                {
                    title = "第二季度";
                }
                else if (month >= 7 && month <= 9)
                {
                    title = "第三季度";
                }
                else if (month >= 10 && month <= 12)
                {
                    title = "第四季度";
                }
            }
            if (record.CYCLE == PTAssessmentCycleEnums.HalfYear)
            {
                int month = DateTime.Now.Month;
                if (month >= 1 && month <= 6)
                {
                    title = "上半年";
                }
                else if (month >= 7 && month <= 12)
                {
                    title = "下半年";
                }
            }
            if (record.CYCLE == PTAssessmentCycleEnums.Year)
            {
                title = "年";
            }
            record.CYCLE_NAME = DateTime.Now.Year + title;
            //发消息
            notices.Add(NotificationTaskService.InsertUserNoticeTaskModel("(" + record.CYCLE_NAME + item.Nav_Post.NAME + ")安全生产责任制考核记录", record.ID, record.ORG_ID, item.USER_ID.Value, item?.Nav_User?.NAME, DateTime.Now,
            DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "OG008"));
            return record;
        }





        //创建员工意见征集
        private void CheckCreateEmployeeCollection(KeywordFilter filter, T_OG_OGCONFIG config, DateTime dt)
        {
            //var dt = DateTime.Now;
            DateTime startTime;
            //var config = GetEntity<T_OG_OGCONFIG>(t => true);
            if (config == null || config.EMPLOYEE_OPINION_TIME == null)
            {
                startTime = new DateTime(dt.Year, 6, 1);
            }
            else
            {
                startTime = (DateTime)config.EMPLOYEE_OPINION_TIME;
            }
            if (dt.Month == startTime.Month && dt.Day == startTime.Day)
            {
                var data = GetEntities<T_OG_EMPLOYEE_OPINION_COLLECTION>(t => t.START_TIME.Value.Month == startTime.Month && t.START_TIME.Value.Day == startTime.Day, new BaseFilter(filter.GetOrgId())).ToList();
                if (data.Count > 0)
                {
                    return;
                }
                var users = GetEntities<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "部门安全员" || t.Nav_ApproveRole.NAME == "车间安全员" || t.Nav_ApproveRole.NAME == "安环部负责人" || t.Nav_ApproveRole.NAME == "安环部安全员", new BaseFilter(filter.GetOrgId()), new string[] { "Nav_ApproveRole", "Nav_Department" }).ToList();
                List<T_OG_EMPLOYEE_OPINION_COLLECTION> employeeOpinions = new List<T_OG_EMPLOYEE_OPINION_COLLECTION>();
                var allSendUserTitles = new List<string>();
                var allSendDataIds = new List<Guid>();
                var allSendUserIds = new List<Guid>();
                var allSendUserNames = new List<string>();
                var safeUser = users.Where(t => t.Nav_ApproveRole.NAME == "部门安全员");
                if (safeUser.Count() == 0)
                {
                    safeUser = users.Where(t => t.Nav_ApproveRole.NAME == "车间安全员");

                }
                safeUser.ForEach(user =>
                {
                    var ahSafe = users.FirstOrDefault(t => t.Nav_ApproveRole.NAME == "安环部负责人");
                    if (ahSafe == null)
                    {
                        ahSafe = users.FirstOrDefault(t => t.Nav_ApproveRole.NAME == "安环部安全员");
                    }
                    var employeeOpinion = new T_OG_EMPLOYEE_OPINION_COLLECTION
                    {
                        ID = Guid.NewGuid(),
                        AH_CHARGE_USER_ID = ahSafe.ID,
                        DEPARTMENT_ID = user.DEPARTMENT_ID,
                        USER_ID = user.ID,
                        CHARGE_USER_ID = user.Nav_Department.USER_ID,
                        CREATER_ID = user.ID,
                        START_TIME = DateTime.Now,
                        ORG_ID = filter.GetOrgId(),

                    };
                    employeeOpinions.Add(employeeOpinion);
                    allSendUserTitles.Add("员工意见征集");
                    allSendDataIds.Add(employeeOpinion.ID);
                    allSendUserIds.Add(user.ID);
                    allSendUserNames.Add(user.NAME);
                });
                var sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(allSendUserTitles, allSendDataIds, filter.GetOrgId(), allSendUserIds, allSendUserNames, DateTime.Now, DateTime.Now.AddDays(1), 1, "OG060");
                UnifiedCommit(() =>
                {
                    if (employeeOpinions != null && employeeOpinions.Any())
                        BantchAddEntityNoCommit(employeeOpinions);
                    if (sendNotices != null && sendNotices.Any())
                        BantchAddEntityNoCommit(sendNotices);
                });
            }

        }
        //回收员工意见
        private void CheckEmployeeCollectionFinish(KeywordFilter filter, DateTime dt)
        {
            //var dt = DateTime.Now;
            BaseFilter baseFilter = new BaseFilter(filter.GetOrgId());
            baseFilter.IgnoreDataRule = true;
            var data = GetEntities<T_OG_EMPLOYEE_OPINION_COLLECTION>(t => t.STATUS == OGEmployeeOpinionStatus.意见征集中 && t.END_TIME.Value <= dt, baseFilter).ToList();
            if (data.Count == 0)
                return;
            var allSendUserTitles = new List<string>();
            var allSendDataIds = new List<Guid>();
            var allSendUserIds = new List<Guid>();
            var allSendUserNames = new List<string>();
            data.ForEach(it =>
            {
                it.STATUS = OGEmployeeOpinionStatus.汇总中;
            });
            data.ForEach(it =>
            {
                allSendUserTitles.Add("员工意见征集汇总");
                allSendDataIds.Add(it.ID);
                allSendUserIds.Add(it.USER_ID.Value);
                allSendUserNames.Add(GetEntity<T_FM_USER>(it.USER_ID.Value).NAME);
            });
            var sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(allSendUserTitles, allSendDataIds, filter.GetOrgId(), allSendUserIds, allSendUserNames, DateTime.Now, DateTime.Now.AddDays(1), 1, "OG059_REPORT");

            UnifiedCommit(() =>
            {
                BantchSaveEntityNoCommit(data);
                BantchAddEntityNoCommit(sendNotices);
            });

        }
        private void CheckCreateEventGet(KeywordFilter filter, T_OG_OGCONFIG config, DateTime dt)
        {
            //3月1日、9月1日触发给安环部负责人，触发时间和频率可以在基础设置调整
            //var config = GetEntity<T_OG_OGCONFIG>(t => true);
            var mm1 = 0;
            var dd1 = 0;
            var mm2 = 0;
            var dd2 = 0;
            if (config != null)
            {
                if (config.EVENT_GET_TIME != null)
                {
                    mm1 = config.EVENT_GET_TIME.Value.Month;
                    dd1 = config.EVENT_GET_TIME.Value.Day;
                }
                if (config.EVENT_GET_TIME_1 != null)
                {
                    mm2 = config.EVENT_GET_TIME_1.Value.Month;
                    dd2 = config.EVENT_GET_TIME_1.Value.Day;
                }
            }

            //var dt = DateTime.Now;
            if ((dt.Month != mm1 || dt.Day != dd1) && (dt.Month != mm2 || dt.Day != dd2))
                return;
            var mm = dt.Month;
            var dd = dt.Day;
            BaseFilter baseFilter = new BaseFilter(filter.GetOrgId());
            baseFilter.IgnoreDataRule = true;
            var data = GetEntities<T_OG_EVENT_GET>(t => t.START_TIME != null && t.START_TIME.Value.Month == mm && t.START_TIME.Value.Day == dd && t.BACK, baseFilter).ToList();
            if (data.Count > 0)
            {
                return;
            }
            var AHUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部负责人");
            if (AHUser == null)
            {
                AHUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部安全员");
            }

            var evt = new T_OG_EVENT_GET
            {
                ID = Guid.NewGuid(),
                ORG_ID = filter.GetOrgId(),
                USER_ID = AHUser.ID,
                START_TIME = dt,
                DEPARTMENT_ID = AHUser.DEPARTMENT_ID,
                BACK = true,
            };

            var sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("工余事件征集", evt.ID, evt.ORG_ID, AHUser.ID, AHUser.NAME, DateTime.Now, DateTime.Now.AddDays(1), 1, "OG030");

            UnifiedCommit(() =>
            {
                AddEntityNoCommit(evt);
                if (sendNotice != null)
                    AddEntityNoCommit(sendNotice);
            });
        }
        public void CheckEventGetFinish(KeywordFilter filter, DateTime dt)
        {
            //var dt = DateTime.Now;
            var reportGet = GetEntity<T_OG_EVENT_GET>(t => t.START_TIME.Value.Year == dt.Year && t.STATUS == OGEventStatus.征集中, new string[] { "Nav_Details.Nav_Items" });
            if (reportGet == null)
                return;
            var mm = reportGet.END_TIME.Value.Month;
            var dd = reportGet.END_TIME.Value.Day;
            if (dt.Month != mm || dt.Day != dd)
                return;
            var AHUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部负责人");
            if (AHUser == null)
            {
                AHUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部安全员");
            };
            reportGet.STATUS = OGEventStatus.汇总中;
            int count = 0;
            var allDetails = reportGet.Nav_Details.Where(t => t.STATUS == OGEventGetUserStatus.完成);
            foreach (var item in allDetails)
            {
                count += item.Nav_Items.Count(t => t.DESC != "");
            }
            reportGet.EVENT_COUNT = count;
            var sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("工余事件征集汇总", reportGet.ID, filter.GetOrgId(), AHUser.ID, AHUser.NAME, DateTime.Now, DateTime.Now.AddDays(1), 0, "OG030_SHOWPRINT");
            UnifiedCommit(() =>
            {
                UpdateEntityNoCommit(reportGet);
                AddEntityNoCommit(sendNotice);
            });
        }
        public void CheckEventReportSum(KeywordFilter filter, DateTime dt)
        {
            var last = GetEntity<T_OG_EVENT_REPORT_SUM>(t => t.TIME < dt.AddMonths(-1));
            if (last == null)
            {
                var total = GetCount<T_OG_EVENT_REPORT>(t => t.IS_DELETED == false, new BaseFilter(filter.GetOrgId()));
                var num = GetCount<T_OG_EVENT_REPORT>(t => t.IS_DELETED == false && t.STATUS == PFStandardStatus.Archived, new BaseFilter(filter.GetOrgId()));
                T_OG_EVENT_REPORT_SUM sum = new T_OG_EVENT_REPORT_SUM();
                if (total > 0)
                {
                    sum.RATIO = num / total * 100;
                    sum.SUM_YEAR = DateTime.Now.Year;
                    sum.TIME = DateTime.Now;
                    sum.ORG_ID = filter.GetOrgId();
                    UnifiedCommit(() =>
                    {
                        AddEntityNoCommit(sum);
                    });
                }
            }
        }
        //检查相关方是否证件到期
        private void CheckReleateExpire(KeywordFilter filter)
        {
            var baseFilter = new BaseFilter(filter.GetOrgId());
            baseFilter.Include = new string[] { "Nav_User" };
            var allTrain = GetEntities<T_SE_RENEWAL_TRAIN>(t => t.IS_DELETED == false && t.Nav_User.ENABLE_STATUS == 0, baseFilter);//离职的不做提醒
            var overTime = allTrain.Where(t => t.REVIEW_DATE == DateTime.Now.Date.AddMonths(3));
            //overTime = allTrain.Where(t => t.REVIEW_DATE == DateTime.Parse("2023-05-02").AddMonths(3));
            var equalTime = allTrain.Where(t => t.REVIEW_DATE == DateTime.Now.Date);
            var AHUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部安全员" && t.ENABLE_STATUS == 0);
            if (AHUser != null)
            {
                var allSendUserTitles = new List<string>();
                var allSendDataIds = new List<Guid>();
                var allSendUserIds = new List<Guid>();
                var allSendUserNames = new List<string>();
                if (overTime.Any())
                {
                    foreach (var item in overTime)
                    {
                        allSendUserTitles.Add(item.Nav_User.NAME + item.Nav_User.CODE + "《" + item.CERTIFICATE_NAME + "》证书将于" + item.REVIEW_DATE.ToShortDateString() + "到期复审，请提前安排委外培训");
                        allSendDataIds.Add(item.ID);
                        allSendUserIds.Add(item.USER_ID);
                        allSendUserNames.Add(item.Nav_User.NAME);

                        allSendUserTitles.Add(item.Nav_User.NAME + item.Nav_User.CODE + "《" + item.CERTIFICATE_NAME + "》证书将于" + item.REVIEW_DATE.ToShortDateString() + "到期复审，请提前安排委外培训");
                        allSendDataIds.Add(item.ID);
                        allSendUserIds.Add(AHUser.ID);
                        allSendUserNames.Add(AHUser.NAME);
                    }
                }
                if (equalTime.Any())
                {
                    foreach (var item in equalTime)
                    {
                        allSendUserTitles.Add(item.Nav_User.NAME + item.Nav_User.CODE + "《" + item.CERTIFICATE_NAME + "》证书于" + item.REVIEW_DATE.ToShortDateString() + "到期，请到换证培训更新复审日期!");
                        allSendDataIds.Add(item.ID);
                        allSendUserIds.Add(AHUser.ID);
                        allSendUserNames.Add(AHUser.NAME);
                    }
                }
                if (allSendDataIds.Any())
                {
                    var sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(allSendUserTitles, allSendDataIds, filter.GetOrgId(), allSendUserIds, allSendUserNames, DateTime.Now, DateTime.Now.AddDays(1).Date, (int)FMNoticeTypeEnum.今日提醒, "PF135");
                    UnifiedCommit(() =>
                    {
                        if (sendNotices.Any())
                            BantchAddEntityNoCommit(sendNotices);
                    });
                }
            }
        }
    }
}
