using APT.BaseData.Domain.ApiModel;
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.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Linq.Expressions;

namespace APT.SC.WebApi.Controllers.Api.OH
{
    [Route("api/OH/OHHealthExamResult")]
    public class OHHealthExamResultController : AuthorizeApiController<T_OH_HEALTH_EXAM_RESULT>
    {
        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 readonly int beforeMonth = -3;//提前月数
        public readonly int afterDays = 1;//推迟天数
        public OHHealthExamResultController(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="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedBatch")]
        public PagedActionResult<T_OH_HEALTH_EXAM_BATCH> OrderPagedBatch([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_OH_HEALTH_EXAM_BATCH> result)
            {
                DateTime dtNow = DateTime.Now.Date.AddDays(afterDays);
                DateTime dtMin = dtNow.AddMonths(beforeMonth);
                PagedActionResult<T_OH_HEALTH_EXAM_BATCH> orderPageEntities = GetOrderPageEntities<T_OH_HEALTH_EXAM_BATCH>(e => dtMin < e.START_TIME && e.END_TIME <= dtNow, pageFilter, null);
                result.Data = orderPageEntities.Data.OrderByDescending(e => e.END_TIME);
                result.TotalCount = orderPageEntities.TotalCount;
            });

        }

        /// <summary>
        /// 排序分页查询数据 体检批次的人员
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedBatchUser")]
        public PagedActionResult<T_OH_HEALTH_EXAM_NOTICE_REGISTER> OrderPagedBatchUser([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_OH_HEALTH_EXAM_NOTICE_REGISTER> result)
            {
                Guid EXAM_BATCH_ID = Guid.Empty;
                if (pageFilter.FilterGroup.Rules.Count > 0)
                {
                    foreach (var item in pageFilter.FilterGroup.Rules)
                    {
                        if (item.Field == "EXAM_BATCH_ID")
                        {
                            EXAM_BATCH_ID = new Guid(item.Value.ToString());
                            pageFilter.FilterGroup.Rules.Remove(item);
                            break;
                        }
                    }
                }

                if (EXAM_BATCH_ID != Guid.Empty)
                {
                    Expression<Func<T_OH_HEALTH_EXAM_NOTICE_REGISTER, bool>> expression = e => e.USER_ID.HasValue && e.EXAM_BATCH_ID == EXAM_BATCH_ID;
                    pageFilter.Sort = null;
                    PagedActionResult<T_OH_HEALTH_EXAM_NOTICE_REGISTER> orderPageEntities = GetOrderPageEntities<T_OH_HEALTH_EXAM_NOTICE_REGISTER>(expression, pageFilter, null);
                    result.Data = orderPageEntities.Data;
                    result.TotalCount = orderPageEntities.TotalCount;
                }
                else
                {
                    result.Data = new List<T_OH_HEALTH_EXAM_NOTICE_REGISTER>();
                    result.TotalCount = 0;
                }
            });
        }


        ///// <summary>
        ///// 排序分页查询数据 体检批次的人员
        ///// </summary>
        ///// <param name="pageFilter">分页过滤实体</param>
        ///// <returns></returns>
        //[HttpPost, Route("OrderPagedBatchUser")]
        //public PagedActionResult<T_FM_USER> OrderPagedBatchUser([FromBody] KeywordPageFilter pageFilter)
        //{
        //    return SafeGetPagedData(delegate (PagedActionResult<T_FM_USER> result)
        //    {
        //        Guid EXAM_BATCH_ID = Guid.Empty;
        //        if (pageFilter.FilterGroup.Rules.Count > 0)
        //        {
        //            foreach (var item in pageFilter.FilterGroup.Rules)
        //            {
        //                if (item.Field == "EXAM_BATCH_ID")
        //                {
        //                    EXAM_BATCH_ID = new Guid(item.Value.ToString());
        //                    pageFilter.FilterGroup.Rules.Remove(item);
        //                    break;
        //                }
        //            }
        //        }
        //        if (EXAM_BATCH_ID != Guid.Empty)
        //        {
        //            Expression<Func<T_OH_HEALTH_EXAM_NOTICE_REGISTER, bool>> expression = e => e.USER_ID.HasValue && e.EXAM_BATCH_ID == EXAM_BATCH_ID;
        //            PagedActionResult<T_OH_HEALTH_EXAM_NOTICE_REGISTER> orderPageEntities = GetOrderPageEntities<T_OH_HEALTH_EXAM_NOTICE_REGISTER>(expression, pageFilter, null);
        //            result.Data = orderPageEntities.Data.Select(e => e.Nav_User).OrderBy(e => e.NAME).ToList();
        //            result.TotalCount = orderPageEntities.TotalCount;
        //        }
        //        else
        //        {
        //            result.Data = new List<T_FM_USER>();
        //            result.TotalCount = 0;
        //        }
        //    });
        //}



        /// <summary>
        /// 体检周期表 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_OH_HEALTH_EXAM_RESULT entity)
        {
            return SafeExecute<bool>(() =>
            {
                //保存并发送的时候 发送给各个部门(负责人 或者安全员)
                //如果有待办 去除待办
                if (!entity.NOTICE_REGISTER_ID.HasValue)
                {
                    throw new Exception("请选择体检批次对应体检人员");
                }

                var check = GetEntity<T_OH_HEALTH_EXAM_RESULT>(e => e.ID != entity.ID && e.NOTICE_REGISTER_ID == entity.NOTICE_REGISTER_ID);

                if (check != null)
                {
                    throw new Exception("该体检批次体检人意见录入体检结果！");
                }

                if (entity.STATUS == OHHealthExamResultStatus.Finish)
                {
                    if (entity.RESULT_ENUM == OHHealthExamResult.NotSign)
                    {
                        throw new Exception("请选择体检结论！");
                    }
                    if (string.IsNullOrEmpty(entity.DESCRIPTION))
                    {
                        throw new Exception("请填写结果描述！");
                    }
                    else if (entity.DESCRIPTION.Length > 500)
                    {
                        throw new Exception("结果描述不能超过500字！");
                    }
                }

                var listOccDisease = entity.Nav_OccDiseaseList;
                entity.Nav_OccDiseaseList = null;
                List<T_OH_HEALTH_EXAM_RESULT_OCC_DISEASE_FILE> listFiles = new List<T_OH_HEALTH_EXAM_RESULT_OCC_DISEASE_FILE>();

                if (listOccDisease != null && listOccDisease.Any())
                {
                    foreach (var item in listOccDisease)
                    {
                        if (item.Nav_Files != null && item.Nav_Files.Any())
                        {
                            listFiles.AddRange(item.Nav_Files);
                            item.Nav_Files = null;
                        }
                    }
                }

                if (entity.RESULT_ENUM != OHHealthExamResult.Disease)
                {
                    //非职业病 没有职业病信息
                    //直接清理
                    if (listOccDisease != null && listOccDisease.Any())
                    {
                        listOccDisease.Clear();
                        listFiles.Clear();
                    }
                }

                if (entity.STATUS == OHHealthExamResultStatus.WaitSign)
                {
                    //草稿
                    this.UnifiedCommit(() =>
                    {
                        if (entity != null)
                            UpdateEntityNoCommit(entity);   //体检结果
                        if (listOccDisease != null && listOccDisease.Any())
                            BantchSaveEntityNoCommit(listOccDisease);//职业病
                        if (listFiles != null && listFiles.Any())
                            BantchSaveEntityNoCommit(listFiles);//附件
                    });
                }
                else
                {
                    //如果数据库中 已经是 待写入职业病信息 或者 已完成 状态  不需要发送 调岗 或者会议通知
                    bool isNotice = true;
                    if (entity.RESULT_ENUM == OHHealthExamResult.Disease)
                    {
                        var resultCheck = GetEntity<T_OH_HEALTH_EXAM_RESULT>(entity.ID);
                        if (resultCheck != null && (resultCheck.STATUS == OHHealthExamResultStatus.WaitSignDisease || resultCheck.STATUS == OHHealthExamResultStatus.Finish))
                        {
                            //如果是导入数据 保存、保存并发送  
                            //导入的时候已经发送了 调岗信息 不需要再次通知
                            isNotice = false;
                        }
                    }

                    if (entity.RESULT_ENUM == OHHealthExamResult.Disease && (listOccDisease == null || !listOccDisease.Any()))
                    {
                        throw new Exception("请填写职业病信息后再保存！");
                    }
                    //OHHealthExamResultStatus.WaitSignDisease 也会进来
                    if (entity.STATUS == OHHealthExamResultStatus.Finish)
                    {
                        int rowIndex = 1;
                        foreach (var item in listOccDisease)
                        {
                            if (!item.OCC_DISEASE_ID.HasValue)
                            {
                                throw new Exception("请选择行：" + rowIndex + "的职业病");
                            }
                            if (!item.OCC_DISEASE_SEVERITY_ID.HasValue)
                            {
                                throw new Exception("请选择行：" + rowIndex + "的职业病严重程度");
                            }
                            if (string.IsNullOrEmpty(item.DESCRIPTION))
                            {
                                throw new Exception("请选择行：" + rowIndex + "的病状描述");
                            }
                            rowIndex++;
                        }
                    }

                    //5、体检结论结果为职业病触发今日提醒给安环部负责人；消息类型为：召开会议；消息内容为：请召开职业危害防治措施的有效性评估会
                    //6、体检结论结果为职业病同时触发今日提醒给体检结论结果为职业病的员工的上级部门负责人；消息类型为：其他；消息内容为：请给“员工姓名”调岗。

                    //上级部门负责人，例如： 班组人员 =》 班长 班长 =》车间级负责人

                    T_FM_NOTIFICATION_TASK taskUserMaster = null;
                    T_FM_NOTIFICATION_TASK taskSafe = null;
                    T_FM_NOTIFICATION_TASK taskEnd = null;
                    if (entity.TaskID != Guid.Empty)
                    {
                        taskEnd = NotificationTaskService.GetEntityTask(entity.TaskID, "OH012_SHOWPRINT");
                    }

                    #region      职业病 今日提醒

                    if (entity.RESULT_ENUM == OHHealthExamResult.Disease && isNotice)
                    {
                        T_FM_USER userMaster = null;//上级负责人
                        //职业病
                        var user = GetEntity<T_FM_USER>(e => e.ID == entity.USER_ID, new string[] { "Nav_ApproveRole", "Nav_Department.Nav_User" });
                        if (user.Nav_ApproveRole == null || !user.Nav_ApproveRole.NAME.Contains("负责人"))
                        {
                            userMaster = user.Nav_Department.Nav_User;
                        }
                        else
                        {
                            //上一级部门的负责人
                            if (user.Nav_Department.PARENT_ID.HasValue)
                            {
                                T_FM_DEPARTMENT dep = GetEntity<T_FM_DEPARTMENT>(e => e.ID == user.Nav_Department.PARENT_ID, new string[] { "Nav_User" });
                                userMaster = dep.Nav_User;
                            }
                            else
                            {
                                //没有上级部门

                            }
                        }
                        if (userMaster != null)
                        {
                            T_FM_USER userResult = GetEntity<T_FM_USER>(entity.USER_ID.Value);
                            taskUserMaster = NotificationTaskService.InsertUserNoticeTaskModel("请给【" + userResult.NAME + "】调岗", Guid.Empty, entity.ORG_ID, userMaster.ID, userMaster.NAME, DateTime.Now, DateTime.Now.AddDays(1), (int)FMNoticeTypeEnum.今日提醒, "");
                        }
                        string Msg = string.Empty;

                        T_FM_USER userSafe = UserService.GetRoleUser(ref Msg, "安环部负责人", null, null);
                        if (userSafe == null || string.IsNullOrEmpty(userSafe.NAME))
                        {
                            if (!string.IsNullOrEmpty(Msg))
                            {
                                throw new Exception(Msg);
                            }
                            else
                            {
                                throw new Exception("获取安环部负责人失败");
                            }
                        }
                        else
                        {
                            taskSafe = NotificationTaskService.InsertUserNoticeTaskModel("请召开职业危害防治措施的有效性评估会", Guid.Empty, entity.ORG_ID, userSafe.ID, userSafe.NAME, DateTime.Now, DateTime.Now.AddDays(1), (int)FMNoticeTypeEnum.今日提醒, "");
                        }
                    }

                    #endregion

                    this.UnifiedCommit(() =>
                    {
                        if (entity != null)
                            UpdateEntityNoCommit(entity);   //体检结果
                        if (listOccDisease != null && listOccDisease.Any())
                            BantchSaveEntityNoCommit(listOccDisease);//职业病
                        if (listFiles != null && listFiles.Any())
                            BantchSaveEntityNoCommit(listFiles);//附件
                        if (taskUserMaster != null)
                            UpdateEntityNoCommit(taskUserMaster);   //上级领导 调岗
                        if (taskSafe != null)
                            UpdateEntityNoCommit(taskSafe);   //安环部 召开会议
                        if (taskEnd != null)
                            UpdateEntityNoCommit(taskEnd);   //结束待办
                    });
                }
                return true;
            });

        }


        /// <summary>
        /// 知识库 超级管理员修改体检结果
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdateResult")]
        public JsonActionResult<bool> FullUpdateResult([FromBody] T_OH_HEALTH_EXAM_RESULT entity)
        {
            return SafeExecute<bool>(() =>
            {
                if (APT.Infrastructure.Api.AppContext.CurrentSession.UserName != "admin")
                {
                    throw new Exception("只有超级管理员才能修改此体检结果");
                }

                //保存并发送的时候 发送给各个部门(负责人 或者安全员)
                //如果有待办 去除待办
                if (!entity.NOTICE_REGISTER_ID.HasValue)
                {
                    throw new Exception("请选择体检批次对应体检人员");
                }

                if (entity.RESULT_ENUM == OHHealthExamResult.NotSign)
                {
                    throw new Exception("请选择体检结论！");
                }
                if (string.IsNullOrEmpty(entity.DESCRIPTION))
                {
                    throw new Exception("请填写结果描述！");
                }
                else if (entity.DESCRIPTION.Length > 500)
                {
                    throw new Exception("结果描述不能超过500字！");
                }


                var listOccDisease = entity.Nav_OccDiseaseList;
                entity.Nav_OccDiseaseList = null;
                List<T_OH_HEALTH_EXAM_RESULT_OCC_DISEASE_FILE> listFiles = new List<T_OH_HEALTH_EXAM_RESULT_OCC_DISEASE_FILE>();

                if (entity.RESULT_ENUM == OHHealthExamResult.Disease && (listOccDisease == null || !listOccDisease.Any()))
                {
                    throw new Exception("请填写职业病信息后再保存！");
                }

                if (listOccDisease != null && listOccDisease.Any())
                {
                    foreach (var item in listOccDisease)
                    {
                        if (entity.RESULT_ENUM != OHHealthExamResult.Disease)
                        {
                            item.IS_DELETED = true;
                        }

                        if (item.Nav_Files != null && item.Nav_Files.Any())
                        {
                            listFiles.AddRange(item.Nav_Files);
                            item.Nav_Files = null;
                        }
                    }
                }
                if (entity.RESULT_ENUM != OHHealthExamResult.Disease)
                {
                    foreach (var item in listFiles)
                    {
                        item.IS_DELETED = true;
                    }
                }


                int rowIndex = 1;
                foreach (var item in listOccDisease)
                {
                    if (item.IS_DELETED)
                    {
                        continue;
                    }
                    if (!item.OCC_DISEASE_ID.HasValue)
                    {
                        throw new Exception("请选择行：" + rowIndex + "的职业病");
                    }
                    if (!item.OCC_DISEASE_SEVERITY_ID.HasValue)
                    {
                        throw new Exception("请选择行：" + rowIndex + "的职业病严重程度");
                    }
                    if (string.IsNullOrEmpty(item.DESCRIPTION))
                    {
                        throw new Exception("请选择行：" + rowIndex + "的病状描述");
                    }
                    rowIndex++;
                }

                //草稿
                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);   //体检结果
                    if (listOccDisease != null && listOccDisease.Any())
                        BantchSaveEntityNoCommit(listOccDisease);//职业病
                    if (listFiles != null && listFiles.Any())
                        BantchSaveEntityNoCommit(listFiles);//附件
                });

                return true;
            });

        }

        [HttpPost, Route("ImportShow2")]
        public PagedActionResult<T_OH_HEALTH_EXAM_RESULT> ImportShow2()
        {
            return null;
        }

        /// <summary>
        /// 获取导入的初始数据
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpPost, Route("GetImportIni")]
        public JsonActionResult<T_OH_HEALTH_EXAM_RESULT_IMPORT> GetImportIni([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                Guid ID = Guid.Empty;
                if (filter.FilterGroup.Rules.Count > 0)
                {
                    foreach (var item in filter.FilterGroup.Rules)
                    {
                        if (item.Field == "ID")
                        {
                            ID = new Guid(item.Value.ToString());
                        }
                    }
                    filter.FilterGroup.Rules.Clear();
                }
                if (ID == Guid.Empty)
                {
                    throw new Exception("获取信息失败！");
                }
                List<T_OH_HEALTH_EXAM_NOTICE> listNotice = new List<T_OH_HEALTH_EXAM_NOTICE>();
                T_OH_HEALTH_EXAM_RESULT_IMPORT result = GetImports(ID, ref listNotice);

                #region   方法提取


                //T_OH_HEALTH_EXAM_RESULT_IMPORT result = GetEntity<T_OH_HEALTH_EXAM_RESULT_IMPORT>(e => e.ID == ID, new string[] { "Nav_ExamNotice" });

                //Guid? PARENTID = result.Nav_ExamNotice.PARENTID;
                //var listNotice = GetEntities<T_OH_HEALTH_EXAM_NOTICE>(e => e.PARENTID == PARENTID, null, null);
                //List<Guid> listNoticeID = listNotice.Select(e => e.ID).ToList();
                //var listNoticeRegist = GetEntities<T_OH_HEALTH_EXAM_NOTICE_REGISTER>(e => listNoticeID.Contains(e.NOTICE_ID.Value), null, new string[] { "Nav_User", "Nav_ExamBatch" }); //e.NOTICE_ID == result.NOTICE_ID

                //List<T_OH_HEALTH_EXAM_RESULT> listResult = new List<T_OH_HEALTH_EXAM_RESULT>();
                //if (listNoticeRegist != null && listNoticeRegist.Any())
                //{
                //    foreach (var item in listNoticeRegist)
                //    {
                //        listResult.Add(new T_OH_HEALTH_EXAM_RESULT()
                //        {
                //            ID = Guid.NewGuid(),
                //            NOTICE_REGISTER_ID = item.ID,
                //            Nav_NoticeRegister = item,
                //            USER_ID = item.USER_ID,
                //            Nav_User = item.Nav_User,
                //            RESULT_ENUM = OHHealthExamResult.NotSign,
                //            DESCRIPTION = "",
                //            SUGGESTION = "",
                //            STATUS = OHHealthExamResultStatus.WaitSign,
                //            IS_DELETED = false,
                //            ORG_ID = item.ORG_ID,
                //            //ENTITY_ORG_TPYE
                //            //FORM_ID
                //            //FLOW_STATUS
                //            //FLOW_SEND_STATUS
                //            //FLOW_ID
                //            //CREATE_TIME
                //            //MODIFY_TIME
                //            //CREATER_ID
                //            //MODIFIER_ID

                //        });
                //    }
                //}
                //result.Nav_ListResult = listResult;

                #endregion
                return result;
            });
        }

        /// <summary>
        /// 获取导入数据
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="listNotice"></param>
        /// <returns></returns>
        public T_OH_HEALTH_EXAM_RESULT_IMPORT GetImports(Guid ID, ref List<T_OH_HEALTH_EXAM_NOTICE> listNotice)
        {
            T_OH_HEALTH_EXAM_RESULT_IMPORT result = GetEntity<T_OH_HEALTH_EXAM_RESULT_IMPORT>(e => e.ID == ID, new string[] { "Nav_ExamNotice" });

            Guid? PARENTID = result.Nav_ExamNotice.PARENTID;
            listNotice = GetEntities<T_OH_HEALTH_EXAM_NOTICE>(e => e.PARENTID == PARENTID, null, null).ToList();
            List<Guid> listNoticeID = listNotice.Select(e => e.ID).ToList();
            var listNoticeRegist = GetEntities<T_OH_HEALTH_EXAM_NOTICE_REGISTER>(e => listNoticeID.Contains(e.NOTICE_ID.Value) && e.STATUS != OHHealthExamNoticeRegisterStatus.NoticeResult, null, new string[] { "Nav_User", "Nav_ExamBatch" }); //e.NOTICE_ID == result.NOTICE_ID

            List<T_OH_HEALTH_EXAM_RESULT> listResult = new List<T_OH_HEALTH_EXAM_RESULT>();
            if (listNoticeRegist != null && listNoticeRegist.Any())
            {
                foreach (var item in listNoticeRegist)
                {
                    listResult.Add(new T_OH_HEALTH_EXAM_RESULT()
                    {
                        ID = Guid.NewGuid(),
                        NOTICE_REGISTER_ID = item.ID,
                        Nav_NoticeRegister = item,
                        USER_ID = item.USER_ID,
                        Nav_User = item.Nav_User,
                        RESULT_ENUM = OHHealthExamResult.NotSign,
                        DESCRIPTION = "",
                        SUGGESTION = "",
                        STATUS = OHHealthExamResultStatus.WaitSign,
                        IS_DELETED = false,
                        ORG_ID = item.ORG_ID,
                        //ENTITY_ORG_TPYE
                        //FORM_ID
                        //FLOW_STATUS
                        //FLOW_SEND_STATUS
                        //FLOW_ID
                        //CREATE_TIME
                        //MODIFY_TIME
                        //CREATER_ID
                        //MODIFIER_ID

                    });
                }
            }

            result.Nav_ListResult = listResult;
            return result;
        }
        /// <summary>
        /// 显示批量导入数据 
        /// </summary>
        /// <param name="filer"></param>
        /// <returns></returns>
        [HttpPost, Route("ImportShow")]
        public PagedActionResult<T_OH_HEALTH_EXAM_RESULT> ImportShow(IFormCollection filer)
        {
            StringValues taskID = string.Empty;
            StringValues id = string.Empty;
            filer.TryGetValue("TaskID", out taskID);
            try
            {
                filer.TryGetValue("id", out id);
                if (string.IsNullOrEmpty(id.ToString()))
                {
                    throw new Exception("获取传参失败！");
                }
            }
            catch
            {
                throw new Exception("获取传参失败！");
                throw;
            }

            return SafeGetPagedData(delegate (PagedActionResult<T_OH_HEALTH_EXAM_RESULT> result)
            {
                var httpRequest = this.HttpContext.Request;
                string orgIdStr = httpRequest.Form["OrgId"];// 获取 组织            
                Guid? orgId = null;
                result.IsSuccessful = true;
                if (!string.IsNullOrEmpty(orgIdStr))
                {
                    orgId = new Guid(orgIdStr);

                    var dic = Path.Combine(System.AppContext.BaseDirectory, "tempImportFiles");
                    if (!Directory.Exists(dic))
                        Directory.CreateDirectory(dic);
                    foreach (var key in httpRequest.Form.Files)  // 文件键
                    {
                        var postedFile = key;    // 获取文件键对应的文件对象
                        string filePath = Path.Combine(dic, DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss") + "_" + postedFile.FileName);
                        Byte[] fileData = new Byte[postedFile.Length];
                        Stream sr = postedFile.OpenReadStream();//创建数据流对象 
                        sr.Read(fileData, 0, (int)postedFile.Length);
                        using (FileStream fs = new FileStream(filePath, FileMode.CreateNew))
                        {
                            fs.Write(fileData, 0, fileData.Length);
                            fs.Flush();
                            fs.Close();
                        }

                        //获取数据
                        Dictionary<int, int> startRowIndexs = new Dictionary<int, int>();
                        startRowIndexs.Add(0, 2);//根据Excel格式数据赋值
                        var dataTables = FileUtils.ReadExcelByOledb(filePath, startRowIndexs);

                        //bool isOK = InsertModel(dataTables.Tables[0], orgId.Value, ref Msg);
                        //try
                        //{
                        //    System.IO.File.Delete(filePath);
                        //}
                        //catch { }


                        #region      提取数据

                        DataTable dtInfo = dataTables.Tables[0];

                        int rowCount = dtInfo.Rows.Count;
                        int colunCount = dtInfo.Columns.Count;
                        if (rowCount < 1)
                        {
                            result.ErrorMessage = "获取导入数据失败！";
                            result.IsSuccessful = false;
                            //return result;
                        }
                        else if (colunCount != 6)
                        {
                            result.ErrorMessage = "获取导入数据异常！";
                            result.IsSuccessful = false;
                        }
                        else
                        {
                            //体检批次 体检人员    身份证号 体检结论    结果描述 处理意见
                            //T_OH_HEALTH_EXAM_NOTICE_REGISTER
                            Dictionary<int, List<int>> listEmptyInfo = new Dictionary<int, List<int>>();
                            Dictionary<int, string> dicErrorRowResult = new Dictionary<int, string>();
                            List<int> listEmptyRowColum = null;

                            List<string> listName = new List<string>();//姓名
                            List<string> listBatch = new List<string>();
                            string strBatch = string.Empty;

                            List<string> listExamResult = new List<string>();
                            OHHealthExamResult[] HealthResult = Enum.GetValues<OHHealthExamResult>();

                            foreach (var item in HealthResult)
                            {
                                listExamResult.Add(item.GetDescription());
                            }


                            for (int i = 0; i < rowCount; i++)
                            {
                                #region    不能为空
                                listEmptyRowColum = null;
                                for (int j = 0; j < 4; j++)
                                {
                                    if (j != 2)
                                    {
                                        if (dtInfo.Rows[i][j] == null || string.IsNullOrEmpty(dtInfo.Rows[i][j].ToString()))
                                        {
                                            if (listEmptyRowColum == null)
                                            {
                                                listEmptyRowColum = new List<int>();
                                            }
                                            listEmptyRowColum.Add(j);
                                        }
                                        else if (j == 3)
                                        {
                                            if (!listExamResult.Contains(dtInfo.Rows[i][j].ToString().Trim()))
                                            {
                                                dicErrorRowResult.Add(i, dtInfo.Rows[i][j].ToString().Trim());
                                            }
                                        }
                                    }


                                    if (listEmptyInfo.Count == 0)
                                    {
                                        //姓名
                                        listName.Add(dtInfo.Rows[i][1].ToString().Trim());

                                        //批次
                                        strBatch = dtInfo.Rows[i][0].ToString().Trim();
                                        if (!listBatch.Contains(strBatch))
                                        {
                                            listBatch.Add(dtInfo.Rows[i][0].ToString().Trim());
                                        }
                                    }
                                }
                                //数据不能为空 
                                if (listEmptyRowColum != null)
                                {
                                    listEmptyInfo.Add(i, listEmptyRowColum);
                                }
                                #endregion
                            }

                            if (listEmptyInfo.Count > 0 || dicErrorRowResult.Count > 0)
                            {
                                string Msg = string.Empty;
                                if (listEmptyInfo.Count > 0)
                                {
                                    foreach (var item in listEmptyInfo)
                                    {
                                        Msg += (Msg.Length == 0 ? "" : "；") + "行：" + item.Key + " 列【" + string.Join(',', item.Value) + "】";
                                    }
                                    Msg += "信息不能为空！";
                                }
                                if (dicErrorRowResult.Count > 0)
                                {
                                    string errorResult = "体检结论有误,";
                                    foreach (var item in dicErrorRowResult)
                                    {
                                        errorResult += "行：" + item.Key + " 【" + item.Value + "】";
                                    }
                                    errorResult += "！";
                                    Msg += (Msg.Length > 0 ? "\r\n" : "") + errorResult;
                                }

                                result.ErrorMessage = Msg;
                                result.IsSuccessful = false;
                                //return result;
                            }
                            else
                            {
                                Guid ID = new Guid(id);
                                T_OH_HEALTH_EXAM_RESULT_IMPORT resultImport = GetEntity<T_OH_HEALTH_EXAM_RESULT_IMPORT>(e => e.ID == ID, new string[] { "Nav_ExamNotice" });
                                Guid? PARENTID = resultImport.Nav_ExamNotice.PARENTID;
                                List<T_OH_HEALTH_EXAM_NOTICE> listNotice = GetEntities<T_OH_HEALTH_EXAM_NOTICE>(e => e.PARENTID == PARENTID, null, null).ToList();
                                var listBatchId = listNotice.Where(e => e.EXAM_BATCH_ID.HasValue).Select(e => e.EXAM_BATCH_ID.Value);

                                //3个月之前结束 到 2天后结束
                                //DateTime dtMin = DateTime.Now.AddMonths(beforeMonth);
                                //DateTime dtMax = DateTime.Now.AddDays(afterDays);

                                ////姓名
                                //List<T_FM_USER> listModelUser = GetEntities<T_FM_USER>(e => listName.Contains(e.NAME), null, null).ToList();
                                //批次 如果名称一样 怎么分辨
                                //List<T_OH_HEALTH_EXAM_BATCH> listModelBatch = GetEntities<T_OH_HEALTH_EXAM_BATCH>(e => listBatch.Contains(e.BATCH) && e.END_TIME > dtMin && e.END_TIME < dtMax, null, null).ToList();
                                List<T_OH_HEALTH_EXAM_BATCH> listModelBatch = GetEntities<T_OH_HEALTH_EXAM_BATCH>(e => listBatchId.Contains(e.ID), null, null).ToList();
                                //体检人员安排  T_OH_HEALTH_EXAM_NOTICE_REGISTER

                                T_OH_HEALTH_EXAM_BATCH modelCheck = null;
                                //有 批次信息 数据库 没找到
                                foreach (var item in listBatch)
                                {
                                    modelCheck = listModelBatch.Find(e => e.BATCH == item);// listBatch.Contains(e.BATCH)
                                    if (result.IsSuccessful && modelCheck == null)
                                    {
                                        result.ErrorMessage = "未找到批次【" + item + "】信息";
                                        result.IsSuccessful = false;
                                        break;
                                    }
                                }



                                if (result.IsSuccessful)
                                {
                                    List<Guid> listBatchID = listModelBatch.Select(e => e.ID).ToList();

                                    //导入数据 是已经通知过的  未通知体检结果的
                                    var listNoticeRegister = GetEntities<T_OH_HEALTH_EXAM_NOTICE_REGISTER>(e => e.EXAM_BATCH_ID.HasValue && listBatchID.Contains(e.EXAM_BATCH_ID.Value) && e.STATUS != OHHealthExamNoticeRegisterStatus.WaitNotice && e.STATUS != OHHealthExamNoticeRegisterStatus.NoticeResult, null, new string[] { "Nav_ExamBatch", "Nav_User" });
                                    //rowCount colunCount
                                    string strName = string.Empty;
                                    string CardID = string.Empty;

                                    Dictionary<int, string> dicRowNameNone = new Dictionary<int, string>();
                                    List<T_OH_HEALTH_EXAM_RESULT> listResult = new List<T_OH_HEALTH_EXAM_RESULT>();
                                    T_OH_HEALTH_EXAM_RESULT modelShow = null;
                                    T_OH_HEALTH_EXAM_NOTICE_REGISTER modelSearch = null;
                                    List<T_OH_HEALTH_EXAM_NOTICE_REGISTER> listNoticeRegisterChange = new List<T_OH_HEALTH_EXAM_NOTICE_REGISTER>();

                                    Dictionary<int, T_FM_USER> dicIUser = new Dictionary<int, T_FM_USER>();
                                    Dictionary<int, T_OH_HEALTH_EXAM_NOTICE_REGISTER> dicIRegister = new Dictionary<int, T_OH_HEALTH_EXAM_NOTICE_REGISTER>();

                                    #region    数据组装

                                    for (int i = 0; i < rowCount; i++)
                                    {
                                        //批次
                                        strBatch = dtInfo.Rows[i][0].ToString().Trim();
                                        //姓名
                                        strName = dtInfo.Rows[i][1].ToString().Trim();
                                        var listRegister = listNoticeRegister.Where(e => !e.IS_DELETED && e.USER_ID.HasValue && e.Nav_User.NAME == strName && e.EXAM_BATCH_ID.HasValue && e.Nav_ExamBatch.BATCH == strBatch);
                                        if (listRegister == null || !listRegister.Any())
                                        {
                                            dicRowNameNone.Add(i, strName);
                                        }
                                        else
                                        {
                                            if (listRegister.Count() > 1)
                                            {
                                                //身份证号
                                                CardID = dtInfo.Rows[i][2].ToString().Trim();
                                                //过滤 
                                                //判断身份证 
                                                //提示问题
                                                if (!string.IsNullOrEmpty(CardID))
                                                {
                                                    modelSearch = listRegister.FirstOrDefault(e => e.Nav_User.ID_CARD == CardID);

                                                }
                                            }
                                            else
                                            {
                                                modelSearch = listRegister.ToList()[0];
                                            }

                                            if (modelSearch == null)
                                            {
                                                dicRowNameNone.Add(i, strName);
                                            }
                                            else
                                            {
                                                //体检批次 体检人员    身份证号 体检结论    结果描述 处理意见
                                                if (dicRowNameNone.Count == 0)
                                                {
                                                    modelShow = new T_OH_HEALTH_EXAM_RESULT();
                                                    modelShow.ID = Guid.NewGuid();
                                                    modelShow.NOTICE_REGISTER_ID = modelSearch.ID;
                                                    modelShow.USER_ID = modelSearch.USER_ID;
                                                    dicIUser.Add(i, modelSearch.Nav_User);
                                                    dicIRegister.Add(i, modelSearch);
                                                    //modelShow.Nav_User = modelSearch.Nav_User;
                                                    modelShow.RESULT_ENUM = GetResult(dtInfo.Rows[i][3].ToString(), listExamResult, HealthResult).Value;//体检结论
                                                    modelShow.DESCRIPTION = dtInfo.Rows[i][4].ToString().Trim();
                                                    modelShow.SUGGESTION = dtInfo.Rows[i][5].ToString().Trim();
                                                    //modelShow.STATUS = OHHealthExamResultStatus.WaitSign; //直接显示在页面
                                                    //直接插入数据库 
                                                    if (modelShow.RESULT_ENUM == OHHealthExamResult.Disease)
                                                    {
                                                        //职业病  待填写职业病信息
                                                        modelShow.STATUS = OHHealthExamResultStatus.WaitSignDisease;
                                                    }
                                                    else
                                                    {
                                                        //非职业病 导入数据完成
                                                        modelShow.STATUS = OHHealthExamResultStatus.Finish;
                                                    }

                                                    modelShow.IS_DELETED = false;
                                                    modelShow.ORG_ID = orgId;
                                                    //modelShow.ENTITY_ORG_TPYE =;
                                                    //modelShow.FORM_ID =;
                                                    //modelShow.FLOW_STATUS =;
                                                    //modelShow.FLOW_SEND_STATUS =;
                                                    //modelShow.FLOW_ID =;
                                                    //modelShow.CREATE_TIME =;
                                                    //modelShow.MODIFY_TIME =;
                                                    //modelShow.CREATER_ID =;
                                                    //modelShow.MODIFIER_ID =;
                                                    listResult.Add(modelShow);

                                                    //体检通知 状态修改
                                                    modelSearch.STATUS = OHHealthExamNoticeRegisterStatus.NoticeResult;
                                                    listNoticeRegisterChange.Add(modelSearch);
                                                }
                                            }
                                        }
                                    }



                                    //var notInt = resultImport.Nav_ListResult.Where(e => e.RESULT_ENUM != OHHealthExamResult.NoException);
                                    //T_FM_NOTIFICATION_TASK taskEnd = null;
                                    //if (notInt == null || !notInt.Any())
                                    //{
                                    //    if (!string.IsNullOrEmpty(taskID.ToString()))
                                    //    {
                                    //        //结束待办
                                    //        taskEnd = NotificationTaskService.GetEntityTask(new Guid(taskID.ToString()));
                                    //    }
                                    //}


                                    #endregion

                                    if (dicRowNameNone.Count > 0)
                                    {
                                        string Msg = string.Empty;
                                        foreach (var item in dicRowNameNone)
                                        {
                                            Msg += (Msg.Length > 0 ? "；" : "") + "行" + item.Key + "【" + item.Value + "】";
                                        }
                                        result.ErrorMessage = "未找到人员批次未上报结果信息【" + Msg + "】信息";
                                        result.IsSuccessful = false;
                                    }

                                    if (result.IsSuccessful)
                                    {
                                        if (listResult.Count > 0)
                                        {
                                            //不能清空 否则值不对
                                            //foreach (var item in listNoticeRegisterChange)
                                            //{
                                            //    item.Nav_User
                                            //    item.Nav_ExamBatch
                                            //}

                                            #region     职业病

                                            T_FM_NOTIFICATION_TASK taskSafe = null;
                                            List<T_FM_NOTIFICATION_TASK> listTaskMaster = new List<T_FM_NOTIFICATION_TASK>();
                                            var listDise = listResult.FindAll(e => e.RESULT_ENUM == OHHealthExamResult.Disease);
                                            if (listDise != null && listDise.Count > 0)
                                            {
                                                string MsgWarming = string.Empty;

                                                #region    安环部会议通知
                                                T_FM_USER userSafe = UserService.GetRoleUser(ref MsgWarming, "安环部负责人", null, null);
                                                if (userSafe == null || string.IsNullOrEmpty(userSafe.NAME))
                                                {
                                                    if (!string.IsNullOrEmpty(MsgWarming))
                                                    {
                                                        throw new Exception(MsgWarming);
                                                    }
                                                    else
                                                    {
                                                        throw new Exception("获取安环部负责人失败");
                                                    }
                                                }
                                                else
                                                {
                                                    taskSafe = NotificationTaskService.InsertUserNoticeTaskModel("请召开职业危害防治措施的有效性评估会", Guid.Empty, orgId, userSafe.ID, userSafe.NAME, DateTime.Now, DateTime.Now.AddDays(1), (int)FMNoticeTypeEnum.今日提醒, "");
                                                }
                                                #endregion

                                                #region     给职业病 上级部门负责人发送调岗通知

                                                List<Guid> listUserID = listDise.Select(e => e.USER_ID.Value).ToList();
                                                List<T_FM_USER> listUserDise = GetEntities<T_FM_USER>(e => listUserID.Contains(e.ID), null, new string[] { "Nav_ApproveRole", "Nav_Department.Nav_User" }).ToList();
                                                T_FM_USER userMaster = null;//上级负责人 //职业病

                                                foreach (var item in listDise)
                                                {
                                                    userMaster = null;
                                                    var user = listUserDise.FirstOrDefault(e => e.ID == item.USER_ID);
                                                    if (user.Nav_ApproveRole == null || !user.Nav_ApproveRole.NAME.Contains("负责人"))
                                                    {
                                                        userMaster = user.Nav_Department.Nav_User;
                                                    }
                                                    else
                                                    {
                                                        //上一级部门的负责人
                                                        if (user.Nav_Department.PARENT_ID.HasValue)
                                                        {
                                                            T_FM_DEPARTMENT dep = GetEntity<T_FM_DEPARTMENT>(e => e.ID == user.Nav_Department.PARENT_ID, new string[] { "Nav_User" });
                                                            userMaster = dep.Nav_User;
                                                        }
                                                        else
                                                        {
                                                            //没有上级部门

                                                        }
                                                    }
                                                    if (userMaster != null)
                                                    {
                                                        T_FM_USER userResult = GetEntity<T_FM_USER>(item.USER_ID.Value);
                                                        var taskUserMaster = NotificationTaskService.InsertUserNoticeTaskModel("体检结果为职业病，请给【" + userResult.NAME + "】调岗", Guid.Empty, item.ORG_ID, userMaster.ID, userMaster.NAME, DateTime.Now, DateTime.Now.AddDays(1), (int)FMNoticeTypeEnum.今日提醒, "");
                                                        listTaskMaster.Add(taskUserMaster);
                                                    }
                                                }

                                                #endregion
                                            }

                                            #endregion

                                            this.UnifiedCommit(() =>
                                            {
                                                if (listResult != null && listResult.Any())
                                                    BantchSaveEntityNoCommit(listResult);//体检信息
                                                if (listNoticeRegisterChange != null && listNoticeRegisterChange.Any())
                                                    BantchSaveEntityNoCommit(listNoticeRegisterChange);//体检 通知状态修改
                                                if (taskSafe != null)
                                                    UpdateEntityNoCommit(taskSafe); //职业病给安环部发送通知
                                                if (listTaskMaster != null && listTaskMaster.Any())
                                                    BantchSaveEntityNoCommit(listTaskMaster);//调岗通知
                                            });

                                            //数据库 查找是否 还有未导入审批结果的 如果没有 结束待办
                                            if (!string.IsNullOrEmpty(taskID.ToString()))
                                            {
                                                T_FM_NOTIFICATION_TASK taskEnd = null;
                                                var listNoticeRegisterCheck = GetEntities<T_OH_HEALTH_EXAM_NOTICE_REGISTER>(e => e.EXAM_BATCH_ID.HasValue && listBatchID.Contains(e.EXAM_BATCH_ID.Value) && e.STATUS != OHHealthExamNoticeRegisterStatus.WaitNotice && e.STATUS != OHHealthExamNoticeRegisterStatus.NoticeResult, null, null);
                                                if (listNoticeRegisterCheck == null || !listNoticeRegisterCheck.Any())
                                                {
                                                    this.UnifiedCommit(() =>
                                                    {
                                                        if (taskEnd != null)
                                                            UpdateEntityNoCommit(taskEnd);//全部人都填写结束待办（人事专员）
                                                    });
                                                }
                                            }


                                            #region    返回数据导航属性处理

                                            for (int i = 0; i < listResult.Count; i++)
                                            {
                                                listResult[i].Nav_User = dicIUser[i];//用户信息
                                                listResult[i].Nav_NoticeRegister = dicIRegister[i];
                                            }

                                            #endregion
                                        }

                                        result.Data = listResult;
                                        result.TotalCount = listResult.Count;
                                    }
                                }
                            }
                        }

                        try
                        {
                            System.IO.File.Delete(filePath);
                        }
                        catch { }
                        #endregion
                    }
                }
                else
                {
                    result.Data = null;//dataTables.Tables[0]
                    result.TotalCount = 0;
                }
                //return result;
            });
        }

        /// <summary>
        /// 获取体检结论
        /// </summary>
        /// <param name="strResult"></param>
        /// <param name="listExamResult"></param>
        /// <param name="HealthResult"></param>
        /// <returns></returns>
        public OHHealthExamResult? GetResult(string strResult, List<string> listExamResult, OHHealthExamResult[] HealthResult)
        {
            strResult = strResult.Trim();
            if (listExamResult.Contains(strResult.Trim()))
            {
                foreach (var item in HealthResult)
                {
                    if (item.GetDescription() == strResult)
                    {
                        return item;
                    }
                }
            }
            return null;
        }

        ///// <summary>
        ///// 显示批量导入数据 
        ///// </summary>
        ///// <param name="pageFilter"></param>
        ///// <returns></returns>
        //[HttpPost, Route("ImportShow")]
        //public PagedActionResult<T_OH_HEALTH_EXAM_RESULT> ImportShow([FromBody] KeywordPageFilter pageFilter)
        //{
        //    //return WitOrderPaged(null, pageFilter);
        //    return SafeGetPagedData(delegate (PagedActionResult<T_OH_HEALTH_EXAM_RESULT> result)
        //    {
        //        var httpRequest = this.HttpContext.Request;
        //        string orgIdStr = httpRequest.Form["OrgId"];// 获取 组织            
        //        Guid? orgId = null;
        //        if (!string.IsNullOrEmpty(orgIdStr))
        //            orgId = new Guid(orgIdStr);
        //        else
        //        {
        //            result.Data = null;//dataTables.Tables[0]
        //            result.TotalCount = 0;
        //        }

        //        var dic = Path.Combine(System.AppContext.BaseDirectory, "tempImportFiles");
        //        if (!Directory.Exists(dic))
        //            Directory.CreateDirectory(dic);
        //        foreach (var key in httpRequest.Form.Files)  // 文件键
        //        {
        //            var postedFile = key;    // 获取文件键对应的文件对象
        //            string filePath = Path.Combine(dic, DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss") + "_" + postedFile.FileName);
        //            Byte[] fileData = new Byte[postedFile.Length];
        //            Stream sr = postedFile.OpenReadStream();//创建数据流对象 
        //            sr.Read(fileData, 0, (int)postedFile.Length);
        //            using (FileStream fs = new FileStream(filePath, FileMode.CreateNew))
        //            {
        //                fs.Write(fileData, 0, fileData.Length);
        //                fs.Flush();
        //                fs.Close();
        //            }

        //            //获取数据
        //            Dictionary<int, int> startRowIndexs = new Dictionary<int, int>();
        //            startRowIndexs.Add(0, 2);//根据Excel格式数据赋值
        //            var dataTables = FileUtils.ReadExcelByOledb(filePath, startRowIndexs);

        //            //bool isOK = InsertModel(dataTables.Tables[0], orgId.Value, ref Msg);
        //            //try
        //            //{
        //            //    System.IO.File.Delete(filePath);
        //            //}
        //            //catch { }

        //            //result.Data = orderPageEntities.Data;//dataTables.Tables[0]
        //            result.TotalCount = dataTables.Tables[0].Rows.Count;


        //        }

        //        //return result;

        //    });
        //}OrderPagedUser

        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedUser")]
        public PagedActionResult<HealthResult> OrderPagedUser([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<HealthResult> result)
            {
                string Name = string.Empty;
                string DEPARTMENTNAME = string.Empty;
                string POSTNAME = string.Empty;
                OHHealthExamResult? RESULT_ENUM = null;
                if (pageFilter.FilterGroup.Rules.Count > 0)
                {
                    foreach (var item in pageFilter.FilterGroup.Rules)
                    {
                        if (item.Field == "NAME")
                        {
                            Name = item.Value.ToString();
                        }
                        else if (item.Field == "DEPARTMENTNAME")
                        {
                            DEPARTMENTNAME = item.Value.ToString();
                        }
                        else if (item.Field == "POSTNAME")
                        {
                            POSTNAME = item.Value.ToString();
                        }
                        else if (item.Field == "RESULT_ENUM")
                        {
                            try
                            {
                                RESULT_ENUM = (OHHealthExamResult)int.Parse(item.Value.ToString());
                            }
                            catch { }
                        }
                    }
                    pageFilter.FilterGroup.Rules.Clear();
                }
                Expression<Func<T_FM_USER, bool>> expressionU = e => e.ORG_ID == pageFilter.OrgId;
                if (!string.IsNullOrEmpty(Name))
                {
                    expressionU = expressionU.And(e => e.NAME.Contains(Name));
                }
                if (!string.IsNullOrEmpty(DEPARTMENTNAME))
                {
                    expressionU = expressionU.And(e => e.DEPARTMENT_ID.HasValue && e.Nav_Department.NAME.Contains(DEPARTMENTNAME));
                }
                if (!string.IsNullOrEmpty(POSTNAME))
                {
                    expressionU = expressionU.And(e => e.PERSON_ID.HasValue && e.Nav_Person.POST_ID.HasValue && e.Nav_Person.Nav_Post.NAME.Contains(POSTNAME));
                }

                #region        自定义查询

                List<T_OH_HEALTH_EXAM_RESULT> listResult = GetEntities<T_OH_HEALTH_EXAM_RESULT>(e => e.USER_ID.HasValue, null, null).ToList();
                List<T_OH_HEALTH_EXAM_RESULT_OCC_DISEASE> listDis = GetEntities<T_OH_HEALTH_EXAM_RESULT_OCC_DISEASE>(e => e.RESULT_ID.HasValue, null, new string[] { "Nav_Files.Nav_ImgFile" }).ToList();
                List<T_FM_USER> listUser = GetEntities<T_FM_USER>(expressionU, null, "Nav_Department", "Nav_Person.Nav_Post").ToList();
                List<T_OH_HEALTH_EXAM_OCC_DISEASE_SEVERITY_LEVEL> listDiseaseSeverityLevel = GetEntities<T_OH_HEALTH_EXAM_OCC_DISEASE_SEVERITY_LEVEL>(null, null, null).ToList();
                List<T_OH_HEALTH_EXAM_OCC_DISEASE> listDisease = GetEntities<T_OH_HEALTH_EXAM_OCC_DISEASE>(null, null, null).ToList();

                if (listResult.Count < 1)
                {
                    result.Data = null;
                    result.TotalCount = 0;
                }

                var query = from resultQ in listResult
                            join user in listUser on resultQ.USER_ID equals user.ID
                            join detail1 in listDis on resultQ.ID equals detail1.RESULT_ID into temp
                            from detail in temp.DefaultIfEmpty()
                            join dise1 in listDisease on detail?.OCC_DISEASE_ID equals dise1.ID into tempDis
                            from dise in tempDis.DefaultIfEmpty()
                            join diseLevel1 in listDiseaseSeverityLevel on detail?.OCC_DISEASE_SEVERITY_ID equals diseLevel1.ID into tempLevelDis
                            from diseLevel in tempLevelDis.DefaultIfEmpty()
                            select new HealthResult
                            {
                                ID = resultQ.ID,
                                CODE = user.CODE,
                                ORG_ID = resultQ.ORG_ID,
                                USER_ID = resultQ.USER_ID.Value,
                                RESULT_ENUM = resultQ.RESULT_ENUM,
                                //DESCRIPTION = resultQ.DESCRIPTION,
                                //SUGGESTION = resultQ.SUGGESTION,
                                CREATE_TIME = resultQ.CREATE_TIME,
                                NAME = user.NAME,
                                ID_CARD = user.ID_CARD,
                                ENTRYTIME = user.ENTRYTIME == DateTime.MinValue ? null : user.ENTRYTIME,
                                DEPARTMENT_ID = user.DEPARTMENT_ID,
                                DEPARTMENTNAME = user.Nav_Department.NAME,
                                POSTNAME = user.Nav_Person?.Nav_Post?.NAME,
                                PERSON_ID = user.PERSON_ID,
                                DEPARTURETIME = user.DEPARTURETIME == DateTime.MinValue ? null : user.DEPARTURETIME,
                                //DIAGNOSE_AGENCY = detail == null ? null : detail.DIAGNOSE_AGENCY,
                                //DIAGNOSE_METHOD = detail == null ? null : detail.DIAGNOSE_METHOD,
                                //DisDESCRIPTION = detail == null ? null : detail.DESCRIPTION,
                                //OCC_HISTORY = detail == null ? null : detail.OCC_HISTORY,
                                OCC_DISEASE_SEVERITY_ID = detail == null ? null : detail.OCC_DISEASE_SEVERITY_ID,
                                OCC_DISEASE_ID = detail == null ? null : detail.OCC_DISEASE_ID,
                                //disName = dise == null ? "" : dise.NAME,
                                disLevelName = diseLevel == null ? "" : diseLevel.NAME,
                                //Nav_Files = detail == null ? null : detail.Nav_Files
                            };

                #region   查询条件

                if (!string.IsNullOrEmpty(Name))
                {
                    query = query.Where(e => e.NAME.Contains(Name));
                }
                if (!string.IsNullOrEmpty(DEPARTMENTNAME))
                {
                    query = query.Where(e => e.DEPARTMENTNAME != null && e.DEPARTMENTNAME.Contains(DEPARTMENTNAME));
                }
                if (!string.IsNullOrEmpty(POSTNAME))
                {
                    query = query.Where(e => e.POSTNAME != null && e.POSTNAME.Contains(POSTNAME));
                }
                if (RESULT_ENUM.HasValue)
                {
                    query = query.Where(e => e.RESULT_ENUM == RESULT_ENUM.Value);
                }

                #endregion

                var listResultTemp = query.OrderBy(e => e.NAME).ThenByDescending(e => e.CREATE_TIME).Skip((pageFilter.PageIndex - 1) * pageFilter.Limit).Take(pageFilter.Limit).ToList();

                result.Data = listResultTemp;
                result.TotalCount = query.Count();

                #endregion

                #region      旧版 不满足需求

                //pageFilter.Sort = "Nav_User.NAME";
                //pageFilter.Include.Remove("Nav_User.Nav_Department");
                //pageFilter.Include.Remove("Nav_User.Nav_Person.Nav_Post");
                //pageFilter.Include.Remove("Nav_OccDiseaseList.Nav_OccDisease");
                //pageFilter.Include.Remove("Nav_OccDiseaseList.Nav_OccDiseaseSeverity");
                //pageFilter.Include.Remove("Nav_OccDiseaseList.Nav_Files.Nav_ImgFile");

                //pageFilter.SelectField = new List<string> { "ID", "USER_ID", "RESULT_ENUM", "DESCRIPTION", "SUGGESTION", "RESULT_ENUM", "Nav_User.NAME", "Nav_User.ID_CARD", "Nav_User.ENTRYTIME", "Nav_User.DEPARTMENT_ID", "Nav_User.PERSON_ID", "Nav_User.DEPARTURETIME", "Nav_OccDiseaseList.OCC_DISEASE_SEVERITY_ID", "Nav_OccDiseaseList.OCC_DISEASE_ID" };

                //PagedActionResult<T_OH_HEALTH_EXAM_RESULT> orderPageEntities = GetOrderPageEntities<T_OH_HEALTH_EXAM_RESULT>(e => e.USER_ID.HasValue, pageFilter, null);
                //result.Data = orderPageEntities.Data;
                //if (result.Data != null && result.Data.Any())
                //{
                //    #region    岗位 
                //    var listPersonID = result.Data.Where(e => e.Nav_User.PERSON_ID.HasValue).Select(e => e.Nav_User.PERSON_ID);
                //    var listPerson = GetEntities<T_FM_PERSON>(e => listPersonID.Contains(e.ID), null, "Nav_Post");
                //    T_FM_PERSON personTemp = null;
                //    #endregion
                //    #region    部门
                //    var listDepID = result.Data.Select(e => e.Nav_User.DEPARTMENT_ID);
                //    var listDep = GetEntities<T_FM_DEPARTMENT>(e => listDepID.Contains(e.ID), null, null);
                //    T_FM_DEPARTMENT depTemp = null;
                //    #endregion
                //    #region      职业病  严重等级
                //    List<T_OH_HEALTH_EXAM_OCC_DISEASE_SEVERITY_LEVEL> listDiseaseSeverityLevel = GetEntities<T_OH_HEALTH_EXAM_OCC_DISEASE_SEVERITY_LEVEL>(e => e.ORG_ID == pageFilter.OrgId, null, "").ToList();
                //    List<T_OH_HEALTH_EXAM_OCC_DISEASE> listDisease = GetEntities<T_OH_HEALTH_EXAM_OCC_DISEASE>(e => e.ORG_ID == pageFilter.OrgId, null, "").ToList();

                //    T_OH_HEALTH_EXAM_OCC_DISEASE_SEVERITY_LEVEL levelTemp = null;
                //    T_OH_HEALTH_EXAM_OCC_DISEASE diseaseTemp = null;

                //    #endregion

                //    foreach (var item in result.Data)
                //    {
                //        #region    入职离职日期 
                //        if (item.Nav_User.ENTRYTIME != DateTime.MinValue)
                //            item.ENTRYTIME = item.Nav_User.ENTRYTIME;
                //        if (item.Nav_User.DEPARTURETIME != DateTime.MinValue)
                //            item.DEPARTURETIME = item.Nav_User.DEPARTURETIME;
                //        #endregion
                //        #region    人员岗位
                //        if (item.Nav_User.PERSON_ID.HasValue)
                //        {
                //            personTemp = listPerson.FirstOrDefault(e => e.ID == item.Nav_User.PERSON_ID);
                //            if (personTemp != null)
                //            {
                //                item.Nav_User.Nav_Person = personTemp;
                //            }
                //        }
                //        #endregion
                //        #region      部门
                //        if (item.Nav_User.DEPARTMENT_ID.HasValue)
                //        {
                //            depTemp = listDep.FirstOrDefault(e => e.ID == item.Nav_User.DEPARTMENT_ID.Value);
                //            if (depTemp != null)
                //            {
                //                item.Nav_User.Nav_Department = depTemp;
                //            }
                //        }
                //        #endregion
                //        //pageFilter.Include.Remove("Nav_OccDiseaseList.Nav_OccDisease");
                //        //pageFilter.Include.Remove("Nav_OccDiseaseList.Nav_OccDiseaseSeverity");
                //        //pageFilter.Include.Remove("Nav_OccDiseaseList.Nav_Files.Nav_ImgFile");
                //        if (item.Nav_OccDiseaseList != null && item.Nav_OccDiseaseList.Any())
                //        {
                //            foreach (var itemOcc in item.Nav_OccDiseaseList)
                //            {
                //                if (itemOcc.OCC_DISEASE_SEVERITY_ID.HasValue)
                //                {
                //                    levelTemp = listDiseaseSeverityLevel.FirstOrDefault(e => e.ID == itemOcc.OCC_DISEASE_SEVERITY_ID.Value);
                //                    if (levelTemp != null)
                //                    {
                //                        itemOcc.Nav_OccDiseaseSeverity = levelTemp;
                //                    }
                //                }
                //                if (itemOcc.OCC_DISEASE_ID.HasValue)
                //                {
                //                    diseaseTemp = listDisease.FirstOrDefault(e => e.ID == itemOcc.OCC_DISEASE_ID.Value);
                //                    if (diseaseTemp != null)
                //                    {
                //                        itemOcc.Nav_OccDisease = diseaseTemp;
                //                    }
                //                }
                //            }
                //        }
                //    }
                //}
                //result.TotalCount = orderPageEntities.TotalCount;

                #endregion

            });
        }


        #region     员工健康监护档案导入


        /// <summary>
        /// 员工健康监护档案导入  
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("GetImportData")]
        public JsonActionResult<ImportDataModel> GetImportData()
        {
            return SafeExecute<ImportDataModel>(() =>
            {
                var httpRequest = this.HttpContext.Request;
                string orgIdStr = httpRequest.Form["OrgId"];// 获取 组织            
                Guid? orgId = null;
                if (!string.IsNullOrEmpty(orgIdStr))
                    orgId = new Guid(orgIdStr);
                else
                    return null;
                ImportDataModel result = new ImportDataModel();
                var dic = Path.Combine(System.AppContext.BaseDirectory, "tempImportFiles");
                if (!Directory.Exists(dic))
                    Directory.CreateDirectory(dic);
                foreach (var key in httpRequest.Form.Files)  // 文件键
                {
                    var postedFile = key;    // 获取文件键对应的文件对象
                    string filePath = Path.Combine(dic, DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss") + "_" + postedFile.FileName);
                    Byte[] fileData = new Byte[postedFile.Length];
                    Stream sr = postedFile.OpenReadStream();//创建数据流对象 
                    sr.Read(fileData, 0, (int)postedFile.Length);
                    using (FileStream fs = new FileStream(filePath, FileMode.CreateNew))
                    {
                        fs.Write(fileData, 0, fileData.Length);
                        fs.Flush();
                        fs.Close();
                    }

                    //获取数据
                    Dictionary<int, int> startRowIndexs = new Dictionary<int, int>();
                    startRowIndexs.Add(0, 3);//根据Excel格式数据赋值
                    var dataTables = FileUtils.ReadExcelByOledb(filePath, startRowIndexs);
                    string Msg = string.Empty;

                    bool isOK = InsertModel(dataTables.Tables[0], orgId.Value, ref Msg);

                    try
                    {
                        System.IO.File.Delete(filePath);
                    }
                    catch { }

                    result.Data = Msg;
                    result.MessageList = new List<string> { Msg };
                }

                return result;
            });
        }

        /// <summary>
        /// 数据判断与导入
        /// </summary>
        /// <param name="dtSource"></param>
        /// <param name="OrgID"></param>
        /// <param name="Msg"></param>
        /// <param name="rowIndex"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public bool InsertModel(DataTable dtSource, Guid OrgID, ref string Msg, int rowIndex = 4)
        {
            //0、姓名*  1、身份证号*  2、职业危害类型*  3、上次参检时间  4、体检结论* 5、结果描述    6、处理意见  7、职业病名称   8、诊断机构 9、诊断方式    10、职业病严重等级  11、病状描述    12、入厂前工作史
            //职业危害类型 取配置
            //体检结论 取枚举
            //职业病严重等级（如果有） 取枚举

            if (dtSource == null || dtSource.Rows.Count < 0)
            {
                Msg = "未获取到导入数据";
                throw new Exception(Msg);
            }

            List<int> listNotEmpty = new List<int>() { 0, 1, 2, 3, 4 };//不能为空的列信息
            Dictionary<int, List<int>> dicIndexEmpty = new Dictionary<int, List<int>>();//某列 哪些行信息为空

            //所有部门信息
            var listAllDeps = GetEntities<T_FM_DEPARTMENT>(e => e.ENABLE_STATUS == 0, null, null);
            T_FM_DEPARTMENT modelDep = null;
            //所有体检周期  对应职业危害   部门范围
            var listAllCycle = GetEntities<T_OH_HEALTH_EXAM_CYCLE>(e => true, null, null); //所有体检周期
            IEnumerable<T_OH_HEALTH_EXAM_CYCLE> iListCycle = null;
            var listAllOccHazard = GetEntities<T_OH_HEALTH_EAXM_CYCLE_OCC_HAZARD_MID>(e => true, null, null);//所有体检周期  对应职业危害
            IEnumerable<T_OH_HEALTH_EAXM_CYCLE_OCC_HAZARD_MID> iListCycleOccHazard = null;
            var listAllCycleDepartmentInfo = GetEntities<T_OH_HEALTH_EXAM_CYCLE_DEPARTMENTINFO>(e => e.DEPARTMENT_ID.HasValue, null, null);//所有体检周期  部门范围  
            IEnumerable<Guid> iListDEPARTMENTINFOID = null;
            IEnumerable<T_OH_HEALTH_EXAM_CYCLE_DEPARTMENTINFO> iListCycleDepInfo = null;
            T_OH_HEALTH_EXAM_CYCLE_DEPARTMENTINFO modelDepInfo = null;
            var listAllCycleDepartmentInfoPost = GetEntities<T_OH_HEALTH_EXAM_CYCLE_DEPARTMENTINFO_POST>(e => true, null, null);//所有体检周期  部门范围 岗位
            IEnumerable<T_OH_HEALTH_EXAM_CYCLE_DEPARTMENTINFO_POST> iListCycleDepInfoPost = null;
            IEnumerable<Guid> iListGUID = null;
            IEnumerable<Guid> iListHazardIDCycleID = null;
            IEnumerable<Guid> iListPostIDCycleID = null;
            IEnumerable<Guid> iListPostIDHazardIDCycleID = null;

            string split = "、";//多个职业危害 可以用 【、】区分
            #region     定义变量 获取判断值

            //1、姓名* 
            //2、身份证号*
            //List<int> listEmptyUser = new List<int>();
            List<int> listWrongUser = new List<int>();
            List<string> listWrongStrUser = new List<string>();//错误文本
            T_FM_USER modelUser = null;
            var listUser = GetEntities<T_FM_USER>(e => !e.IS_DELETED && e.ENABLE_STATUS == 0, null, null);
            var listPerson = GetEntities<T_FM_PERSON>(e => !e.IS_DELETED, null, null);
            Guid? PostID = null;//用户的岗位ID

            //3、职业危害类型 * 
            List<int> listWrongIdentify = new List<int>();
            List<string> listWrongStrIdentify = new List<string>();
            T_HM_IDENTIFYING modelIdentify = null;
            var listIdentify = GetEntities<T_HM_IDENTIFYING>(e => !e.IS_DELETED && e.RISK_TYPE == HMRiskTypeEnmu.职业危害辨识, null, null);

            //4、上次参检时间
            List<int> listWrongCheckTime = new List<int>();
            List<string> listWrongStrCheckTime = new List<string>();

            //5、体检结论* 
            //List<int> listEmptyResult = new List<int>();
            List<int> listWrongResult = new List<int>();
            List<string> listWrongStrResult = new List<string>();
            EnumsResult modelEnumsResult = null;
            List<EnumsResult> listExamResult = DataHelper.GetEnum("OHHealthExamResult");

            //6、结果描述    
            //7、处理意见 
            //8、职业病名称  
            List<int> listEmptyDiseaseName = new List<int>();//职业病时 职业病名称不能为空
            List<int> listWrongDiseaseName = new List<int>();
            List<string> listWrongStrDiseaseName = new List<string>();
            T_OH_HEALTH_EXAM_OCC_DISEASE modelDisease = null;
            var listDiseaseName = GetEntities<T_OH_HEALTH_EXAM_OCC_DISEASE>(e => !e.IS_DELETED, null, null);//其实可以自动加 就怕名称乱的

            //9、诊断机构 
            //10、诊断方式    
            //11、职业病严重等级 
            List<int> listWrongDiseaseLevel = new List<int>();
            List<string> listWrongStrDiseaseLevel = new List<string>();
            T_OH_HEALTH_EXAM_OCC_DISEASE_SEVERITY_LEVEL modelDiseaseLevel = null;
            var listDiseaseLevel = GetEntities<T_OH_HEALTH_EXAM_OCC_DISEASE_SEVERITY_LEVEL>(e => !e.IS_DELETED, null, null);//严重等级
            //12、病状描述    
            //13、入厂前工作史

            #endregion

            //健康档案
            List<T_OH_HEALTH_EXAM_RESULT> listHealthResult = new List<T_OH_HEALTH_EXAM_RESULT>();
            T_OH_HEALTH_EXAM_RESULT modelHealthResult = null;//体检结果
            List<T_OH_EXAM_RESULT_OCC_HAZARD> listResultHazard = new List<T_OH_EXAM_RESULT_OCC_HAZARD>();
            T_OH_EXAM_RESULT_OCC_HAZARD modelResultHazard = null;//职业危害类型
            List<T_OH_HEALTH_EXAM_RESULT_OCC_DISEASE> listResultDisease = new List<T_OH_HEALTH_EXAM_RESULT_OCC_DISEASE>();
            T_OH_HEALTH_EXAM_RESULT_OCC_DISEASE modelResultDisease = null;//职业病信息
            DateTime dtNow = new DateTime();

            //T_OH_HEALTH_EXAM_NOTICE modelNotice = null;//体检通知
            List<T_OH_HEALTH_EXAM_NOTICE_REGISTER> listNoticeRegister = new List<T_OH_HEALTH_EXAM_NOTICE_REGISTER>();//体检安排
            T_OH_HEALTH_EXAM_NOTICE_REGISTER modelNoticeRegister = null;//体检安排
            T_OH_HEALTH_EXAM_CYCLE modelCycle = null;
            List<string> listNoCycleName = new List<string>();
            #region     数据判断

            //第一行是标题 跳过
            int rowAll = dtSource.Rows.Count;
            List<EnumsResult> list = DataHelper.GetEnum("BSMineTypeEnum");

            string strContent = string.Empty;
            string strContentNO = string.Empty;
            DateTime? deCheckTime = null; //上次参检时间
            Guid loginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;
            for (int i = 0; i < rowAll; i++)
            {
                #region    不能为空
                List<int> listi = null;
                for (int j = 0; j < 5; j++)//4为  listNotEmpty 中的最大值
                {
                    if (!listNotEmpty.Contains(j))
                        continue;

                    if (string.IsNullOrEmpty(dtSource.Rows[i][j].ToString().Trim()))
                    {
                        if (listi == null)
                        {
                            listi = new List<int>();
                        }
                        listi.Add(j + 1);
                    }
                }
                if (listi != null)
                {
                    dicIndexEmpty.Add(i + rowIndex, listi);//有空的 直接添加
                    continue;
                }

                #endregion
                #region    姓名   身份证号  0 1 匹配
                strContent = dtSource.Rows[i][0].ToString().Trim();
                strContentNO = dtSource.Rows[i][1].ToString().Trim();

                modelUser = listUser.FirstOrDefault(e => e.NAME == strContent && e.ID_CARD == strContentNO);
                if (modelUser == null)
                {
                    modelUser = listUser.FirstOrDefault(e => e.CODE == strContent && e.ID_CARD == strContentNO);//兼容匹配工号
                }
                if (modelUser == null)
                {
                    listWrongUser.Add(i + rowIndex);//未获取到对应的人 下一个
                    if (!listWrongStrUser.Contains(strContent + "【" + strContentNO + "】"))
                        listWrongStrUser.Add(strContent + "【" + strContentNO + "】");
                    continue;
                }

                #endregion
                #region 职业危害类型  2

                strContent = dtSource.Rows[i][2].ToString().Trim();
                modelIdentify = listIdentify.FirstOrDefault(e => e.NAME == strContent);
                if (modelIdentify == null)
                {
                    listWrongIdentify.Add(i + rowIndex);//未获取到对应的人 下一个
                    if (!listWrongStrIdentify.Contains(strContent))
                        listWrongStrIdentify.Add(strContent);
                    continue;
                }

                #endregion
                #region 上次参检时间  3
                strContent = dtSource.Rows[i][3].ToString().Trim();
                if (!string.IsNullOrEmpty(strContent))
                {
                    try
                    {
                        deCheckTime = Convert.ToDateTime(strContent);
                    }
                    catch
                    {
                        listWrongCheckTime.Add(i + rowIndex);//未获取到对应的人 下一个
                        if (!listWrongStrCheckTime.Contains(strContent))
                            listWrongStrCheckTime.Add(strContent);
                        continue;
                    }
                }

                #endregion
                #region 体检结论  4

                strContent = dtSource.Rows[i][4].ToString().Trim();
                if (!string.IsNullOrEmpty(strContent))
                {
                    modelEnumsResult = listExamResult.FirstOrDefault(e => e.NAME == strContent);
                    if (modelEnumsResult == null)
                    {
                        listWrongResult.Add(i + rowIndex);//未获取到对应的人 下一个
                        if (!listWrongStrResult.Contains(strContent))
                            listWrongStrResult.Add(strContent);
                        continue;
                    }
                }

                #endregion
                #region     职业病名称 7
                //未填写 0  //目前未见异常 5  //建议复查 10 //职业病 15 //职业禁忌症 20   //其他疾病或异常 25  //疑似职业病 30
                strContent = dtSource.Rows[i][7].ToString().Trim();
                if (modelEnumsResult.ID == (int)OHHealthExamResult.Disease)//|| modelEnumsResult.ID == (int)OHHealthExamResult.Contraindications || modelEnumsResult.ID == (int)OHHealthExamResult.OtherDisease
                {
                    if (string.IsNullOrEmpty(strContent))
                    {
                        listEmptyDiseaseName.Add(i + rowIndex);//未获取到对应的人 下一个
                        continue;
                    }
                    modelDisease = listDiseaseName.FirstOrDefault(e => e.NAME == strContent);
                    if (modelDisease == null)
                    {
                        listWrongDiseaseName.Add(i + rowIndex);//未获取到对应的人 下一个
                        if (!listWrongStrDiseaseName.Contains(strContent))
                            listWrongStrDiseaseName.Add(strContent);
                        continue;
                    }
                }

                #endregion
                #region  职业病严重等级 10

                if (modelDisease != null)
                {
                    strContent = dtSource.Rows[i][10].ToString().Trim();
                    if (!string.IsNullOrEmpty(strContent))
                    {
                        modelDiseaseLevel = listDiseaseLevel.FirstOrDefault(e => e.NAME == strContent);
                        if (modelDiseaseLevel == null)
                        {
                            listWrongDiseaseLevel.Add(i + rowIndex);//未获取到对应的人 下一个
                            if (!listWrongStrDiseaseLevel.Contains(strContent))
                                listWrongStrDiseaseLevel.Add(strContent);
                            continue;
                        }
                    }
                }

                #endregion

                #region     体检周期 获取
                //未获取到体检周期 也要向下继续 比如 boss加进去体检
                //根据 体检周期 职业危害类型  部门岗位  找出最适合的体检周期配置

                iListHazardIDCycleID = null;
                iListPostIDCycleID = null;
                iListPostIDHazardIDCycleID = null;

                iListCycleOccHazard = listAllOccHazard.Where(e => e.HAZARD_ID == modelIdentify.ID);
                if (iListCycleOccHazard != null && iListCycleOccHazard.Any())
                    iListHazardIDCycleID = iListCycleOccHazard.Select(e => e.RECORD_ID).Distinct().ToList();//;//获取 符合【职业危害】条件的所有 体检周期表ID

                if (modelUser.PERSON_ID.HasValue)
                    PostID = listPerson.FirstOrDefault(e => e.ID == modelUser.PERSON_ID)?.POST_ID;
                if (PostID != null && PostID != Guid.Empty)
                    iListCycleDepInfoPost = listAllCycleDepartmentInfoPost.Where(e => e.POST_ID == PostID);//体检周期【岗位】符合的
                if (iListCycleDepInfoPost != null && iListCycleDepInfoPost.Any())
                {
                    iListPostIDCycleID = iListCycleDepInfoPost.Select(e => e.DEPARTMENTINFO_ID);
                    if (iListPostIDCycleID != null && iListPostIDCycleID.Any())
                        iListPostIDCycleID = listAllCycleDepartmentInfo.Where(e => iListPostIDCycleID.Contains(e.ID)).Select(e => e.EXAM_CYCLE_ID).Distinct().ToList();//获取 符合【岗位】条件的所有 体检周期表ID
                }

                if (iListHazardIDCycleID != null && iListPostIDCycleID != null)
                {
                    try
                    {
                        modelCycle = GetUserDepPostCycle(modelUser.DEPARTMENT_ID, iListHazardIDCycleID, iListPostIDCycleID, listAllDeps, listAllCycle, listAllCycleDepartmentInfo);
                    }
                    catch { }
                }
                else
                {
                    modelCycle = null;
                }

                if (modelCycle == null)
                {
                    listNoCycleName.Add(dtSource.Rows[i][0].ToString().Trim());
                }
                #endregion
                #region      listHealthResult.Add 健康档案 （体检结论、体检结果职业危害、职业病 信息、体检通知信息（周期））

                if (listWrongUser.Count < 1 && listWrongIdentify.Count < 1 && listWrongCheckTime.Count < 1 && listWrongResult.Count < 1 && listEmptyDiseaseName.Count < 1 && listWrongDiseaseName.Count < 1 && listWrongDiseaseLevel.Count < 1)
                {
                    //0、姓名*  1、身份证号*  2、职业危害类型*  3、上次参检时间  4、体检结论* 5、结果描述    6、处理意见  7、职业病名称   8、诊断机构 9、诊断方式    10、职业病严重等级  11、病状描述    12、入厂前工作史
                    #region     体检结论

                    modelHealthResult = new T_OH_HEALTH_EXAM_RESULT();
                    modelHealthResult.ID = Guid.NewGuid();
                    modelHealthResult.ORG_ID = OrgID;
                    modelHealthResult.IS_DELETED = false;
                    modelHealthResult.CREATE_TIME = dtNow;
                    modelHealthResult.CREATER_ID = loginID;

                    modelHealthResult.USER_ID = modelUser.ID;
                    modelHealthResult.RESULT_ENUM = (OHHealthExamResult)modelEnumsResult.ID;
                    modelHealthResult.DESCRIPTION = dtSource.Rows[i][5].ToString().Trim();
                    modelHealthResult.SUGGESTION = dtSource.Rows[i][6].ToString().Trim();
                    modelHealthResult.STATUS = OHHealthExamResultStatus.Finish;

                    #endregion

                    #region   体检结果职业危害
                    modelResultHazard = new T_OH_EXAM_RESULT_OCC_HAZARD();
                    modelResultHazard.ID = Guid.NewGuid();
                    modelResultHazard.ORG_ID = OrgID;
                    modelResultHazard.IS_DELETED = false;
                    modelResultHazard.CREATE_TIME = dtNow;
                    modelResultHazard.CREATER_ID = loginID;

                    modelResultHazard.RESULT_ID = modelHealthResult.ID;
                    modelResultHazard.HAZARD_ID = modelIdentify.ID;

                    listResultHazard.Add(modelResultHazard);
                    #endregion

                    #region 职业病 信息
                    if (modelHealthResult.RESULT_ENUM == OHHealthExamResult.Disease)//|| modelHealthResult.RESULT_ENUM == OHHealthExamResult.Contraindications || modelHealthResult.RESULT_ENUM == OHHealthExamResult.OtherDisease
                    {
                        modelResultDisease = new T_OH_HEALTH_EXAM_RESULT_OCC_DISEASE();
                        modelResultDisease.ID = Guid.NewGuid();
                        modelResultDisease.ORG_ID = OrgID;
                        modelResultDisease.IS_DELETED = false;
                        modelResultDisease.CREATE_TIME = dtNow;
                        modelResultDisease.CREATER_ID = loginID;

                        modelResultDisease.RESULT_ID = modelHealthResult.ID;
                        modelResultDisease.MEDICAL_AID = YesNoEnum.No;//默认未启用
                        if (modelDisease != null)
                            modelResultDisease.OCC_DISEASE_ID = modelDisease.ID;
                        modelResultDisease.DIAGNOSE_AGENCY = dtSource.Rows[i][8].ToString().Trim();
                        modelResultDisease.DIAGNOSE_METHOD = dtSource.Rows[i][9].ToString().Trim();
                        if (modelDiseaseLevel != null)
                            modelResultDisease.OCC_DISEASE_SEVERITY_ID = modelDiseaseLevel.ID;
                        modelResultDisease.DESCRIPTION = dtSource.Rows[i][11].ToString().Trim();
                        modelResultDisease.OCC_HISTORY = dtSource.Rows[i][12].ToString().Trim();

                        listResultDisease.Add(modelResultDisease);
                    }
                    #endregion

                    listHealthResult.Add(modelHealthResult);

                    //怎么补齐体检通知
                    //T_OH_HEALTH_EXAM_NOTICE_REGISTER

                    #region 体检通知信息（周期）

                    modelNoticeRegister = new T_OH_HEALTH_EXAM_NOTICE_REGISTER();//体检安排
                    modelNoticeRegister.ID = Guid.NewGuid();
                    modelNoticeRegister.ORG_ID = OrgID;
                    modelNoticeRegister.IS_DELETED = false;
                    modelNoticeRegister.CREATE_TIME = dtNow;
                    modelNoticeRegister.CREATER_ID = loginID;

                    modelNoticeRegister.USER_ID = modelUser.ID;
                    modelNoticeRegister.DEPARTMENT_ID = modelUser.DEPARTMENT_ID;
                    //modelNoticeRegister.DEPARTMENT_ID = Guid.Empty;// modelUser.DEPARTMENT_ID;//部门
                    //modelNoticeRegister.DEPARTMENT_ID_WORKSHOP = Guid.Empty;// modelUser.DEPARTMENT_ID;//车间
                    modelNoticeRegister.TYPE = OHHealthExamType.Post;
                    modelNoticeRegister.STATUS = OHHealthExamNoticeRegisterStatus.NoticeResult;
                    modelNoticeRegister.THISDATE = deCheckTime;
                    if (modelCycle != null)
                    {
                        modelNoticeRegister.CYCLE_ID = modelCycle.ID;
                        modelNoticeRegister.NEXTDATE = deCheckTime.Value.AddMonths(modelCycle.HEALTH_EXAM_CYCLE);
                    }
                    listNoticeRegister.Add(modelNoticeRegister);

                    #endregion
                }
                #endregion
            }

            #endregion

            if (dicIndexEmpty.Count > 0 || listEmptyDiseaseName.Count > 0 || listWrongUser.Count > 0 || listWrongIdentify.Count > 0 || listWrongCheckTime.Count > 0 || listWrongResult.Count > 0 || listWrongDiseaseName.Count > 0 || listWrongDiseaseLevel.Count > 0)
            {
                #region     错误提示
                // 行：1，列：2、3、4；行：2，列：1 不能为空！
                string strEmptyError = string.Empty;
                if (dicIndexEmpty.Count > 0)
                {
                    int colIndex = 0;
                    foreach (var item in dicIndexEmpty)
                    {
                        strEmptyError += "行：" + item.Key + "，列：";
                        colIndex = 0;
                        foreach (var itemVal in item.Value)
                        {
                            strEmptyError += (colIndex > 0 ? "、" : "") + itemVal;
                            colIndex++;
                        }
                        strEmptyError += "；";
                    }
                    strEmptyError = strEmptyError.Substring(0, strEmptyError.Length - 1) + "不能为空！";
                }

                string strDiseaseNameEmpty = string.Empty;
                if (listEmptyDiseaseName != null && listEmptyDiseaseName.Any())
                    strDiseaseNameEmpty = "【职业病】职业病名称不能为空，行：" + string.Join(',', listEmptyDiseaseName);

                string strUserError = string.Empty;
                if (listWrongUser != null && listWrongUser.Count > 0)
                    strUserError = "未找到人员:" + string.Join(",", listWrongStrUser) + "，行：" + string.Join(',', listWrongUser);

                string strIdentifyError = string.Empty;
                if (listWrongIdentify != null && listWrongIdentify.Count > 0)
                    strIdentifyError = "未找到职业危害类型:" + string.Join(",", listWrongStrIdentify) + ",行：" + string.Join(',', listWrongIdentify);

                string strCheckTimeError = string.Empty;
                if (listWrongCheckTime != null && listWrongCheckTime.Count > 0)
                    strCheckTimeError = "上次参检时间格式错误:" + string.Join(",", listWrongStrCheckTime) + "，行：" + string.Join(',', listWrongCheckTime);

                string strResultError = string.Empty;
                if (listWrongResult != null && listWrongResult.Count > 0)
                    strResultError = "未找到体检结论：" + string.Join(",", listWrongStrResult) + "，行：" + string.Join(',', listWrongResult);

                string strDiseaseNameError = string.Empty;
                if (listWrongDiseaseName != null && listWrongDiseaseName.Count > 0)
                    strDiseaseNameError = "未找到职业病名称：" + string.Join(",", listWrongStrDiseaseName) + "，行：" + string.Join(',', listWrongDiseaseName);

                string strDiseaseLevelError = string.Empty;
                if (listWrongDiseaseLevel != null && listWrongDiseaseLevel.Count > 0)
                    strDiseaseLevelError = "未找到职业病严重等级：" + string.Join(",", listWrongStrDiseaseLevel) + "，行：" + string.Join(',', listWrongDiseaseLevel);

                if (!string.IsNullOrEmpty(strEmptyError))
                {
                    Msg += strEmptyError;
                }
                if (!string.IsNullOrEmpty(strDiseaseNameEmpty)) //3、【职业病】职业病名称
                {
                    Msg += (Msg.Length > 0 ? "、\r\n" : "") + strDiseaseNameEmpty;
                }
                if (!string.IsNullOrEmpty(strUserError)) //3、人员信息
                {
                    Msg += (Msg.Length > 0 ? "、\r\n" : "") + strUserError;
                }
                if (!string.IsNullOrEmpty(strIdentifyError)) //3、职业危害类型
                {
                    Msg += (Msg.Length > 0 ? "、\r\n" : "") + strIdentifyError;
                }
                if (!string.IsNullOrEmpty(strCheckTimeError))//4、上次参检时间
                {
                    Msg += (Msg.Length > 0 ? "、\r\n" : "") + strCheckTimeError;
                }
                if (!string.IsNullOrEmpty(strResultError))//5、体检结论
                {
                    Msg += (Msg.Length > 0 ? "、\r\n" : "") + strResultError;
                }
                if (!string.IsNullOrEmpty(strDiseaseNameError))//8、职业病名称 
                {
                    Msg += (Msg.Length > 0 ? "、\r\n" : "") + strDiseaseNameError;
                }
                if (!string.IsNullOrEmpty(strDiseaseLevelError))//11、职业病严重等级 
                {
                    Msg += (Msg.Length > 0 ? "、\r\n" : "") + strDiseaseLevelError;
                }
                if (!string.IsNullOrEmpty(Msg))
                {
                    throw new Exception(Msg);
                }

                #endregion
            }
            else if (listHealthResult != null && listHealthResult.Any())
            {
                this.UnifiedCommit(() =>
                {
                    BantchSaveEntityNoCommit(listHealthResult);//体检结果
                    if (listResultHazard != null && listResultHazard.Any())//职业危害
                        BantchSaveEntityNoCommit(listResultHazard);
                    if (listResultDisease != null && listResultDisease.Any())//职业病
                        BantchSaveEntityNoCommit(listResultDisease);
                    if (listNoticeRegister != null && listNoticeRegister.Any())//体检通知信息（周期）
                        BantchSaveEntityNoCommit(listNoticeRegister);
                });
                Msg = "导入成功！\r\n共：" + listHealthResult.Count + "条健康监护档案信息！";
                if (listNoCycleName != null && listNoCycleName.Any())
                {
                    try
                    {
                        Msg += "\r\n 其中未匹配到体检周期的有" + string.Join(",", listNoCycleName);
                    }
                    catch { }
                }
            }
            else
            {
                throw new Exception("功能异常，请联系管理员");
            }

            return true;
        }


        /// <summary>
        /// 递归  获取限定 职业危害类型与岗位 对应 组织  的体检周期
        /// </summary>
        /// <param name="DepartmentID">部门</param>
        /// <param name="iListPostIDHazardIDCycleID">职业危害类型 岗位 限制下的体检周期ID</param>
        /// <param name="listAllDeps">部门信息 用于循环查找</param>
        /// <param name="listAllCycle">体检周期</param>
        /// <param name="listAllCycleDepartmentInfo">某职业危害类型 对应所有中间表</param>
        /// <returns></returns>
        private T_OH_HEALTH_EXAM_CYCLE GetUserDepPostCycle(Guid? DepartmentID, IEnumerable<Guid> iListHazardIDCycleID, IEnumerable<Guid> iListPostIDCycleID, IEnumerable<T_FM_DEPARTMENT> listAllDeps, IEnumerable<T_OH_HEALTH_EXAM_CYCLE> listAllCycle, IEnumerable<T_OH_HEALTH_EXAM_CYCLE_DEPARTMENTINFO> listAllCycleDepartmentInfo)
        {
            if (DepartmentID == null || DepartmentID == Guid.Empty || listAllCycle == null || !listAllCycle.Any() || listAllCycleDepartmentInfo == null || !listAllCycleDepartmentInfo.Any() || iListHazardIDCycleID == null || !iListHazardIDCycleID.Any() || iListPostIDCycleID == null || !iListPostIDCycleID.Any())
            {
                //此操作不应进入递归查找
                return null;
            }
            else //(DepartmentID != null && DepartmentID != Guid.Empty)
            {
                var modelDepInfo = listAllCycleDepartmentInfo.FirstOrDefault(e => iListHazardIDCycleID.Contains(e.EXAM_CYCLE_ID) && iListPostIDCycleID.Contains(e.EXAM_CYCLE_ID) && e.DEPARTMENT_ID.Value == DepartmentID.Value);
                if (modelDepInfo == null)
                {
                    var dep = listAllDeps.FirstOrDefault(e => e.ID == DepartmentID.Value);
                    if (dep != null && dep.PARENT_ID.HasValue)
                    {
                        DepartmentID = dep.PARENT_ID.Value;
                        return GetUserDepPostCycle(DepartmentID, iListHazardIDCycleID, iListPostIDCycleID, listAllDeps, listAllCycle, listAllCycleDepartmentInfo);//查询实体
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    return listAllCycle.First(e => e.ID == modelDepInfo.EXAM_CYCLE_ID);
                }
            }
        }

        #endregion
    }

    /// <summary>
    /// 员工健康监护档案
    /// </summary>
    public class HealthResult
    {
        public Guid ID { get; set; }
        public Guid? ORG_ID { get; set; }
        public string CODE { get; set; }
        public Guid? USER_ID { get; set; }
        public OHHealthExamResult RESULT_ENUM { get; set; }
        public string DESCRIPTION { get; set; }
        public string SUGGESTION { get; set; }
        public DateTime? CREATE_TIME { get; set; }
        public string NAME { get; set; }
        public string ID_CARD { get; set; }
        public DateTime? ENTRYTIME { get; set; }
        public Guid? DEPARTMENT_ID { get; set; }
        public string DEPARTMENTNAME { get; set; }
        public string POSTNAME { get; set; }
        public Guid? PERSON_ID { get; set; }
        public DateTime? DEPARTURETIME { get; set; }
        public Guid? OCC_DISEASE_SEVERITY_ID { get; set; }
        public Guid? OCC_DISEASE_ID { get; set; }
        public string disName { get; set; }
        public string disLevelName { get; set; }
        public string DIAGNOSE_AGENCY { get; set; }

        public string DisDESCRIPTION { get; set; }
        public string DIAGNOSE_METHOD { get; set; }
        public string OCC_HISTORY { get; set; }

        public ICollection<T_OH_HEALTH_EXAM_RESULT_OCC_DISEASE_FILE> Nav_Files { get; set; }
    }
}