using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums.PF;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.AE;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Entities.OH;
using APT.MS.Domain.Entities.PF;
using APT.MS.Domain.Entities.SC;
using APT.MS.Domain.Entities.TI;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace APT.SC.WebApi.Controllers.Api.OH
{
    [Route("api/OH/OHHealthExamPlan")]
    public class OHHealthExamPlanController : AuthorizeApiController<T_OH_HEALTH_EXAM_PLAN>
    {
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IAEAccidentEventReportService AccidentEventReportService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMUserService UserService { get; set; }
        IFMDepartmentService DepartmentService { get; set; }
        public OHHealthExamPlanController(IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService, IAEAccidentEventReportService accidentEventReportService, IFMNotificationTaskService notificationTaskService, IFMUserService userService, IFMDepartmentService departmentService)
        {
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService = approveCallBackService;
            AccidentEventReportService = accidentEventReportService;
            NotificationTaskService = notificationTaskService;
            UserService = userService;
            DepartmentService = departmentService;
        }

        /// <summary>
        /// 体检周期表 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_OH_HEALTH_EXAM_PLAN entity)
        {
            return SafeExecute<bool>(() =>
            {
                //保存并发送的时候 发送给各个部门(负责人 或者安全员)
                //如果有待办 去除待办

                if (string.IsNullOrEmpty(entity.NAME))
                {
                    throw new Exception("请填写体检计划名称");
                }
                if (entity.YEAR == 0)
                {
                    throw new Exception("请填写年度");
                }
                if (entity.STATUS == PFStandardStatus.Sign)
                {
                    if (!entity.DUE_TIME.HasValue)
                    {
                        throw new Exception("请选择上报截止时间");
                    }
                    else
                    {
                        //entity.DUE_TIME = entity.DUE_TIME.Value.Date.AddDays(1).AddSeconds(-1);
                        if (entity.DUE_TIME.Value < DateTime.Now)
                        {
                            throw new Exception("上报截止时间不能小于当前时间");
                        }
                    }
                    //设置结束日期
                    //entity.DUE_TIME = entity.DUE_TIME.Value.Date.AddDays(1).AddSeconds(-1);
                    if (entity.Nav_ListDepartment == null || !entity.Nav_ListDepartment.Any())
                    {
                        throw new Exception("请选择上报部门");
                    }

                    if (entity.CONTENT.Length > 500)
                    {
                        throw new Exception("计划内容不能超过500字");
                    }
                }
                var ListDepartment = entity.Nav_ListDepartment;
                entity.Nav_ListDepartment = null;

                if (entity.STATUS == PFStandardStatus.Draft)
                {
                    foreach (var item in ListDepartment)
                    {
                        item.Nav_Department = null;
                    }
                    //草稿
                    this.UnifiedCommit(() =>
                    {
                        if (entity != null)
                            UpdateEntityNoCommit(entity);   //事故事件上报
                        if (ListDepartment != null && ListDepartment.Any())//职业危害类型
                            BantchSaveEntityNoCommit(ListDepartment);
                    });
                }
                else
                {
                    //给人员发送待办
                    //提交后发送上报部门安全员填写体检员工登记表，职能部门发送给部门负责人，综合部人员中包含公司领导
                    //[ "部门类型")]   DEPARTMENT_STATUS { get; set; }   职能部门 = 0, 生产部门 = 1,   安全部门 = 2,
                    var listDepIDNotice = ListDepartment.Select(e => e.DEPARTMENT_ID);
                    var listDep = GetEntities<T_FM_DEPARTMENT>(e => listDepIDNotice.Contains(e.ID) && e.DEPARTMENT_TYPE == 10 && !e.IS_DELETED && e.ENABLE_STATUS == 0, null, new string[] { "Nav_User" });//部门级别
                    if (listDep == null || !listDep.Any())
                    {
                        throw new Exception("获取部门信息失败！");
                    }

                    List<T_FM_USER> listNoticeUser = new List<T_FM_USER>();//通知人
                    List<string> listDepNoMaster = new List<string>();
                    List<Guid> listDepID = new List<Guid>();//生产部门ID
                    foreach (var item in listDep)
                    {
                        if (!item.USER_ID.HasValue && item.DEPARTMENT_STATUS != 1)//没有部门负责人
                        {
                            listDepNoMaster.Add(item.NAME);
                        }

                        if (item.DEPARTMENT_STATUS == 1)
                        {
                            listDepID.Add(item.ID);
                        }
                        else
                        {
                            //item.Nav_User.Nav_Department = item;
                            listNoticeUser.Add(item.Nav_User);//部门负责人
                        }
                    }
                    if (listDepNoMaster.Count > 0)
                    {
                        throw new Exception(string.Join(",", listDepNoMaster) + "未找到部门负责人！");
                    }
                    if (listDepID.Count < 1)
                    {
                        throw new Exception("请联系管理员配置生产部门！");
                    }
                    var approvalSafe = GetEntity<T_PF_APPROVAL_ROLE>(e => e.NAME == "部门安全员");
                    if (approvalSafe == null)
                    {
                        throw new Exception("请联系管理员配置审批角色【部门安全员】！");
                    }

                    var listSafeUser = GetEntities<T_FM_USER>(e => e.DEPARTMENT_ID.HasValue && listDepID.Contains(e.DEPARTMENT_ID.Value) && e.APPROVE_ROLE_ID.HasValue && approvalSafe.ID == e.APPROVE_ROLE_ID.Value, null, null);
                    if (listSafeUser == null || !listSafeUser.Any())
                    {
                        throw new Exception("请联系管理员配置部门安全员！");
                    }
                    //查找 生产部门安全员
                    List<T_FM_DEPARTMENT> listNoSafe = null;
                    foreach (var item in listDepID)
                    {
                        var SafeEr = listSafeUser.FirstOrDefault(e => e.DEPARTMENT_ID.Value == item);
                        if (SafeEr != null)
                        {
                            //SafeEr.Nav_Department = listDep.FirstOrDefault(e => e.ID == SafeEr.DEPARTMENT_ID);
                            listNoticeUser.Add(SafeEr);
                        }
                        else
                        {
                            if (listNoSafe == null)
                            {
                                listNoSafe = new List<T_FM_DEPARTMENT>();
                            }
                            listNoSafe.Add(listDep.First(e => e.ID == item));
                        }
                    }
                    if (listNoSafe != null && listNoSafe.Count > 0)
                    {
                        throw new Exception("请联系管理员给生产部门" + String.Join("，", listNoSafe.Select(e => e.NAME)) + "设置安全员！");
                    }

                    //bool SendNotificationTask(List<string> names, List<Guid> dataIds, Guid? orgId, List<Guid> userIds, List<string>  userNames, DateTime startTime, DateTime endTime, int noticeType, string formCode, Action action);
                    //List<string> ListName=new List<string>();
                    //List< Guid > ListDataId=new List<Guid>();

                    //NotificationTaskService.SendAndFinishNotificationTask("部门体检计划表", entity.ID, entity.ORG_ID, listNoticeUser.Select(e => e.ID).ToList(), listNoticeUser.Select(e => e.NAME).ToList(), DateTime.Now, DateTime.Now.AddDays(1), 0, "OH005", entity.TaskID, () =>

                    List<string> ListTitleName = new List<string>();
                    List<Guid> ListDataId = new List<Guid>();
                    List<Guid> ListUserId = new List<Guid>();
                    List<string> ListUserName = new List<string>();
                    foreach (var modelDep in ListDepartment)
                    {
                        modelDep.ID = Guid.NewGuid();
                        modelDep.PLAN_ID = entity.ID;
                        //modelDep.DEPARTMENT_ID = item.Nav_Department != null ? item.Nav_Department.ID : item.DEPARTMENT_ID.Value;//上报部门
                        modelDep.ISCONTENTMASTER = false;//上报部门
                        if (modelDep.Nav_Department != null && modelDep.Nav_Department.NAME.Contains("企业管理"))
                        {
                            //包含公司领导
                            modelDep.ISCONTENTMASTER = true;
                        }

                        modelDep.STATUS = PFStandardStatus.Draft;
                        modelDep.ORG_ID = entity.ORG_ID;

                        var user = listNoticeUser.Find(e => e.DEPARTMENT_ID.HasValue && e.DEPARTMENT_ID == modelDep.DEPARTMENT_ID);
                        ListDataId.Add(modelDep.ID);
                        ListUserId.Add(user.ID);
                        modelDep.USER_ID = user.ID;//接收信息的人
                        ListUserName.Add(user.NAME);
                        ListTitleName.Add(modelDep.Nav_Department.NAME + "体检计划表");
                    }

                    foreach (var item in ListDepartment)
                    {
                        item.Nav_Department = null;
                    }

                    NotificationTaskService.SendAndFinishNotificationTask(ListTitleName, ListDataId, entity.ORG_ID, ListUserId, ListUserName, DateTime.Now, DateTime.Now.AddDays(1), 0, "OH005", entity.TaskID, () =>
                    {
                        if (entity != null)
                            UpdateEntityNoCommit(entity);   //体检计划
                        if (ListDepartment != null && ListDepartment.Any())//上报部门
                            BantchSaveEntityNoCommit(ListDepartment);
                    }, "OH004_SHOWPRINT");
                }
                return true;
            });

        }

        //GetDep
        //UpdateDep
        #region     获取部门检查计划信息


        /// <summary>
        /// 体检计划新增选择人
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetCombinPlanRegister")]
        public JsonActionResult<T_OH_HEALTH_EXAM_PLAN_REGISTER> GetCombinPlanRegister([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                if (string.IsNullOrEmpty(filter.Keyword))
                {
                    ThrowError("获取选择人员信息传参失败！");
                }
                if (string.IsNullOrEmpty(filter.Parameter1))
                {
                    ThrowError("获取体检计划信息传参失败！");
                }

                Guid PLAN_ID = new Guid(filter.Parameter1);
                Guid UserID = new Guid(filter.Keyword);
                Guid ID = new Guid(filter.Parameter2);
                Guid? DepartmentID = null;
                if (!string.IsNullOrEmpty(filter.Parameter3))
                {
                    DepartmentID = new Guid(filter.Parameter3);
                }

                T_OH_HEALTH_EXAM_PLAN_REGISTER checkReg = GetEntity<T_OH_HEALTH_EXAM_PLAN_REGISTER>(e => e.PLAN_ID.HasValue && e.PLAN_ID.Value == PLAN_ID && e.USER_ID.HasValue && e.USER_ID.Value == UserID);

                if (checkReg != null && checkReg.ID != Guid.Empty)
                {
                    throw new Exception("该体检计划有此人，添加失败！");
                }

                Guid? DEPARTMENT_ID = null;
                //Guid? DEPARTMENT_ID_WORKSHOP = null;
                T_FM_DEPARTMENT Department = null;
                //T_FM_DEPARTMENT DepartmentWorkshop = null;

                var User = GetEntity<T_FM_USER>(UserID, "Nav_Department", "Nav_Person.Nav_Post");
                //部门=0,  车间=1,   班组=2,   公司=3 
                #region   获取部门信息

                //if (User.Nav_Department.DEPARTMENT_TYPE == 5)
                //{
                //    DEPARTMENT_ID = User.DEPARTMENT_ID.Value;
                //    Department = User.Nav_Department;
                //}
                //else if (User.Nav_Department.DEPARTMENT_TYPE == 20)
                //{
                //    DEPARTMENT_ID_WORKSHOP = User.Nav_Department.PARENT_ID.Value;
                //    DepartmentWorkshop = GetEntity<T_FM_DEPARTMENT>(DEPARTMENT_ID_WORKSHOP.Value, "Nav_Parent");

                //    DEPARTMENT_ID = DepartmentWorkshop.PARENT_ID.Value;
                //    Department = GetEntity<T_FM_DEPARTMENT>(DEPARTMENT_ID.Value);

                //}
                //else if (User.Nav_DepartmentDEPARTMENT_TYPE == 15) 
                //{
                //    DEPARTMENT_ID_WORKSHOP = User.DEPARTMENT_ID.Value;
                //    DEPARTMENT_ID = User.Nav_Department.PARENT_ID.Value;

                //    DepartmentWorkshop = User.Nav_Department;
                //    Department = GetEntity<T_FM_DEPARTMENT>(DEPARTMENT_ID.Value);
                //}
                //else if (User.Nav_Department.DEPARTMENT_TYPE == 10)
                //{
                //    DEPARTMENT_ID = User.DEPARTMENT_ID.Value;
                //    Department = User.Nav_Department;
                //}

                DEPARTMENT_ID = User.DEPARTMENT_ID.Value;
                Department = User.Nav_Department;

                #endregion
                //User.Nav_Person.POST_ID;

                //Guid? SC_POST_ID = null;
                //T_SC_POST_DEPOST modelDpost = null;
                //if (User.Nav_Person.POST_ID.HasValue)
                //{
                //    modelDpost = GetEntity<T_SC_POST_DEPOST>(e => e.DEPOST_ID == User.Nav_Person.POST_ID.Value, "Nav_Post");
                //}

                T_OH_HEALTH_EXAM_PLAN_REGISTER modelCombin = new T_OH_HEALTH_EXAM_PLAN_REGISTER();
                modelCombin.ID = ID;
                modelCombin.PLAN_ID = PLAN_ID;
                modelCombin.USER_ID = UserID;
                modelCombin.Nav_User = User;
                modelCombin.DEPARTMENT_ID = DEPARTMENT_ID;
                modelCombin.Nav_Department = Department;
                //modelCombin.Nav_DepartmentWorkshop = DepartmentWorkshop;
                //modelCombin.DEPARTMENT_ID_WORKSHOP = DEPARTMENT_ID_WORKSHOP;

                //modelCombin.EXAM_CYCLE_ID =;
                modelCombin.TYPE = OHHealthExamType.Post;

                //TODO
                //责任制岗位修改 0511(2)
                //modelCombin.SC_POST_ID = SC_POST_ID;
                //modelCombin.Nav_SCPost = modelDpost?.Nav_Post;
                modelCombin.POST_ID = User.Nav_Person?.POST_ID;
                modelCombin.Nav_Post = User.Nav_Person?.Nav_Post;

                DateTime dt = User.DEPARTURETIME != null ? (DateTime)User.DEPARTURETIME : DateTime.Now;
                modelCombin.WORKYEAR = GetWorkYear(User.ENTRYTIME, dt, DateTime.Now);
                modelCombin.IS_DELETED = false;
                modelCombin.ORG_ID = filter.OrgId;
                //modelCombin.PLAN_ID_DEP = DepartmentID;


                //modelCombin.HEALTH_EXAM_CONTENT =;


                //modelCombin.ENTITY_ORG_TPYE =;
                //modelCombin.FORM_ID =;
                //modelCombin.FLOW_STATUS =;
                //modelCombin.FLOW_SEND_STATUS =;
                //modelCombin.FLOW_ID =;
                //modelCombin.CREATE_TIME =;
                //modelCombin.MODIFY_TIME =;
                //modelCombin.CREATER_ID =;
                //modelCombin.MODIFIER_ID =;

                //判断是否有  职业危害类型 体检项目 等
                ////modelCombin.Nav_ListHazard = null;
                if (modelCombin.POST_ID.HasValue && User.DEPARTMENT_ID.HasValue)
                {
                    var cycleDepPost = GetEntity<T_OH_HEALTH_EXAM_CYCLE_DEPARTMENTINFO_POST>(e => e.POST_ID == modelCombin.POST_ID.Value && !e.IS_DELETED && e.Nav_DepartmentInfo.DEPARTMENT_ID == User.DEPARTMENT_ID.Value && !e.Nav_DepartmentInfo.IS_DELETED && !e.Nav_DepartmentInfo.Nav_ExamCycle.IS_DELETED, "Nav_DepartmentInfo.Nav_ExamCycle");
                    if (cycleDepPost != null && cycleDepPost.ID != Guid.Empty)
                    {
                        var listCycleHazard = GetEntities<T_OH_HEALTH_EAXM_CYCLE_OCC_HAZARD_MID>(e => e.RECORD_ID == cycleDepPost.Nav_DepartmentInfo.EXAM_CYCLE_ID, null, "Nav_Hazard");
                        List<T_OH_HEALTH_EXAM_PLAN_REGISTER_HAZARD> ListHazard = new List<T_OH_HEALTH_EXAM_PLAN_REGISTER_HAZARD>();
                        if (listCycleHazard != null && listCycleHazard.Any())
                        {
                            foreach (var item in listCycleHazard)
                            {
                                ListHazard.Add(new T_OH_HEALTH_EXAM_PLAN_REGISTER_HAZARD()
                                {
                                    ID = Guid.NewGuid(),
                                    ORG_ID = modelCombin.ORG_ID,
                                    REGISTER_ID = modelCombin.ID,
                                    HAZARD_ID = item.HAZARD_ID,
                                    Nav_Hazard = item.Nav_Hazard
                                }); ;
                            }
                            modelCombin.HEALTH_EXAM_CONTENT = cycleDepPost.Nav_DepartmentInfo.Nav_ExamCycle.HEALTH_EXAM_CONTENT;
                            modelCombin.Nav_ExamCycle = cycleDepPost.Nav_DepartmentInfo.Nav_ExamCycle;
                            modelCombin.EXAM_CYCLE_ID = cycleDepPost.Nav_DepartmentInfo.EXAM_CYCLE_ID;
                        }
                        modelCombin.Nav_ListHazard = ListHazard;
                    }
                }
                return modelCombin;
            });
        }

        ///// <summary>
        ///// 体检计划添加体检人员
        ///// </summary>
        ///// <param name="pageFilter"></param>
        ///// <returns></returns>
        //[HttpPost, Route("OrderPagedUseful")]
        //public PagedActionResult<T_FM_USER> OrderPagedUseful([FromBody] KeywordPageFilter pageFilter)
        //{
        //    return SafeGetPagedData(delegate (PagedActionResult<T_FM_USER> result)
        //    {
        //        Guid PLAN_ID = Guid.Empty;
        //        if (pageFilter.FilterGroup.Rules.Count > 0)
        //        {
        //            foreach (var item in pageFilter.FilterGroup.Rules)
        //            {
        //                if (item.Field == "PLAN_ID")
        //                {
        //                    PLAN_ID = new Guid(item.Value.ToString());
        //                }
        //            }
        //            pageFilter.FilterGroup.Rules.Clear();
        //        }
        //        //非 此次体检人员 linq不好筛选
        //        PagedActionResult<T_FM_USER> pageEntities = GetPageEntities<T_FM_USER>(null, pageFilter, null);
        //        result.Data = pageEntities.Data;
        //        result.TotalCount = pageEntities.TotalCount;
        //    });


        //}

        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetDep")]
        public JsonActionResult<T_OH_HEALTH_EAXM_PLAN_DEPARTMENT> GetDep([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                Guid PLAN_ID_DEP = Guid.Empty;
                if (filter.FilterGroup.Rules.Count > 0)
                {
                    foreach (var item in filter.FilterGroup.Rules)
                    {
                        if (item.Field == "ID")
                        {
                            PLAN_ID_DEP = new Guid(item.Value.ToString());
                        }
                    }
                }
                var PlanDep = GetEntity<T_OH_HEALTH_EAXM_PLAN_DEPARTMENT>(e => e.ID == PLAN_ID_DEP, new string[] { "Nav_Plan" });
                if (PlanDep == null)
                {
                    throw new Exception("获取您所在部门体检计划上报信息失败！");
                }
                PlanDep.Nav_Plan.Nav_ListPlanRegister = GetEntities<T_OH_HEALTH_EXAM_PLAN_REGISTER>(e => e.PLAN_ID_DEP == PLAN_ID_DEP && e.PLAN_ID == PlanDep.Nav_Plan.ID, null, null).ToList();

                if (PlanDep.Nav_Plan.Nav_ListPlanRegister == null || !PlanDep.Nav_Plan.Nav_ListPlanRegister.Any())
                {
                    #region    这个部门 这次体检计划 所有的参加人员

                    //部门级 所有 有职业危害 的岗位 成员

                    var listDepPost = GetEntities<T_OH_HEALTH_EXAM_CYCLE_DEPARTMENTINFO>(e => !e.IS_DELETED && !e.Nav_ExamCycle.IS_DELETED, null, "Nav_ExamCycle", "Nav_ListDepartmentInfoPost.Nav_Post");
                    if (listDepPost == null || !listDepPost.Any())
                    {
                        throw new Exception("请设置体检周期表！设置路径：系统管理 => 职业卫生设置 => 体检周期表");
                    }

                    var listCycle = GetEntities<T_OH_HEALTH_EXAM_CYCLE>(e => !e.IS_DELETED, null, "Nav_ListOccHazard.Nav_Hazard");

                    foreach (var item in listDepPost)
                    {
                        item.Nav_ExamCycle = listCycle.FirstOrDefault(e => e.ID == item.EXAM_CYCLE_ID);
                    }
                    listDepPost = listDepPost.Where(e => e.Nav_ExamCycle != null && !e.Nav_ExamCycle.IS_DELETED);

                    #endregion


                    #region    旧方式

                    ////责任制岗位
                    ////var listPost = GetEntities<T_SC_POST>(e => !e.IS_DELETED, null, new string[] { "Nav_Posts" });
                    //var listPostT = GetEntities<T_SC_POST_DEPOST>(e => !e.IS_DELETED, null, new string[] { "Nav_Post" });

                    //if (listPostT == null || !listPostT.Any())
                    //{
                    //    throw new Exception("请联系管理员设置【责任制岗位】");
                    //}
                    //List<T_SC_POST_DEPOST> listPost = listPostT.ToList();
                    //List<Guid> listPostID = listPost.Select(e => e.DEPOST_ID).ToList();

                    ////TODO
                    ////责任制岗位修改 0511
                    //List<T_OH_HEALTH_EAXM_CYCLE_POST_MID> listSCPostCycleT = new List<T_OH_HEALTH_EAXM_CYCLE_POST_MID>();
                    ////var listSCPostCycleT = GetEntities<T_OH_HEALTH_EAXM_CYCLE_POST_MID>(e => !e.IS_DELETED && e.Nav_Record.DEPARTMENT_ID.HasValue && e.Nav_Record.DEPARTMENT_ID.Value == PlanDep.DEPARTMENT_ID, null, new string[] { "Nav_Record.Nav_ListOccHazard.Nav_Hazard", "Nav_SCPost" });


                    //if (listSCPostCycleT == null || !listSCPostCycleT.Any())
                    //{
                    //    throw new Exception("请联系管理员设置您所在部门的【体检周期表】");
                    //}

                    //List<T_OH_HEALTH_EAXM_CYCLE_POST_MID> listSCPostCycle = listSCPostCycleT.ToList();

                    ////var listExamT = GetEntities<T_OH_HEALTH_EXAM_CYCLE>(e => e.DEPARTMENT_ID.HasValue && e.DEPARTMENT_ID == PlanDep.DEPARTMENT_ID, null, new string[] { "Nav_ListSCPost", "Nav_ListOccHazard.Nav_Hazard" });

                    ////if (listExamT == null || !listExamT.Any())
                    ////{
                    ////    throw new Exception("请联系管理员设置您所在部门的【体检周期表】");
                    ////}
                    ////List<T_OH_HEALTH_EXAM_CYCLE> listExam = listExamT.ToList(); 
                    #endregion

                    //加载人员
                    List<T_FM_USER> listUser = new List<T_FM_USER>();
                    if (PlanDep.ISCONTENTMASTER)
                    {
                        var listrUserCom = GetEntities<T_FM_USER>(e => e.ENABLE_STATUS == 0 && !e.IS_DELETED && e.CODE != "admin" && e.DEPARTMENT_ID.HasValue && e.Nav_Department.DEPARTMENT_TYPE == 5 && e.PERSON_ID.HasValue && e.Nav_Person.POST_ID.HasValue, null, new string[] { "Nav_Person.Nav_Post", "Nav_Department" }).OrderByDescending(e => e.APPROVE_ROLE_ID);//&& listPostID.Contains(e.Nav_Person.POST_ID.Value)
                        if (listrUserCom != null && listrUserCom.Any())
                        {
                            listUser.AddRange(listrUserCom);
                        }
                    }

                    //部门
                    var listrUserDep = GetEntities<T_FM_USER>(e => e.ENABLE_STATUS == 0 && !e.IS_DELETED && e.DEPARTMENT_ID.HasValue && e.DEPARTMENT_ID == PlanDep.DEPARTMENT_ID && e.PERSON_ID.HasValue && e.Nav_Person.POST_ID.HasValue, null, new string[] { "Nav_Person.Nav_Post", "Nav_Department" }).OrderByDescending(e => e.APPROVE_ROLE_ID); //&& listPostID.Contains(e.Nav_Person.POST_ID.Value)

                    if (listrUserDep != null && listrUserDep.Any())
                    {
                        listUser.AddRange(listrUserDep);
                    }

                    //车间
                    var listrUserWork = GetEntities<T_FM_USER>(e => e.ENABLE_STATUS == 0 && !e.IS_DELETED && e.DEPARTMENT_ID.HasValue && e.Nav_Department.PARENT_ID.HasValue && e.Nav_Department.PARENT_ID == PlanDep.DEPARTMENT_ID && e.PERSON_ID.HasValue && e.Nav_Person.POST_ID.HasValue, null, new string[] { "Nav_Person.Nav_Post", "Nav_Department.Nav_Parent" }).OrderByDescending(e => e.APPROVE_ROLE_ID);//&& listPostID.Contains(e.Nav_Person.POST_ID.Value)
                    if (listrUserWork != null && listrUserWork.Any())
                    {
                        listUser.AddRange(listrUserWork);
                    }

                    //班组
                    var listrUserClass = GetEntities<T_FM_USER>(e => e.ENABLE_STATUS == 0 && !e.IS_DELETED && e.DEPARTMENT_ID.HasValue && e.Nav_Department.PARENT_ID.HasValue && e.Nav_Department.Nav_Parent.PARENT_ID == PlanDep.DEPARTMENT_ID && e.PERSON_ID.HasValue && e.Nav_Person.POST_ID.HasValue, null, new string[] { "Nav_Person.Nav_Post", "Nav_Department.Nav_Parent.Nav_Parent" }).OrderByDescending(e => e.APPROVE_ROLE_ID);//&& listPostID.Contains(e.Nav_Person.POST_ID.Value)
                    if (listrUserClass != null && listrUserClass.Any())
                    {
                        listUser.AddRange(listrUserClass);
                    }

                    DateTime dtNow = DateTime.Now;
                    Guid LoginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;
                    var ListPlanRegister = new List<T_OH_HEALTH_EXAM_PLAN_REGISTER>();
                    T_SC_POST_DEPOST UserDePost = null;
                    List<T_SC_POST_DEPOST> ListUserDePost = null;
                    List<T_OH_HEALTH_EXAM_PLAN_REGISTER_HAZARD> Nav_ListHazard = null;
                    List<T_OH_HEALTH_EAXM_CYCLE_POST_MID> listSCPostCycleCheck = null;
                    List<T_OH_HEALTH_EXAM_CYCLE_DEPARTMENTINFO> listDepInfoCheck = null;
                    foreach (var item in listUser)
                    {
                        listDepInfoCheck = listDepPost.Where(e => e.DEPARTMENT_ID.HasValue && e.DEPARTMENT_ID == item.DEPARTMENT_ID && e.Nav_ListDepartmentInfoPost != null && e.Nav_ListDepartmentInfoPost.FirstOrDefault(ec => ec.POST_ID == item.Nav_Person.POST_ID) != null).ToList();
                        if (listDepInfoCheck == null || !listDepInfoCheck.Any())
                        {
                            //没找到对应职位的职业危害设置 这个人不需要体检
                            continue;
                        }

                        T_OH_HEALTH_EXAM_PLAN_REGISTER model = new T_OH_HEALTH_EXAM_PLAN_REGISTER();
                        model.ID = Guid.NewGuid();
                        model.PLAN_ID = PlanDep.PLAN_ID;
                        model.Nav_Plan = PlanDep.Nav_Plan;

                        model.USER_ID = item.ID;
                        model.Nav_User = item;

                        //获取 部门 车间
                        #region     获取部门人员信息 旧

                        //if (item.Nav_Department.DEPARTMENT_TYPE == 5 || item.Nav_Department.DEPARTMENT_TYPE == 10)
                        //{
                        //    //   公司 = 3  部门 = 0,
                        //    model.DEPARTMENT_ID = item.DEPARTMENT_ID;
                        //    model.DEPARTMENT_ID_WORKSHOP = null;

                        //    model.Nav_Department = item.Nav_Department;
                        //}
                        //else if (item.Nav_DepartmentDEPARTMENT_TYPE == 15) 
                        //{
                        //    //    车间 = 1,
                        //    model.DEPARTMENT_ID = item.Nav_Department.PARENT_ID;
                        //    model.DEPARTMENT_ID_WORKSHOP = item.DEPARTMENT_ID;

                        //    model.Nav_Department = item.Nav_Department.Nav_Parent;
                        //    model.Nav_DepartmentWorkshop = item.Nav_Department;
                        //}
                        //else
                        //{
                        //    //    班组 = 2,
                        //    model.DEPARTMENT_ID = item.Nav_Department.Nav_Parent.PARENT_ID;
                        //    model.DEPARTMENT_ID_WORKSHOP = item.Nav_Department.PARENT_ID;

                        //    model.Nav_Department = item.Nav_Department.Nav_Parent.Nav_Parent;
                        //    model.Nav_DepartmentWorkshop = item.Nav_Department.Nav_Parent;
                        //} 
                        #endregion

                        #region       获取部门人员信息

                        model.DEPARTMENT_ID = item.DEPARTMENT_ID;
                        model.Nav_Department = item.Nav_Department;

                        #endregion

                        ////如果匹配到多个  责任制岗位
                        //ListUserDePost = listPost.FindAll(e => e.DEPOST_ID == item.Nav_Person.POST_ID.Value);
                        //if (ListUserDePost == null || ListUserDePost.Count < 1)
                        //{
                        //    continue;
                        //}


                        //var listSCPostID = ListUserDePost.Select(e => e.POST_ID);
                        //listSCPostCycleCheck = listSCPostCycle.FindAll(e => listSCPostID.Contains(e.SC_POST_ID));
                        //if (listSCPostCycleCheck == null)
                        //{
                        //    continue;
                        //}

                        foreach (var itemCycle in listDepInfoCheck)
                        {
                            //TODO
                            //责任制岗位修改 0511

                            //model.SC_POST_ID = item.Nav_Person.POST_ID;// itemCycle.Nav_SCPost.ID;
                            //model.Nav_SCPost = item.Nav_Person.Nav_Post;// itemCycle.Nav_SCPost;

                            model.EXAM_CYCLE_ID = itemCycle.Nav_ExamCycle.ID;
                            model.Nav_ExamCycle = itemCycle.Nav_ExamCycle;
                            break;
                        }

                        //foreach (var itemCycle in listSCPostCycleCheck)
                        //{
                        //    //TODO
                        //    //责任制岗位修改 0511
                        //    //如果 体检周期 和
                        //    if (itemCycle.Nav_Record.DEPARTMENT_ID == model.DEPARTMENT_ID)
                        //    {
                        //        if (itemCycle.Nav_Record.DEPARTMENT_ID_WORKSHOP == null || itemCycle.Nav_Record.DEPARTMENT_ID_WORKSHOP == model.DEPARTMENT_ID_WORKSHOP)
                        //        {
                        //            model.SC_POST_ID = itemCycle.Nav_SCPost.ID;
                        //            model.Nav_SCPost = itemCycle.Nav_SCPost;

                        //            model.EXAM_CYCLE_ID = itemCycle.Nav_Record.ID;
                        //            model.Nav_ExamCycle = itemCycle.Nav_Record;

                        //            break;
                        //        }
                        //    }
                        //}

                        ////责任制岗位
                        //UserDePost = listPost.FirstOrDefault(e => e.DEPOST_ID == item.Nav_Person.POST_ID.Value);
                        //if (UserDePost == null)
                        //{
                        //    continue;
                        //}
                        //model.SC_POST_ID = UserDePost.POST_ID;
                        //model.Nav_SCPost = UserDePost.Nav_Post;

                        ////获取体检周期信息（根据 部门 车间 责任制岗位）
                        ////model.EXAM_CYCLE_ID = "";
                        //foreach (var itemExam in listExam)
                        //{
                        //    foreach (var itemPost in itemExam.Nav_ListSCPost)
                        //    {
                        //        if (itemPost.SC_POST_ID == model.SC_POST_ID)
                        //        {
                        //            model.EXAM_CYCLE_ID = itemExam.ID;
                        //            model.Nav_ExamCycle = itemExam;
                        //            break;
                        //        }
                        //    }
                        //    if (model.EXAM_CYCLE_ID != null && model.EXAM_CYCLE_ID != Guid.Empty)
                        //    {
                        //        break;
                        //    }
                        //}

                        if (model.EXAM_CYCLE_ID == null || model.EXAM_CYCLE_ID == Guid.Empty)
                        {
                            continue;
                        }
                        DateTime dt = item.DEPARTURETIME != null ? (DateTime)item.DEPARTURETIME : DateTime.Now;
                        model.WORKYEAR = GetWorkYear(item.ENTRYTIME, dt, dtNow);
                        model.TYPE = OHHealthExamType.Post;
                        model.IS_DELETED = false;
                        model.ORG_ID = PlanDep.ORG_ID;
                        //model.ENTITY_ORG_TPYE = "";
                        //model.FORM_ID = "";
                        //model.FLOW_STATUS = "";
                        //model.FLOW_SEND_STATUS = "";
                        //model.FLOW_ID = "";
                        model.CREATE_TIME = dtNow;
                        model.MODIFY_TIME = dtNow;
                        model.CREATER_ID = LoginID;
                        model.MODIFIER_ID = LoginID;
                        model.PLAN_ID_DEP = PlanDep.ID;
                        model.Nav_PlanDEP = PlanDep;
                        //item.Nav_Person.POST_ID

                        model.HEALTH_EXAM_CONTENT = model.Nav_ExamCycle.HEALTH_EXAM_CONTENT;
                        Nav_ListHazard = new List<T_OH_HEALTH_EXAM_PLAN_REGISTER_HAZARD>();
                        foreach (var itemHaz in model.Nav_ExamCycle.Nav_ListOccHazard)
                        {
                            Nav_ListHazard.Add(new T_OH_HEALTH_EXAM_PLAN_REGISTER_HAZARD()
                            {
                                REGISTER_ID = model.ID,
                                HAZARD_ID = itemHaz.HAZARD_ID,
                                Nav_Hazard = itemHaz.Nav_Hazard,
                                ORG_ID = itemHaz.ORG_ID,
                                ID = Guid.NewGuid(),
                                IS_DELETED = false,
                            });
                        }
                        model.Nav_ListHazard = Nav_ListHazard;
                        ListPlanRegister.Add(model);
                    }

                    PlanDep.Nav_Plan.Nav_ListPlanRegister = ListPlanRegister;
                    PlanDep.Nav_Plan.Nav_ListDepartment = GetEntities<T_OH_HEALTH_EAXM_PLAN_DEPARTMENT>(e => e.PLAN_ID == PlanDep.PLAN_ID, null, new string[] { "Nav_Department" }).ToList();

                }
                return PlanDep;
            });
        }

        /// <summary>
        /// 获取工龄(按365天 按小时算)
        /// </summary>
        /// <param name="ENTRYTIME"></param>
        /// <param name="DEPARTURETIME"></param>
        /// <param name="dtNow"></param>
        private int GetWorkYear(DateTime ENTRYTIME, DateTime DEPARTURETIME, DateTime dtNow)
        {
            int WorkYear = 0;
            if (ENTRYTIME == DateTime.MinValue || (ENTRYTIME.Year == dtNow.Year))
            {
                return 0;
            }
            else if (DEPARTURETIME == DateTime.MinValue)
            {
                WorkYear = (int)((dtNow - ENTRYTIME).TotalHours / 8760);// 365*24=8760.0
                //WorkYear = dtNow.Year - ENTRYTIME.Year + (dtNow.Month > ENTRYTIME.Month ? 1 : 0);
            }
            else
            {
                //WorkYear = DEPARTURETIME.Year - ENTRYTIME.Year + (DEPARTURETIME.Month > ENTRYTIME.Month ? 1 : 0);
                WorkYear = (int)((DEPARTURETIME - ENTRYTIME).TotalHours / 8760);// 365*24=8760.0
            }
            return WorkYear;
        }

        /// <summary>
        /// 更新或新增数据
        /// </summary>
        /// <param name="entity">对象实体</param>
        /// <returns></returns>
        [HttpPost, Route("UpdateDep")]
        public JsonActionResult<bool> UpdateDep([FromBody] T_OH_HEALTH_EAXM_PLAN_DEPARTMENT entity)
        {
            return SafeExecute(() =>
            {
                //UpdateEntity(entity);
                //如果是保存并发送 
                //如果全部都 提交了  各部门填写完成后汇总到企管部人事专员，可增删人员，给企管部负责人审批
                //写一个 跑批  如果 报名截止（超过1天） 还有人没有提交  自动提交 到 人事专员

                var ListPlanRegister = entity.Nav_Plan.Nav_ListPlanRegister;
                entity.Nav_Plan.Nav_ListPlanRegister = null;
                entity.Nav_Plan = null;
                List<T_OH_HEALTH_EXAM_PLAN_REGISTER_HAZARD> ListRegHazard = new List<T_OH_HEALTH_EXAM_PLAN_REGISTER_HAZARD>();
                foreach (var item in ListPlanRegister)
                {
                    if (item.Nav_ListHazard != null && item.Nav_ListHazard.Any())
                    {
                        ListRegHazard.AddRange(item.Nav_ListHazard);
                        item.Nav_ListHazard = null;
                    }
                }

                if (entity.STATUS == PFStandardStatus.Draft)
                {
                    this.UnifiedCommit(() =>
                    {
                        if (entity != null)
                            UpdateEntityNoCommit(entity);   //部门体检计划
                        if (ListPlanRegister != null && ListPlanRegister.Any())//体检人员
                            BantchSaveEntityNoCommit(ListPlanRegister);
                        if (ListRegHazard != null && ListRegHazard.Any())//体检职业危害
                            BantchSaveEntityNoCommit(ListRegHazard);
                    });
                }
                else if (entity.STATUS == PFStandardStatus.Archived)
                {
                    List<int> listRowIndex = new List<int>();
                    int rowIndex = 1;
                    T_OH_HEALTH_EAXM_PLAN_DEPARTMENT PlanDep = null;
                    foreach (var item in ListPlanRegister)
                    {
                        if (string.IsNullOrEmpty(item.HEALTH_EXAM_CONTENT))
                        {
                            listRowIndex.Add(rowIndex);
                        }
                        rowIndex++;

                        if (!item.PLAN_ID_DEP.HasValue)
                        {
                            if (PlanDep == null)
                            {
                                PlanDep = GetEntity<T_OH_HEALTH_EAXM_PLAN_DEPARTMENT>(e => e.PLAN_ID == item.PLAN_ID && e.DEPARTMENT_ID == APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID && !e.IS_DELETED);
                            }
                            if (PlanDep != null)
                            {
                                item.PLAN_ID_DEP = PlanDep.ID;
                            }
                        }
                    }
                    if (listRowIndex.Count > 0)
                    {
                        throw new Exception("体检项目不能为空：行：" + string.Join(",", listRowIndex) + "！");
                    }

                    bool isDepEnd = false;
                    #region    判断是否 转入 人事专员

                    //保存并发送 需要发送
                    var plan = GetEntity<T_OH_HEALTH_EXAM_PLAN>(entity.PLAN_ID);
                    List<T_FM_NOTIFICATION_TASK> listTaskEnd = null;

                    if (plan.DUE_TIME.HasValue && DateTime.Now > plan.DUE_TIME.Value.AddDays(1))//人性化往后一天
                    {
                        isDepEnd = true;

                        #region      

                        var listNotArchived = GetEntities<T_OH_HEALTH_EAXM_PLAN_DEPARTMENT>(e => !e.IS_DELETED && e.ID != entity.ID && e.PLAN_ID == entity.PLAN_ID && e.STATUS != PFStandardStatus.Archived, null, null);
                        if (listNotArchived != null && listNotArchived.Any())
                        {
                            var listDataID = listNotArchived.Select(e => e.ID).ToList();
                            listTaskEnd = GetEntities<T_FM_NOTIFICATION_TASK>(e => e.SOURCE_FORMCODE == "OH005" && e.SOURCE_DATA_ID.HasValue && listDataID.Contains(e.SOURCE_DATA_ID.Value), null, null).ToList();
                            if (listTaskEnd != null && listTaskEnd.Any())
                            {
                                foreach (var item in listTaskEnd)
                                {
                                    item.TASK_DT = DateTime.Now;
                                    item.NOTICE_STATUS = 4;// FMNoticeStatusEnum.超时无需办理;
                                    item.SOURCE_FORMCODE = "OH005_SHOWPRINT";
                                }
                            }
                        }

                        #endregion

                    }
                    if (!isDepEnd)
                    {
                        var listNotArchived = GetEntities<T_OH_HEALTH_EAXM_PLAN_DEPARTMENT>(e => !e.IS_DELETED && e.ID != entity.ID && e.PLAN_ID == entity.PLAN_ID && e.STATUS != PFStandardStatus.Archived, null, null);
                        if (listNotArchived == null || !listNotArchived.Any() || listNotArchived.Count() < 1)
                        {
                            isDepEnd = true;
                        }
                    }

                    #endregion

                    if (!isDepEnd)
                    {
                        var taskEnd = NotificationTaskService.GetEntityTask(entity.TaskID, "OH005_SHOWPRINT");
                        this.UnifiedCommit(() =>
                        {
                            if (entity != null)
                                UpdateEntityNoCommit(entity);   //部门体检计划
                            if (taskEnd != null)
                                UpdateEntityNoCommit(taskEnd);   //结束待办
                            //UpdateEntityNoCommit(plan);//体检计划状态修改
                            if (ListPlanRegister != null && ListPlanRegister.Any())//体检人员
                                BantchSaveEntityNoCommit(ListPlanRegister);
                            if (ListRegHazard != null && ListRegHazard.Any())//体检职业危害
                                BantchSaveEntityNoCommit(ListRegHazard);
                        });
                    }
                    else
                    {
                        //给人事专员
                        #region  获取人事专员

                        string Msg = string.Empty;
                        var UserRS = UserService.GetPostUser(ref Msg, "人事专员");
                        if (UserRS == null)
                        {
                            if (string.IsNullOrEmpty(Msg))
                            {
                                throw new Exception("未获取到人事专员！");
                            }
                            else
                            {
                                throw new Exception(Msg);
                            }
                        }
                        #endregion

                        //plan.STATUS = PFStandardStatus.Sign;

                        NotificationTaskService.SendAndFinishNotificationTask("部门体检计划汇总", entity.PLAN_ID, entity.ORG_ID, UserRS.ID, UserRS.NAME, DateTime.Now, DateTime.Now.AddDays(1), (int)FMNoticeTypeEnum.消息, "OH006", entity.TaskID, () =>
                            {
                                if (entity != null)
                                    UpdateEntityNoCommit(entity);   //部门体检计划
                                //UpdateEntityNoCommit(plan);//体检计划状态修改
                                if (ListPlanRegister != null && ListPlanRegister.Any())//体检人员
                                    BantchSaveEntityNoCommit(ListPlanRegister);
                                if (ListRegHazard != null && ListRegHazard.Any())//体检职业危害
                                    BantchSaveEntityNoCommit(ListRegHazard);

                                if (listTaskEnd != null && listTaskEnd.Any())//代办未处理的 超时不办理
                                    BantchSaveEntityNoCommit(listTaskEnd);
                            }, "OH005_SHOWPRINT");
                    }
                }
                return true;
            });
        }


        /// <summary>
        /// 部门负责人（安全员） 选择 职业危害  获取信息
        /// 暂时不用
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetExamCycleByIdentifying")]
        public JsonActionResult<T_OH_HEALTH_EXAM_CYCLE> GetExamCycleByIdentifying([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeExecute<T_OH_HEALTH_EXAM_CYCLE>(() =>
            {
                //根据 职业危害类型  车间  部门 适配 体检周期 显示 体检项目

                T_OH_HEALTH_EXAM_CYCLE result = new T_OH_HEALTH_EXAM_CYCLE();
                Guid HazardID = Guid.Empty;

                var listMin = GetEntities<T_OH_HEALTH_EAXM_CYCLE_OCC_HAZARD_MID>(e => e.HAZARD_ID == HazardID, null, null);

                var listcycle = GetEntities<T_OH_HEALTH_EXAM_CYCLE>(e => e.Nav_ListOccHazard.FirstOrDefault(e => e.Nav_Hazard.ID == HazardID) != null, null, null);


                return result;
            });
        }

        #endregion


        #region      人事专员编辑


        /// <summary>
        /// 获得单条实体数据 OH006
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetOH006")]
        public JsonActionResult<T_OH_HEALTH_EXAM_PLAN> GetOH006([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                Guid PlanID = Guid.Empty;
                if (filter.FilterGroup.Rules.Count > 0)
                {
                    foreach (var item in filter.FilterGroup.Rules)
                    {
                        if (item.Field == "ID")
                        {
                            PlanID = new Guid(item.Value.ToString());
                        }
                    }
                    if (filter.FilterGroup.Rules.Count == 1)
                    {
                        filter.FilterGroup.Rules.Clear();
                    }
                }

                T_OH_HEALTH_EXAM_PLAN Plan = null;
                if (PlanID != Guid.Empty)
                {
                    Plan = GetEntity<T_OH_HEALTH_EXAM_PLAN>(e => e.ID == PlanID);
                    if (Plan != null)
                    {
                        //上报部门
                        Plan.Nav_ListDepartment = GetEntities<T_OH_HEALTH_EAXM_PLAN_DEPARTMENT>(e => e.PLAN_ID == PlanID, null, new string[] { "Nav_Department" }).ToList();
                        //体检员工登记表
                        //Plan.Nav_ListPlanRegister = GetEntities<T_OH_HEALTH_EXAM_PLAN_REGISTER>(e => e.PLAN_ID == PlanID, null, new string[] { "Nav_User", "Nav_Department", "Nav_DepartmentWorkshop", "Nav_ExamCycle", "Nav_SCPost", "Nav_ListHazard.Nav_Hazard" }).ToList();
                        Plan.Nav_ListPlanRegister = GetEntities<T_OH_HEALTH_EXAM_PLAN_REGISTER>(e => e.PLAN_ID == PlanID, null, new string[] { "Nav_User.Nav_Person.Nav_Post", "Nav_Department", "Nav_DepartmentWorkshop", "Nav_ExamCycle", "Nav_ListHazard.Nav_Hazard" }).ToList();

                        if (Plan.Nav_ListPlanRegister != null && Plan.Nav_ListPlanRegister.Any())
                        {
                            //体检周期（职业危害类型）
                            var listCycle = Plan.Nav_ListPlanRegister.Select(e => e.EXAM_CYCLE_ID);
                            if (listCycle != null && listCycle.Any())
                            {
                                List<Guid?> listDisCycleID = listCycle.Distinct().ToList();
                                var listModelCycle = GetEntities<T_OH_HEALTH_EXAM_CYCLE>(e => listDisCycleID.Contains(e.ID), null, new string[] { "Nav_ListOccHazard.Nav_Hazard" });
                                if (listModelCycle != null && listModelCycle.Any())
                                {
                                    foreach (var item in Plan.Nav_ListPlanRegister)
                                    {
                                        if (item.EXAM_CYCLE_ID.HasValue)
                                        {
                                            item.Nav_ExamCycle = listModelCycle.FirstOrDefault(e => e.ID == item.EXAM_CYCLE_ID);
                                        }
                                        item.Nav_ListHazard = item.Nav_ListHazard.OrderBy(e => e.HAZARD_ID).ToList();//职业危害排序
                                    }
                                }
                            }
                            //排序
                            Plan.Nav_ListPlanRegister = Plan.Nav_ListPlanRegister.OrderBy(e => e.DEPARTMENT_ID).ThenBy(e => e.DEPARTMENT_ID_WORKSHOP).ToList();
                        }
                    }
                }
                return Plan;
            });
        }


        /// <summary>
        /// 人事专员汇总
        /// </summary>
        /// <param name="entity">对象实体</param>
        /// <returns></returns>
        [HttpPost, Route("UpdateSum")]
        public JsonActionResult<bool> UpdateSum([FromBody] T_OH_HEALTH_EXAM_PLAN entity)
        {
            return SafeExecute(() =>
            {
                //保存并发送  发送给 人事部负责人
                var ListPlanRegister = entity.Nav_ListPlanRegister;
                entity.Nav_ListPlanRegister = null;

                List<T_OH_HEALTH_EXAM_PLAN_REGISTER_HAZARD> ListRegHazard = new List<T_OH_HEALTH_EXAM_PLAN_REGISTER_HAZARD>();
                foreach (var item in ListPlanRegister)
                {
                    if (item.Nav_ListHazard != null && item.Nav_ListHazard.Any())
                    {
                        ListRegHazard.AddRange(item.Nav_ListHazard);
                        item.Nav_ListHazard = null;
                    }
                }

                if (entity.STATUS == PFStandardStatus.Sign)
                {
                    //保存
                    this.UnifiedCommit(() =>
                    {
                        if (entity != null)
                            UpdateEntityNoCommit(entity);   //部门体检计划
                        if (ListPlanRegister != null && ListPlanRegister.Any())//体检人员
                            BantchSaveEntityNoCommit(ListPlanRegister);
                        if (ListRegHazard != null && ListRegHazard.Any())//体检人员
                            BantchSaveEntityNoCommit(ListRegHazard);
                    });
                }
                else if (entity.STATUS == PFStandardStatus.Approving)
                {
                    //保存并发送

                    List<int> listRowIndex = new List<int>();
                    int rowIndex = 1;
                    T_OH_HEALTH_EAXM_PLAN_DEPARTMENT PlanDep = null;
                    List<T_OH_HEALTH_EAXM_PLAN_DEPARTMENT> listDep = new List<T_OH_HEALTH_EAXM_PLAN_DEPARTMENT>();

                    foreach (var item in ListPlanRegister)
                    {
                        if (string.IsNullOrEmpty(item.HEALTH_EXAM_CONTENT))
                        {
                            listRowIndex.Add(rowIndex);
                        }
                        rowIndex++;

                        if (!item.PLAN_ID_DEP.HasValue)
                        {
                            if (listDep.Count < 1)
                            {
                                listDep = GetEntities<T_OH_HEALTH_EAXM_PLAN_DEPARTMENT>(e => e.PLAN_ID == item.PLAN_ID && !e.IS_DELETED, null, null).ToList();
                            }

                            PlanDep = listDep.FirstOrDefault(e => e.DEPARTMENT_ID == item.DEPARTMENT_ID);

                            if (PlanDep == null)
                            {
                                PlanDep = listDep.FirstOrDefault(e => e.ISCONTENTMASTER);
                            }
                            if (PlanDep != null)
                            {
                                item.PLAN_ID_DEP = PlanDep.ID;
                            }
                            else if (listDep.Count > 0)
                            {
                                item.PLAN_ID_DEP = listDep[0].ID;
                            }
                        }
                    }
                    if (listRowIndex.Count > 0)
                    {
                        throw new Exception("体检项目不能为空：行：" + string.Join(",", listRowIndex) + "！");
                    }


                    //给综合部负责人
                    #region  获取综合部负责人
                    T_FM_USER userMaster = null;
                    //人事专员 所在部门的负责人
                    var Depart = GetEntity<T_FM_DEPARTMENT>(e => e.ID == APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID, new string[] { "Nav_User" });
                    if (Depart.Nav_User != null)
                    {
                        userMaster = Depart.Nav_User;
                    }
                    else if (userMaster == null)
                    {
                        //throw new Exception("未获取到" + RSDepName + "负责人！");
                        string RSDepName = "企业管理部";
                        var dep = DepartmentService.GetRSDep(RSDepName, new string[] { "Nav_User" });

                        if (dep == null || !dep.USER_ID.HasValue)
                        {
                            throw new Exception("未获取到" + RSDepName + "！");
                        }
                        else// if (dep.USER_ID.HasValue)
                        {
                            userMaster = dep.Nav_User;
                        }
                    }


                    #endregion


                    ////人事部负责人审批待办
                    //NotificationTaskService.SendAndFinishNotificationTask("部门体检计划汇总审批", entity.ID, entity.ORG_ID, userMaster.ID, userMaster.NAME, DateTime.Now, DateTime.Now.AddDays(1), (int)FMNoticeTypeEnum.消息, "OH006_SHOWPRINT", entity.TaskID, () =>
                    //{
                    //    if (entity != null)
                    //        UpdateEntityNoCommit(entity);   //部门体检计划
                    //    if (ListPlanRegister != null && ListPlanRegister.Any())//体检人员
                    //        BantchSaveEntityNoCommit(ListPlanRegister);
                    //}, "OH006_SHOWPRINT");

                    Dictionary<int, T_FM_USER> dicApproveUser = new Dictionary<int, T_FM_USER>();
                    dicApproveUser.Add(1, userMaster);

                    //人事部负责人审批待办
                    entity.APPROVE_ID = Guid.NewGuid();
                    MFlowPermitService.InsertApprove("TJ" + DateTime.Now.ToString("yyyyMMddHHmmss"), "OH006", null, entity.ID, "OH006_SHOWPRINT", entity.TaskID, true, () =>
                     {
                         if (entity != null)
                             UpdateEntityNoCommit(entity);   //部门体检计划
                         if (ListPlanRegister != null && ListPlanRegister.Any())//体检人员
                             BantchSaveEntityNoCommit(ListPlanRegister);
                         if (ListRegHazard != null && ListRegHazard.Any())//体检人员
                             BantchSaveEntityNoCommit(ListRegHazard);
                     }, entity.APPROVE_ID, userMaster.ID, dicApproveUser, null, null, "OH006_SHOWPRINT");
                }
                return true;
            });
        }



        /// <summary>
        /// 职业危害类型(有设置体检周期 OH006)
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedIdentifying")]
        public PagedActionResult<T_OH_HEALTH_EAXM_CYCLE_OCC_HAZARD_MID> OrderPagedIdentifying([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_OH_HEALTH_EAXM_CYCLE_OCC_HAZARD_MID> result)
            {
                PagedActionResult<T_OH_HEALTH_EAXM_CYCLE_OCC_HAZARD_MID> orderPageEntities = GetOrderPageEntities<T_OH_HEALTH_EAXM_CYCLE_OCC_HAZARD_MID>(null, pageFilter, null);
                result.Data = orderPageEntities.Data;
                result.TotalCount = orderPageEntities.TotalCount;
            });
        }


        /// <summary>
        /// 人事部负责人审批回调
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("PlanMasterBack")]
        public JsonActionResult<bool> PlanMasterBack(string id)
        {
            return SafeExecute<bool>(() =>
            {
                return ApproveCallBackService.CallBack("OH/OHHealthExamPlan/PlanMasterBack", id);
            });
        }


        #endregion
    }
}