using APT.BaseData.Domain.ApiModel;
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.Entities.HM;
using APT.MS.Domain.Entities.OG;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;

namespace APT.FO.WebApi.Controllers
{
    /// <summary>
    /// 技术交底表
    /// </summary>
    [Route("api/FO/FOTechDisclosureFrom")]
    public partial class TechDisclosureFromController : AuthorizeApiController<T_FO_TECH_DISCLOSURE_FROM>
    {
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMDepartmentService DepartmentService { get; set; }
        /// <summary>
        /// FOPreOperSch
        /// </summary>
        /// <param name="codeRuleService"></param>
        public TechDisclosureFromController(IPFCodeRuleService codeRuleService, IFMNotificationTaskService notificationTaskService, IFMDepartmentService departmentService)
        {
            CodeRuleService = codeRuleService;
            NotificationTaskService = notificationTaskService;
            DepartmentService = departmentService;
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetEditOld")]
        public JsonActionResult<T_FO_TECH_DISCLOSURE_FROM> GetEditOld([FromBody] KeywordFilter filter)
        {
            filter.Include.Clear();
            filter.Include.Add("Nav_JobName");
            filter.Include.Add("Nav_JobNameOut");
            filter.Include.Add("Nav_OperationStep");
            filter.Include.Add("Nav_DisclosurePerson.Nav_UserSignFiles.Nav_ImgFile.Nav_File");
            filter.Include.Add("Nav_Person.Nav_User.Nav_UserSignFiles.Nav_ImgFile.Nav_File");
            filter.Include.Add("Nav_Person.Nav_RelatedUser.Nav_Signs.Nav_ImgFile.Nav_File");
            var result = WitEntity(null, filter);
            if (result.Data != null)
            {
                result.Data.Nav_Person = result.Data.Nav_Person.OrderBy(t => t.MODIFY_TIME).ThenByDescending(m => m.DEAL_STATUS).ToList();
            }
            return result;
        }

        [HttpPost, Route("GetEdit")]
        public JsonActionResult<T_FO_TECH_DISCLOSURE_FROM> GetEdit([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() => {
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
            if (string.IsNullOrEmpty(id))
                this.ThrowError("060010");
            var entity = this.GetEntity<T_FO_TECH_DISCLOSURE_FROM>(id,"Nav_OperationStep", "Nav_JobName", "Nav_JobNameOut", "Nav_DisclosurePerson.Nav_UserSignFiles.Nav_ImgFile.Nav_File");
            if (entity != null)
            {
                var newFilter = new BaseFilter(filter.OrgId);
                newFilter.SelectField = new List<string> { "ID", "DEAL_STATUS", "TECH_DISCLOSURE_FROM_ID", "USER_ID", "RELATED_USER_ID", "Nav_User.NAME", "Nav_User.CODE", "Nav_User.Nav_UserSignFiles.Nav_ImgFile.Nav_File", "Nav_RelatedUser.NAME", "Nav_RelatedUser.Nav_Signs.Nav_ImgFile.Nav_File" };
                var persons = this.GetEntities<T_FO_TECH_DISCLOSURE_PERSON>(t => t.TECH_DISCLOSURE_FROM_ID == entity.ID, newFilter).ToList();
                entity.Nav_Person = persons.OrderBy(t => t.MODIFY_TIME).ThenByDescending(m => m.DEAL_STATUS).ToList();
            }
            return entity;
            });
        }
        /// <summary>
        /// 新增修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_FO_TECH_DISCLOSURE_FROM entity)
        {
            return SafeExecute<bool>(() =>
            {
                entity.FORM_STATUS = (int)FOTeamActivityState.草稿;
                var persons = entity.Nav_Person;
                var deleteIds = new List<Guid>();
                if (persons != null && persons.Any())
                {
                    deleteIds = persons.Where(t => t.IS_DELETED).Select(m => m.ID).ToList();
                    persons = persons.Where(t => !t.IS_DELETED).ToList();
                }
                entity.Nav_Person = null;
                
                List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                T_FM_NOTIFICATION_TASK task = null;
                T_FO_JOB_ACTIVITY_RECORD record = null;
                List<T_FO_JOB_ACTIVITY_PERSON> apersons = new List<T_FO_JOB_ACTIVITY_PERSON>();
                List<T_FO_JOB_ACTIVITY_DETAIL> detailList = new List<T_FO_JOB_ACTIVITY_DETAIL>();
                List<T_FO_JOB_ACTIVITY_FLOW> flowList = new List<T_FO_JOB_ACTIVITY_FLOW>();
                List<T_FO_JOB_ACTIVITY_MEASURE> measureList = new List<T_FO_JOB_ACTIVITY_MEASURE>();
                var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                entity.DEPARTMENT_ID = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID;
                entity.DisclosureContent =entity.DisclosureContent.Trim().Replace(" ","");
                if (persons != null && persons.Any())
                {
                    persons.ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID; t.TECH_DISCLOSURE_FROM_ID = entity.ID;
                    });
                }
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                    {
                        if (entity.IS_OUTSOURCE == true && entity.RELATED_ID != null)
                        {
                            var userIds = new List<Guid>();
                            persons.ForEach(t =>
                            {
                                if (t.USER_ID == loginUserId)
                                    t.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                                if(t.RELATED_USER_ID != null)
                                    t.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                                if(t.USER_ID != null)
                                    userIds.Add((Guid)t.USER_ID);
                            });
                            var tech = this.GetEntity<T_FO_TECH_DISCLOSURE_FROM>(entity.ID, "Nav_JobNameOut", "Nav_JobNameOut.Nav_CrucialLicensePerson", "Nav_Person", "Nav_JobNameOut.Nav_SafeConfirms", "Nav_JobNameOut.Nav_SafeMeasures", "Nav_JobNameOut.Nav_DealMeasures");
                            if (userIds != null && userIds.Any())
                            {
                                entity.FORM_STATUS = (int)FOTeamActivityState.签到中;
                                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);
                                }
                                //发消息
                                DateTime dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.JobSite, entity.ORG_ID.Value, DateTime.Now, null, null);
                                notices = NotificationTaskService.InsertUserNoticeTaskModels("安全技术交底表外包确认(" + tech?.Nav_JobNameOut?.JOB_DATE.Value.ToShortDateString().Replace(" / ", "") + ")", entity.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                                dtEnd, (int)FMNoticeTypeEnum.消息, "FO019_SHOWPRINT");
                            }
                            else
                            {
                                entity.FORM_STATUS = (int)FOTeamActivityState.已归档;
                                //自动生成作业活动记录表
                                record = new T_FO_JOB_ACTIVITY_RECORD();
                                //取审批流水码
                                var sysFilter = new SystemCodeFilter();
                                sysFilter.CodeType = (int)PFCodeRuleType.关键许可作业活动记录表编号;
                                sysFilter.Count = 1;
                                sysFilter.OrgId = tech.ORG_ID;
                                var codes = CodeRuleService.NewGenSerial(sysFilter);
                                var codeList = codes.Split(new char[] { ',' });
                                record.CODE = codeList[0];
                                record.JOB_NAME_OUTSOURCE_ID = tech.JOB_NAME_OUTSOURCE_ID;
                                record.OPERATION_STEP_ID = tech.OPERATION_STEP_ID;
                                record.TECH_DISCLOSURE_ID = tech.ID;
                                record.JOB_DATE = tech.Nav_JobNameOut?.JOB_DATE ?? DateTime.Now;
                                record.JOB_END_DATE = tech.Nav_JobNameOut?.JOB_END_DATE ?? DateTime.Now;
                                record.ORG_ID = tech.ORG_ID;
                                record.JOB_LOCATION = tech.Nav_JobNameOut?.JOB_LOCATION;
                                record.IS_EFFECTIVE = (int)ISImportantEnum.是;
                                record.IS_EXIST = (int)ISImportantEnum.是;
                                record.IS_NEED = (int)ISImportantEnum.是;
                                record.IS_REQUIRES = (int)ISImportantEnum.是;
                                record.IS_SUITABLE = (int)ISImportantEnum.是;
                                record.IS_OUTSOURCE = true;
                                record.RELATED_ID = tech.RELATED_ID;
                                if (tech.Nav_JobNameOut != null && tech.Nav_JobNameOut.Nav_CrucialLicensePerson != null && tech.Nav_JobNameOut.Nav_CrucialLicensePerson.Any())
                                {
                                    tech.Nav_JobNameOut.Nav_CrucialLicensePerson.ForEach(t =>
                                    {
                                        T_FO_JOB_ACTIVITY_PERSON jobPerson = new T_FO_JOB_ACTIVITY_PERSON();
                                        jobPerson.JOB_ACTIVITY_RECORD_ID = record.ID;
                                        jobPerson.JOB_DOCUMENT = t.CERTIFICATE_NAME;// !string.IsNullOrEmpty(t.JOB_DOCUMENT)?t.JOB_DOCUMENT:t.Nav_Train.CERTIFICATE_NAME;
                                        jobPerson.RELATED_USER_ID = t.USER_ID;
                                        jobPerson.ORG_ID = t.ORG_ID;
                                        apersons.Add(jobPerson);
                                    });
                                }
                                //record.Nav_JobActivityPerson = persons;
                                if (tech.Nav_JobNameOut != null && tech.Nav_JobNameOut.Nav_SafeConfirms != null && tech.Nav_JobNameOut.Nav_SafeConfirms.Any())
                                {
                                    tech.Nav_JobNameOut.Nav_SafeConfirms.ForEach(t =>
                                    {
                                        T_FO_JOB_ACTIVITY_DETAIL detail = new T_FO_JOB_ACTIVITY_DETAIL();
                                        detail.JOB_ACTIVITY_RECORD_ID = record.ID;
                                        detail.SafeConfirmsStr = t.NAME;
                                        detail.IS_CONFIRM = false;
                                        detail.ORG_ID = t.ORG_ID;
                                        detailList.Add(detail);
                                    });
                                }
                                if (tech.Nav_JobNameOut != null && tech.Nav_JobNameOut.Nav_SafeMeasures != null && tech.Nav_JobNameOut.Nav_SafeMeasures.Any())
                                {
                                    tech.Nav_JobNameOut.Nav_SafeMeasures.ForEach(t =>
                                    {
                                        T_FO_JOB_ACTIVITY_FLOW flow = new T_FO_JOB_ACTIVITY_FLOW();
                                        flow.JOB_ACTIVITY_RECORD_ID = record.ID;
                                        flow.SafeMeasuresStr = t.NAME;
                                        flow.IS_CONFIRM = false;
                                        flow.ORG_ID = t.ORG_ID;
                                        flowList.Add(flow);
                                    });
                                }
                                if (tech.Nav_JobNameOut != null && tech.Nav_JobNameOut.Nav_DealMeasures != null && tech.Nav_JobNameOut.Nav_DealMeasures.Any())
                                {
                                    tech.Nav_JobNameOut.Nav_DealMeasures.ForEach(t =>
                                    {
                                        T_FO_JOB_ACTIVITY_MEASURE measure = new T_FO_JOB_ACTIVITY_MEASURE();
                                        measure.JOB_ACTIVITY_RECORD_ID = record.ID;
                                        measure.DealMeasuresStr = t.NAME;
                                        measure.IS_CONFIRM = false;
                                        measure.ORG_ID = t.ORG_ID;
                                        measureList.Add(measure);
                                    });
                                }
                                //record.Nav_Details = detailList;
                                //record.Nav_Flow = flowList;
                                //record.Nav_Measure = measureList;
                                if (tech.Nav_JobNameOut != null && tech.Nav_JobNameOut.MONITOR_USER_ID != null)
                                {
                                    record.CREATER_ID = tech.Nav_JobNameOut.MONITOR_USER_ID;
                                    var userInfo = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && t.ID == tech.Nav_JobNameOut.MONITOR_USER_ID);
                                    //发消息
                                    DateTime dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.JobSite, tech.ORG_ID.Value, DateTime.Now, null, null);
                                    notices.Add(NotificationTaskService.InsertUserNoticeTaskModel("作业活动记录表单(关键/许可作业)-外包", record.ID, record.ORG_ID, userInfo.ID, userInfo.NAME, DateTime.Now,
                                    tech.Nav_JobNameOut.JOB_END_DATE.Value, (int)FMNoticeTypeEnum.消息, "FO021"));
                                }
                            }
                        }
                        else
                        {
                            entity.FORM_STATUS = (int)FOTeamActivityState.签到中;
                            persons.ForEach(t =>
                            {
                                t.RELATED_USER_ID = null;
                                if (t.USER_ID == loginUserId)
                                    t.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                            });
                            var tech = this.GetEntity<T_FO_TECH_DISCLOSURE_FROM>(entity.ID, "Nav_JobName", "Nav_JobName.Nav_CrucialLicensePerson", "Nav_Person", "Nav_JobName.Nav_SafeConfirms", "Nav_JobName.Nav_SafeMeasures", "Nav_JobName.Nav_DealMeasures");
                            //新增的消息通知
                            var userIds = persons.Where(m => m.USER_ID != null && m.USER_ID != loginUserId).Select(t => (Guid)t.USER_ID).Distinct().ToList();
                            if (userIds != null && userIds.Any())
                            {
                                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);
                                }
                                //发消息
                                DateTime dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.JobSite, entity.ORG_ID.Value, DateTime.Now, null, null);
                                notices = NotificationTaskService.InsertUserNoticeTaskModels("安全技术交底表确认(" + tech?.Nav_JobName?.JOB_DATE.Value.ToShortDateString().Replace("/", "") + ")", entity.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                                dtEnd, (int)FMNoticeTypeEnum.消息, "FO019_SHOWPRINT");
                            }
                            else
                            {
                                entity.FORM_STATUS = (int)FOTeamActivityState.已归档;
                                //自动生成作业活动记录表
                                record = new T_FO_JOB_ACTIVITY_RECORD();
                                //取审批流水码
                                var sysFilter = new SystemCodeFilter();
                                sysFilter.CodeType = (int)PFCodeRuleType.关键许可作业活动记录表编号;
                                sysFilter.Count = 1;
                                sysFilter.OrgId = tech.ORG_ID;
                                var codes = CodeRuleService.NewGenSerial(sysFilter);
                                var codeList = codes.Split(new char[] { ',' });
                                record.CODE = codeList[0];
                                record.JOB_NAME_ID = tech.JOB_NAME_ID;
                                record.OPERATION_STEP_ID = tech.OPERATION_STEP_ID;
                                record.TECH_DISCLOSURE_ID = tech.ID;
                                record.JOB_DATE = tech.Nav_JobName?.JOB_DATE ?? DateTime.Now;
                                record.JOB_END_DATE = tech.Nav_JobName?.JOB_END_DATE ?? DateTime.Now;
                                record.ORG_ID = tech.ORG_ID;
                                record.JOB_LOCATION = tech.Nav_JobName?.JOB_LOCATION;
                                record.IS_EFFECTIVE = (int)ISImportantEnum.是;
                                record.IS_EXIST = (int)ISImportantEnum.是;
                                record.IS_NEED = (int)ISImportantEnum.是;
                                record.IS_REQUIRES = (int)ISImportantEnum.是;
                                record.IS_SUITABLE = (int)ISImportantEnum.是;
                                record.IS_OUTSOURCE = false;
                                record.RELATED_ID = null;
                                if (tech.Nav_JobName != null && tech.Nav_JobName.Nav_CrucialLicensePerson != null && tech.Nav_JobName.Nav_CrucialLicensePerson.Any())
                                {
                                    tech.Nav_JobName.Nav_CrucialLicensePerson.ForEach(t =>
                                    {
                                        T_FO_JOB_ACTIVITY_PERSON jobPerson = new T_FO_JOB_ACTIVITY_PERSON();
                                        jobPerson.JOB_ACTIVITY_RECORD_ID = record.ID;
                                        jobPerson.JOB_DOCUMENT = !string.IsNullOrEmpty(t.JOB_DOCUMENT)?t.JOB_DOCUMENT:t.Nav_Train.CERTIFICATE_NAME;
                                        jobPerson.USER_ID = t.USER_ID;
                                        jobPerson.ORG_ID = t.ORG_ID;
                                        apersons.Add(jobPerson);
                                    });
                                }
                                //record.Nav_JobActivityPerson = persons;
                                if (tech.Nav_JobName != null && tech.Nav_JobName.Nav_SafeConfirms != null && tech.Nav_JobName.Nav_SafeConfirms.Any())
                                {
                                    tech.Nav_JobName.Nav_SafeConfirms.ForEach(t =>
                                    {
                                        T_FO_JOB_ACTIVITY_DETAIL detail = new T_FO_JOB_ACTIVITY_DETAIL();
                                        detail.JOB_ACTIVITY_RECORD_ID = record.ID;
                                        detail.SafeConfirmsStr = t.NAME;
                                        detail.IS_CONFIRM = false;
                                        detail.ORG_ID = t.ORG_ID;
                                        detailList.Add(detail);
                                    });
                                }
                                if (tech.Nav_JobName != null && tech.Nav_JobName.Nav_SafeMeasures != null && tech.Nav_JobName.Nav_SafeMeasures.Any())
                                {
                                    tech.Nav_JobName.Nav_SafeMeasures.ForEach(t =>
                                    {
                                        T_FO_JOB_ACTIVITY_FLOW flow = new T_FO_JOB_ACTIVITY_FLOW();
                                        flow.JOB_ACTIVITY_RECORD_ID = record.ID;
                                        flow.SafeMeasuresStr = t.NAME;
                                        flow.IS_CONFIRM = false;
                                        flow.ORG_ID = t.ORG_ID;
                                        flowList.Add(flow);
                                    });
                                }
                                if (tech.Nav_JobName != null && tech.Nav_JobName.Nav_DealMeasures != null && tech.Nav_JobName.Nav_DealMeasures.Any())
                                {
                                    tech.Nav_JobName.Nav_DealMeasures.ForEach(t =>
                                    {
                                        T_FO_JOB_ACTIVITY_MEASURE measure = new T_FO_JOB_ACTIVITY_MEASURE();
                                        measure.JOB_ACTIVITY_RECORD_ID = record.ID;
                                        measure.DealMeasuresStr = t.NAME;
                                        measure.IS_CONFIRM = false;
                                        measure.ORG_ID = t.ORG_ID;
                                        measureList.Add(measure);
                                    });
                                }
                                //record.Nav_Details = detailList;
                                //record.Nav_Flow = flowList;
                                //record.Nav_Measure = measureList;
                                if (tech.Nav_JobName != null && tech.Nav_JobName.MONITOR_USER_ID != null)
                                {
                                    record.CREATER_ID = tech.Nav_JobName.MONITOR_USER_ID;
                                    var userInfo = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && t.ID == tech.Nav_JobName.MONITOR_USER_ID);
                                    //发消息
                                    DateTime dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.JobSite, tech.ORG_ID.Value, DateTime.Now, null, null);
                                    notices.Add(NotificationTaskService.InsertUserNoticeTaskModel("关键/许可作业活动记录表单(" + tech?.Nav_JobName?.JOB_DATE.Value.ToShortDateString().Replace("/", "") + ")", record.ID, record.ORG_ID, userInfo.ID, userInfo.NAME, DateTime.Now,
                                    tech.Nav_JobName.JOB_END_DATE.Value, (int)FMNoticeTypeEnum.消息, "FO021"));
                                }
                            }
                        }
                        //查询消息表
                        //var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                        //task = this.GetEntity<T_FM_NOTIFICATION_TASK>(i => i.SOURCE_DATA_ID == entity.ID && i.USER_ID == userID
                        //&& (i.NOTICE_STATUS == FMNoticeStatusEnum.未处理.GetInt() || i.NOTICE_STATUS == FMNoticeStatusEnum.超期办理.GetInt()), false);
                        //if (task != null)
                        //{
                        //    task.NOTICE_STATUS = FMNoticeStatusEnum.正常已办.GetInt();
                        //    task.TASK_DT = DateTime.Now;
                        //    task.MODIFIER_ID = userID;
                        //}
                        if (entity.TaskID != Guid.Empty)
                        {
                            task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                            task.SOURCE_FORMCODE = "FO019_SHOWPRINT";
                        }
                    }
            
                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);
                    if (persons != null && persons.Any())
                        this.BantchSaveEntityNoCommit(persons);
                    if (notices != null && notices.Any())
                        this.BantchSaveEntityNoCommit(notices);
                    if (task != null)
                        UpdateEntityNoCommit(task);
                    if (record != null)
                        UpdateEntityNoCommit(record);
                    if (apersons != null && apersons.Any())
                        this.BantchSaveEntityNoCommit(apersons);
                    if (detailList != null && detailList.Any())
                        this.BantchSaveEntityNoCommit(detailList);
                    if (flowList != null && flowList.Any())
                        this.BantchSaveEntityNoCommit(flowList);
                    if (measureList != null && measureList.Any())
                        this.BantchSaveEntityNoCommit(measureList);
                    if (deleteIds != null && deleteIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FO_TECH_DISCLOSURE_PERSON>(deleteIds);
                });
                return true;
            });
        }

        /// <summary>
        /// 发布给被交底人签字
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("PublishToIdentify")]
        public JsonActionResult<bool> PublishToIdentify(Guid id)
        {
            return SafeExecute<bool>(() =>
            {
                T_FO_TECH_DISCLOSURE_FROM entity = GetEntity<T_FO_TECH_DISCLOSURE_FROM>(t => t.ID == id);
                List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                entity.FORM_STATUS = (int)FOTeamActivityState.签到中;
                //发布给第一个分析人确认
                if (entity != null && entity.DISCLOSURED_PERSON_ID !=null)
                {
                    var userIds = new List<Guid>();
                    userIds.Add((Guid)entity.DISCLOSURED_PERSON_ID);
                    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("表单【" + entity.CODE + "】技术交底表待签字", entity.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                    DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "FO019_SHOWPRINT");
                }
                UnifiedCommit(() =>
                {
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (notices.Any())
                        this.BantchAddEntityNoCommit(notices);
                });
                return true;
            });
        }
        /// <summary>
        /// 签到同意
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("PersonalAgree")]
        public JsonActionResult<bool> PersonalAgree([FromBody] T_FO_TECH_DISCLOSURE_FROM entity)
        {
            return SafeExecute<bool>(() =>
            {
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var tech = this.GetEntity<T_FO_TECH_DISCLOSURE_FROM>(entity.ID, "Nav_JobName", "Nav_JobName.Nav_CrucialLicensePerson.Nav_Train", "Nav_Person", "Nav_JobName.Nav_SafeConfirms", "Nav_JobName.Nav_SafeMeasures", "Nav_JobName.Nav_DealMeasures");
                var user = this.GetEntity<T_FO_TECH_DISCLOSURE_PERSON>(t => t.TECH_DISCLOSURE_FROM_ID == tech.ID && t.USER_ID == userID, new BaseFilter(orgId));
                user.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                //T_HM_OTHER_APPROVE_LOG log = new T_HM_OTHER_APPROVE_LOG();
                //log.USER_ID = userID;
                //log.MAIN_FORM_ID = tech.ID;
                //log.ORG_ID = tech.ORG_ID;
                //var userCount = tech != null ? tech.Nav_Person.Count() : 0;
                //var userLogCount = this.GetEntities<T_HM_OTHER_APPROVE_LOG>(t => t.MAIN_FORM_ID == tech.ID, new BaseFilter(orgId)).Count();
                List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                T_FO_JOB_ACTIVITY_RECORD record = null;
                List<T_FO_JOB_ACTIVITY_PERSON> persons = new List<T_FO_JOB_ACTIVITY_PERSON>();
                List<T_FO_JOB_ACTIVITY_DETAIL> detailList = new List<T_FO_JOB_ACTIVITY_DETAIL>();
                List<T_FO_JOB_ACTIVITY_FLOW> flowList = new List<T_FO_JOB_ACTIVITY_FLOW>();
                List<T_FO_JOB_ACTIVITY_MEASURE> measureList = new List<T_FO_JOB_ACTIVITY_MEASURE>();
                var todoCount = this.GetCount<T_FO_TECH_DISCLOSURE_PERSON>(t => t.TECH_DISCLOSURE_FROM_ID == tech.ID && t.DEAL_STATUS == 0 && t.USER_ID != null, new BaseFilter(orgId));
                var isExist = this.GetEntity<T_FO_JOB_ACTIVITY_RECORD>(t => t.TECH_DISCLOSURE_ID == tech.ID);
                if (todoCount == 0 || todoCount == 1)
                {
                    tech.FORM_STATUS = (int)FOTeamActivityState.已归档;
                    if (isExist == null)
                    {
                        //自动生成作业活动记录表
                        record = new T_FO_JOB_ACTIVITY_RECORD();
                        //取审批流水码
                        var sysFilter = new SystemCodeFilter();
                        sysFilter.CodeType = (int)PFCodeRuleType.关键许可作业活动记录表编号;
                        sysFilter.Count = 1;
                        sysFilter.OrgId = tech.ORG_ID;
                        var codes = CodeRuleService.NewGenSerial(sysFilter);
                        var codeList = codes.Split(new char[] { ',' });
                        record.CODE = codeList[0];
                        record.OPERATION_STEP_ID = tech.OPERATION_STEP_ID;
                        record.TECH_DISCLOSURE_ID = tech.ID;
                        record.ORG_ID = tech.ORG_ID;
                        record.IS_EFFECTIVE = (int)ISImportantEnum.是;
                        record.IS_EXIST = (int)ISImportantEnum.是;
                        record.IS_NEED = (int)ISImportantEnum.是;
                        record.IS_REQUIRES = (int)ISImportantEnum.是;
                        record.IS_SUITABLE = (int)ISImportantEnum.是;
                        if (tech.JOB_NAME_ID != null)
                        {
                            record.JOB_NAME_ID = tech.JOB_NAME_ID;
                            record.JOB_DATE = tech.Nav_JobName?.JOB_DATE ?? DateTime.Now;
                            record.JOB_END_DATE = tech.Nav_JobName?.JOB_END_DATE ?? DateTime.Now;
                            record.JOB_LOCATION = tech.Nav_JobName?.JOB_LOCATION;
                            record.IS_OUTSOURCE = false;
                            record.RELATED_ID = null;
                            if (tech.Nav_JobName != null && tech.Nav_JobName.Nav_CrucialLicensePerson != null && tech.Nav_JobName.Nav_CrucialLicensePerson.Any())
                            {
                                tech.Nav_JobName.Nav_CrucialLicensePerson.ForEach(t =>
                                {
                                    T_FO_JOB_ACTIVITY_PERSON jobPerson = new T_FO_JOB_ACTIVITY_PERSON();
                                    jobPerson.JOB_ACTIVITY_RECORD_ID = record.ID;
                                    jobPerson.JOB_DOCUMENT = !string.IsNullOrEmpty(t.JOB_DOCUMENT) ? t.JOB_DOCUMENT : t.Nav_Train?.CERTIFICATE_NAME;
                                    jobPerson.USER_ID = t.USER_ID;
                                    jobPerson.ORG_ID = t.ORG_ID;
                                    persons.Add(jobPerson);
                                });
                            }
                            //record.Nav_JobActivityPerson = persons;
                            if (tech.Nav_JobName != null && tech.Nav_JobName.Nav_SafeConfirms != null && tech.Nav_JobName.Nav_SafeConfirms.Any())
                            {
                                tech.Nav_JobName.Nav_SafeConfirms.ForEach(t =>
                                {
                                    T_FO_JOB_ACTIVITY_DETAIL detail = new T_FO_JOB_ACTIVITY_DETAIL();
                                    detail.JOB_ACTIVITY_RECORD_ID = record.ID;
                                    detail.SafeConfirmsStr = t.NAME;
                                    detail.IS_CONFIRM = false;
                                    detail.ORG_ID = t.ORG_ID;
                                    detailList.Add(detail);
                                });
                            }
                            if (tech.Nav_JobName != null && tech.Nav_JobName.Nav_SafeMeasures != null && tech.Nav_JobName.Nav_SafeMeasures.Any())
                            {
                                tech.Nav_JobName.Nav_SafeMeasures.ForEach(t =>
                                {
                                    T_FO_JOB_ACTIVITY_FLOW flow = new T_FO_JOB_ACTIVITY_FLOW();
                                    flow.JOB_ACTIVITY_RECORD_ID = record.ID;
                                    flow.SafeMeasuresStr = t.NAME;
                                    flow.IS_CONFIRM = false;
                                    flow.ORG_ID = t.ORG_ID;
                                    flowList.Add(flow);
                                });
                            }
                            if (tech.Nav_JobName != null && tech.Nav_JobName.Nav_DealMeasures != null && tech.Nav_JobName.Nav_DealMeasures.Any())
                            {
                                tech.Nav_JobName.Nav_DealMeasures.ForEach(t =>
                                {
                                    T_FO_JOB_ACTIVITY_MEASURE measure = new T_FO_JOB_ACTIVITY_MEASURE();
                                    measure.JOB_ACTIVITY_RECORD_ID = record.ID;
                                    measure.DealMeasuresStr = t.NAME;
                                    measure.IS_CONFIRM = false;
                                    measure.ORG_ID = t.ORG_ID;
                                    measureList.Add(measure);
                                });
                            }
                            //record.Nav_Details = detailList;
                            //record.Nav_Flow = flowList;
                            //record.Nav_Measure = measureList;
                            if (tech.Nav_JobName != null && tech.Nav_JobName.MONITOR_USER_ID != null)
                            {
                                record.CREATER_ID = tech.Nav_JobName.MONITOR_USER_ID;
                                var userInfo = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && t.ID == tech.Nav_JobName.MONITOR_USER_ID);
                                //发消息
                                DateTime dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.JobSite, orgId.Value, DateTime.Now, null, null);
                                notices.Add(NotificationTaskService.InsertUserNoticeTaskModel("作业活动记录表单(关键/许可作业)", record.ID, record.ORG_ID, userInfo.ID, userInfo.NAME, DateTime.Now,
                                tech.Nav_JobName.JOB_END_DATE.Value.AddHours(1), (int)FMNoticeTypeEnum.消息, "FO021"));
                            }
                        }
                        else
                        {
                            tech = this.GetEntity<T_FO_TECH_DISCLOSURE_FROM>(entity.ID, "Nav_JobNameOut", "Nav_JobNameOut.Nav_CrucialLicensePerson", "Nav_Person", "Nav_JobNameOut.Nav_SafeConfirms", "Nav_JobNameOut.Nav_SafeMeasures", "Nav_JobNameOut.Nav_DealMeasures");
                            record.JOB_NAME_OUTSOURCE_ID = tech.JOB_NAME_OUTSOURCE_ID;
                            record.JOB_DATE = tech.Nav_JobNameOut?.JOB_DATE ?? DateTime.Now;
                            record.JOB_END_DATE = tech.Nav_JobNameOut?.JOB_END_DATE ?? DateTime.Now;
                            record.JOB_LOCATION = tech.Nav_JobNameOut?.JOB_LOCATION;
                            record.IS_OUTSOURCE = true;
                            record.RELATED_ID = tech.RELATED_ID;
                            if (tech.Nav_JobNameOut != null && tech.Nav_JobNameOut.Nav_CrucialLicensePerson != null && tech.Nav_JobNameOut.Nav_CrucialLicensePerson.Any())
                            {
                                tech.Nav_JobNameOut.Nav_CrucialLicensePerson.ForEach(t =>
                                {
                                    T_FO_JOB_ACTIVITY_PERSON jobPerson = new T_FO_JOB_ACTIVITY_PERSON();
                                    jobPerson.JOB_ACTIVITY_RECORD_ID = record.ID;
                                    jobPerson.JOB_DOCUMENT = t.CERTIFICATE_NAME;
                                    jobPerson.RELATED_USER_ID = t.USER_ID;
                                    jobPerson.ORG_ID = t.ORG_ID;
                                    persons.Add(jobPerson);
                                });
                            }
                            //record.Nav_JobActivityPerson = persons;
                            if (tech.Nav_JobNameOut != null && tech.Nav_JobNameOut.Nav_SafeConfirms != null && tech.Nav_JobNameOut.Nav_SafeConfirms.Any())
                            {
                                tech.Nav_JobNameOut.Nav_SafeConfirms.ForEach(t =>
                                {
                                    T_FO_JOB_ACTIVITY_DETAIL detail = new T_FO_JOB_ACTIVITY_DETAIL();
                                    detail.JOB_ACTIVITY_RECORD_ID = record.ID;
                                    detail.SafeConfirmsStr = t.NAME;
                                    detail.IS_CONFIRM = false;
                                    detail.ORG_ID = t.ORG_ID;
                                    detailList.Add(detail);
                                });
                            }
                            if (tech.Nav_JobNameOut != null && tech.Nav_JobNameOut.Nav_SafeMeasures != null && tech.Nav_JobNameOut.Nav_SafeMeasures.Any())
                            {
                                tech.Nav_JobNameOut.Nav_SafeMeasures.ForEach(t =>
                                {
                                    T_FO_JOB_ACTIVITY_FLOW flow = new T_FO_JOB_ACTIVITY_FLOW();
                                    flow.JOB_ACTIVITY_RECORD_ID = record.ID;
                                    flow.SafeMeasuresStr = t.NAME;
                                    flow.IS_CONFIRM = false;
                                    flow.ORG_ID = t.ORG_ID;
                                    flowList.Add(flow);
                                });
                            }
                            if (tech.Nav_JobNameOut != null && tech.Nav_JobNameOut.Nav_DealMeasures != null && tech.Nav_JobNameOut.Nav_DealMeasures.Any())
                            {
                                tech.Nav_JobNameOut.Nav_DealMeasures.ForEach(t =>
                                {
                                    T_FO_JOB_ACTIVITY_MEASURE measure = new T_FO_JOB_ACTIVITY_MEASURE();
                                    measure.JOB_ACTIVITY_RECORD_ID = record.ID;
                                    measure.DealMeasuresStr = t.NAME;
                                    measure.IS_CONFIRM = false;
                                    measure.ORG_ID = t.ORG_ID;
                                    measureList.Add(measure);
                                });
                            }
                            //record.Nav_Details = detailList;
                            //record.Nav_Flow = flowList;
                            //record.Nav_Measure = measureList;
                            if (tech.Nav_JobNameOut != null && tech.Nav_JobNameOut.MONITOR_USER_ID != null)
                            {
                                record.CREATER_ID = tech.Nav_JobNameOut.MONITOR_USER_ID;
                                var userInfo = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && t.ID == tech.Nav_JobNameOut.MONITOR_USER_ID);
                                //发消息
                                DateTime dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.JobSite, orgId.Value, DateTime.Now, null, null);
                                notices.Add(NotificationTaskService.InsertUserNoticeTaskModel("作业活动记录表单外包(关键/许可作业)", record.ID, record.ORG_ID, userInfo.ID, userInfo.NAME, DateTime.Now,
                                tech.Nav_JobNameOut.JOB_END_DATE.Value.AddHours(1), (int)FMNoticeTypeEnum.消息, "FO021"));
                            }
                        }
                    }
                }
                //查询消息表
                //var task = this.GetEntity<T_FM_NOTIFICATION_TASK>(i => i.SOURCE_DATA_ID == entity.ID && i.USER_ID == userID
                //&& (i.NOTICE_STATUS == FMNoticeStatusEnum.未处理.GetInt() || i.NOTICE_STATUS == FMNoticeStatusEnum.超期办理.GetInt()), false);
                //if (task != null)
                //{
                //    task.NOTICE_STATUS = FMNoticeStatusEnum.正常已办.GetInt();
                //    task.TASK_DT = DateTime.Now;
                //    task.MODIFIER_ID = userID;
                //}
                T_FM_NOTIFICATION_TASK task = null;
                if (entity.TaskID != Guid.Empty)
                {
                    task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                    task.SOURCE_FORMCODE = "FO019_SHOWPRINT";
                }
                this.UnifiedCommit(() =>
                {
                    if (tech != null)
                        UpdateEntityNoCommit(tech);
                    if (user != null)
                        this.UpdateEntityNoCommit(user);
                    //if (log != null)
                    //    this.AddEntityNoCommit(log);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                    if (notices != null && notices.Any())
                        this.BantchSaveEntityNoCommit(notices);
                    if (record != null)
                        UpdateEntityNoCommit(record);
                    if (persons != null && persons.Any())
                        this.BantchSaveEntityNoCommit(persons);
                    if (detailList != null && detailList.Any())
                        this.BantchSaveEntityNoCommit(detailList);
                    if (flowList != null && flowList.Any())
                        this.BantchSaveEntityNoCommit(flowList);
                    if (measureList != null && measureList.Any())
                        this.BantchSaveEntityNoCommit(measureList);
                });
                return true;
            });
        }

        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("FullOrderPaged")]
        public PagedActionResult<T_FO_TECH_DISCLOSURE_FROM> FullOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            var result = new PagedActionResult<T_FO_TECH_DISCLOSURE_FROM>();
            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_TECH_DISCLOSURE_FROM>(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_TECH_DISCLOSURE_FROM>(t => (t.Nav_DisclosurePerson != null && departmentIds.Contains(t.Nav_DisclosurePerson.DEPARTMENT_ID.Value)), pageFilter);//|| dataIds.Contains(t.ID)
                }
                else
                    result.Data = null;
            }
            return result;
        }
    }
}
