using APT.BaseData.Domain.ApiModel.Platform;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.Enums.PF;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.BaseData.Services.Services.FM;
using APT.Infrastructure.Api.Redis;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.FO;
using APT.MS.Domain.Entities.SC.PE;
using APT.MS.Domain.Entities.SC.PM;
using APT.MS.Domain.Enums;
using APT.Utility;
using Castle.Core.Internal;
using Google.Protobuf.WellKnownTypes;
using InfluxData.Net.InfluxDb.Models.Responses;
using Microsoft.AspNetCore.Mvc;
using MySqlX.XDevAPI.Common;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using static NPOI.HSSF.Record.UnicodeString;

namespace APT.SC.WebApi.Controllers.Api.PEController
{
    /// <summary>
    ///  安全标准化内部评价记录表
    /// </summary>
    [Route("api/PE/PESafetyEvaluationRecord")]
    public partial class SafetyEvaluationRecordController : AuthorizeApiController<T_PE_SAFETY_EVALUATION_RECORD>
    {
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="notificationTaskService"></param>
        public SafetyEvaluationRecordController(IPFCodeRuleService codeRuleService, IFMNotificationTaskService notificationTaskService, IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService)
        {
            CodeRuleService = codeRuleService;
            NotificationTaskService = notificationTaskService;
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService = approveCallBackService;
        }
        /// <summary>
        /// 新增/编辑
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_PE_SAFETY_EVALUATION_RECORD entity)
        {
            return SafeExecute(() =>
            {
                var details = entity.Nav_Details;
                var evaluationUser = entity.Nav_RecordUser;
                var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (entity.TaskID != Guid.Empty)
                {
                    var currTask = GetEntity<T_FM_NOTIFICATION_TASK>(t => t.ID == entity.TaskID);
                    if (currTask != null)
                    {
                        loginUserId = currTask.USER_ID;
                    }
                }
                entity.DEPARTMENT_ID = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == 0 && t.ID == (Guid)loginUserId)?.DEPARTMENT_ID;
                List<T_PE_SAFETY_EVALUATION_RECORD_METHOD> evaluationMethod = new List<T_PE_SAFETY_EVALUATION_RECORD_METHOD>();
                List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                T_FM_NOTIFICATION_TASK task = null;
                if (details != null && details.Any())
                {
                    details.ForEach(t =>
                    {
                        if (t.RESULT_SCORE > t.STANDARDIZED_SCORE)
                            this.ThrowError("040007");
                        t.ORG_ID = entity.ORG_ID; t.SAFETY_EVALUATION_RECORD_ID = entity.ID;
                        if (t.Nav_EvaluationMethod != null && t.Nav_EvaluationMethod.Any())
                        {
                            t.Nav_EvaluationMethod.ForEach(t1 =>
                            {
                                t1.ORG_ID = entity.ORG_ID; t1.SAFETY_EVALUATION_RECORD_DETAIL_ID = t.ID;
                                evaluationMethod.Add(t1);
                            });
                            t.Nav_EvaluationMethod = null;
                        }
                    });
                }
                if (evaluationUser != null && evaluationUser.Any())
                {
                    evaluationUser.ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID; t.SAFETY_EVALUATION_RECORD_ID = entity.ID;
                    });
                }
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    if (evaluationUser != null && evaluationUser.Any())
                    {
                        evaluationUser.ForEach(t =>
                        {
                            if (t.USER_ID == loginUserId && t.ROW_NO == 1)
                                t.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                        });
                    }
                    entity.STATUS = PFStandardStatus.Sign;
                    var loginUserGroup = evaluationUser.Where(t => t.USER_ID == loginUserId && t.ROW_NO == 1).Select(m => m.GROUP_NO).Distinct().ToList();
                    var userTemps = evaluationUser.Where(t => loginUserGroup.Contains(t.GROUP_NO) && t.USER_ID != loginUserId).ToList();
                    List<Guid> userIds = new List<Guid>();
                    List<string> userNames = new List<string>();
                    foreach (var temp in userTemps)
                    {
                        var isExsist = evaluationUser.Where(t => t.USER_ID == temp.USER_ID && t.GROUP_NO != temp.GROUP_NO && t.ROW_NO != 1 && t.DEAL_STATUS == FOUserShiftStatusEnum.待处理).ToList();
                        if (isExsist != null && isExsist.Any())
                        {
                            var isExsistGroup = isExsist.Select(t => t.GROUP_NO).Distinct().ToList();
                            var idDeal = evaluationUser.Where(t => isExsistGroup.Contains(t.GROUP_NO) && t.ROW_NO == 1 && t.DEAL_STATUS == FOUserShiftStatusEnum.已处理).ToList();
                            if (isExsistGroup.Count == idDeal.Count)
                                userIds.Add(temp.USER_ID.Value);
                            //var isSend = true;
                            //foreach (var exsist in isExsist)
                            //{
                            //    var idDeal = evaluationUser.FirstOrDefault(t => t.GROUP_NO == exsist.GROUP_NO && t.ROW_NO == 1 && t.DEAL_STATUS == FOUserShiftStatusEnum.已处理);
                            //    if (idDeal == null)
                            //        isSend = false;
                            //} 
                            //if(isSend)
                            //    userIds.Add(temp.USER_ID.Value);
                        }
                        else
                        {
                            userIds.Add(temp.USER_ID.Value);
                        }
                    }
                    userIds = userIds.Distinct().ToList();
                    //var userIds = evaluationUser.Where(t => t.GROUP_NO == loginUser.GROUP_NO && t.USER_ID != loginUserId).Select(t => t.USER_ID.Value).Distinct().ToList();
                    if (userIds != null && userIds.Any())
                    {
                        var users = this.GetEntities<T_FM_USER>(t => userIds.Contains(t.ID) && t.ENABLE_STATUS == 0, new BaseFilter(entity.ORG_ID)).ToList();
                        foreach (var user in users)
                        {
                            userNames.Add(user.NAME);
                        }
                        //发消息
                        notices = NotificationTaskService.InsertUserNoticeTaskModels("安全标准化内部评价记录表-确认", entity.ID, entity.ORG_ID, userIds, userNames, DateTime.Now,
                        DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "PE030_SHOWPRINT");
                    }
                    else
                    {

                    }
                    if (entity.TaskID != Guid.Empty)
                    {
                        task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                        task.SOURCE_FORMCODE = "PE029_SHOWPRINT";
                    }
                }
                entity.Nav_Details = null;
                entity.Nav_RecordUser = null;
                UnifiedCommit(() =>
                {
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (details != null && details.Any())
                        this.BantchSaveEntityNoCommit(details);
                    if (evaluationUser != null && evaluationUser.Any())
                        this.BantchSaveEntityNoCommit(evaluationUser);
                    if (evaluationMethod != null && evaluationMethod.Any())
                        this.BantchSaveEntityNoCommit(evaluationMethod);
                    if (notices != null && notices.Any())
                        this.BantchSaveEntityNoCommit(notices);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                });
                return true;
            });
        }

        /// <summary>
        /// 新增/编辑
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdateNew")]
        public JsonActionResult<bool> FullUpdateNew([FromBody] T_PE_SAFETY_EVALUATION_RECORD entity)
        {
            return SafeExecute(() =>
            {
                var details = entity.Nav_Details;
                var evaluationUser = entity.Nav_RecordUser;
                var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (entity.TaskID != Guid.Empty)
                {
                    var currTask = GetEntity<T_FM_NOTIFICATION_TASK>(t => t.ID == entity.TaskID);
                    if (currTask != null)
                    {
                        loginUserId = currTask.USER_ID;
                    }
                }
                entity.DEPARTMENT_ID = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == 0 && t.ID == (Guid)loginUserId)?.DEPARTMENT_ID;
                List<T_PE_SAFETY_EVALUATION_RECORD_METHOD> evaluationMethod = new List<T_PE_SAFETY_EVALUATION_RECORD_METHOD>();
                List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                T_FM_NOTIFICATION_TASK task = null;
                if (details != null && details.Any())
                {
                    details.ForEach(t =>
                    {
                        if (t.RESULT_SCORE > t.STANDARDIZED_SCORE)
                            this.ThrowError("040007");
                        if (t.RESULT_SCORE < t.STANDARDIZED_SCORE && string.IsNullOrEmpty(t.NON_CONFORMANCE))
                            this.ThrowError("实得分小于标准分，必须填写不符合说明");
                        if (t.RESULT_SCORE < t.STANDARDIZED_SCORE)
                            t.EVALUATION_RESULT = PEEvaluationResultEnum.NoConform;
                        else
                            t.EVALUATION_RESULT = PEEvaluationResultEnum.Conform;
                        t.ORG_ID = entity.ORG_ID; t.SAFETY_EVALUATION_RECORD_ID = entity.ID;
                        if (t.Nav_EvaluationMethod != null && t.Nav_EvaluationMethod.Any())
                        {
                            t.Nav_EvaluationMethod.ForEach(t1 =>
                            {
                                t1.ORG_ID = entity.ORG_ID; t1.SAFETY_EVALUATION_RECORD_DETAIL_ID = t.ID;
                                evaluationMethod.Add(t1);
                            });
                            t.Nav_EvaluationMethod = null;
                        }
                    });
                }
                if (evaluationUser != null && evaluationUser.Any())
                {
                    evaluationUser.ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID; t.SAFETY_EVALUATION_RECORD_ID = entity.ID;
                    });
                }
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    if (evaluationUser != null && evaluationUser.Any())
                    {
                        evaluationUser.ForEach(t =>
                        {
                            if (t.USER_ID == loginUserId)
                                t.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                        });
                    }
                    entity.STATUS = PFStandardStatus.Sign;
                    //var loginUserGroup = evaluationUser.Where(t => t.USER_ID == loginUserId && t.ROW_NO == 1).Select(m => m.GROUP_NO).Distinct().ToList();
                    //var userTemps = evaluationUser.Where(t => loginUserGroup.Contains(t.GROUP_NO) && t.USER_ID != loginUserId).ToList();
                    List<Guid> userIds = evaluationUser.Where(t => t.USER_ID != loginUserId).Select(m => (Guid)m.USER_ID).Distinct().ToList();
                    List<string> userNames = new List<string>();
                    //foreach (var temp in userTemps)
                    //{
                    //    var isExsist = evaluationUser.Where(t => t.USER_ID == temp.USER_ID && t.GROUP_NO != temp.GROUP_NO && t.ROW_NO != 1 && t.DEAL_STATUS == FOUserShiftStatusEnum.待处理).ToList();
                    //    if (isExsist != null && isExsist.Any())
                    //    {
                    //        var isExsistGroup = isExsist.Select(t => t.GROUP_NO).Distinct().ToList();
                    //        var idDeal = evaluationUser.Where(t => isExsistGroup.Contains(t.GROUP_NO) && t.ROW_NO == 1 && t.DEAL_STATUS == FOUserShiftStatusEnum.已处理).ToList();
                    //        if (isExsistGroup.Count == idDeal.Count)
                    //            userIds.Add(temp.USER_ID.Value);
                    //        //var isSend = true;
                    //        //foreach (var exsist in isExsist)
                    //        //{
                    //        //    var idDeal = evaluationUser.FirstOrDefault(t => t.GROUP_NO == exsist.GROUP_NO && t.ROW_NO == 1 && t.DEAL_STATUS == FOUserShiftStatusEnum.已处理);
                    //        //    if (idDeal == null)
                    //        //        isSend = false;
                    //        //} 
                    //        //if(isSend)
                    //        //    userIds.Add(temp.USER_ID.Value);
                    //    }
                    //    else
                    //    {
                    //        userIds.Add(temp.USER_ID.Value);
                    //    }
                    //}
                    //userIds = userIds.Distinct().ToList();
                    //var userIds = evaluationUser.Where(t => t.GROUP_NO == loginUser.GROUP_NO && t.USER_ID != loginUserId).Select(t => t.USER_ID.Value).Distinct().ToList();
                    if (userIds != null && userIds.Any())
                    {
                        var users = this.GetEntities<T_FM_USER>(t => userIds.Contains(t.ID) && t.ENABLE_STATUS == 0, new BaseFilter(entity.ORG_ID)).ToList();
                        foreach (var user in users)
                        {
                            userNames.Add(user.NAME);
                        }
                        //发消息
                        notices = NotificationTaskService.InsertUserNoticeTaskModels("安全标准化内部评价记录表-确认", entity.ID, entity.ORG_ID, userIds, userNames, DateTime.Now,
                        DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "PE029_SHOWPRINT");
                    }
                    else
                    {
                        entity.STATUS = PFStandardStatus.Archived;
                        var records = this.GetEntities<T_PE_SAFETY_EVALUATION_RECORD>(t => t.EVALUATION_PLAN_ID == entity.EVALUATION_PLAN_ID && t.ID != entity.ID, new BaseFilter(entity.ORG_ID), "Nav_RecordUser");
                        bool send = true;
                        foreach (var item in records)
                        {
                            if (item.Nav_RecordUser != null && item.Nav_RecordUser.Any())
                            {
                                item.Nav_RecordUser.ForEach(t =>
                                {
                                    if (t.DEAL_STATUS == FOUserShiftStatusEnum.待处理)
                                        send = false;
                                });
                            }
                        }
                        if (send)
                        {
                            //entity.STATUS = PFStandardStatus.Approving;
                            //取审批流水码
                            var sysFilter = new SystemCodeFilter();
                            sysFilter.CodeType = (int)PFCodeRuleType.审批流编码;
                            sysFilter.Count = 1;
                            sysFilter.OrgId = entity.ORG_ID;
                            var codes = CodeRuleService.NewGenSerial(sysFilter);
                            var serialCode = codes.Split(new char[] { ',' });
                            entity.Nav_Details = null;
                            entity.Nav_RecordUser = null;
                            MFlowPermitService.InsertApprove(serialCode[0], "PE029", "", entity.ID, "PE030_SHOWPRINT", entity.TaskID, true, () =>
                            {
                                if (entity != null)
                                    this.UpdateEntityNoCommit(entity);
                                if (details != null && details.Any())
                                    this.BantchSaveEntityNoCommit(details);
                                if (evaluationUser != null && evaluationUser.Any())
                                    this.BantchSaveEntityNoCommit(evaluationUser);
                                if (evaluationMethod != null && evaluationMethod.Any())
                                    this.BantchSaveEntityNoCommit(evaluationMethod);
                                if (notices != null && notices.Any())
                                    this.BantchSaveEntityNoCommit(notices);
                                if (task != null)
                                    this.UpdateEntityNoCommit(task);
                            }, null, null, null, null, null, "PE029_SHOWPRINT", null);
                            return true;
                        }
                    }
                    if (entity.TaskID != Guid.Empty)
                    {
                        task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                        task.SOURCE_FORMCODE = "PE029_SHOWPRINT";
                    }
                }
                entity.Nav_Details = null;
                entity.Nav_RecordUser = null;
                UnifiedCommit(() =>
                {
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (details != null && details.Any())
                        this.BantchSaveEntityNoCommit(details);
                    if (evaluationUser != null && evaluationUser.Any())
                        this.BantchSaveEntityNoCommit(evaluationUser);
                    if (evaluationMethod != null && evaluationMethod.Any())
                        this.BantchSaveEntityNoCommit(evaluationMethod);
                    if (notices != null && notices.Any())
                        this.BantchSaveEntityNoCommit(notices);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                });
                return true;
            });
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetUserEdit")]
        public JsonActionResult<T_PE_SAFETY_EVALUATION_RECORD> GetUserEdit([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                if (string.IsNullOrEmpty(id))
                    this.ThrowError("030017");
                var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var result = this.GetEntity<T_PE_SAFETY_EVALUATION_RECORD>(id, new string[] {"Nav_EvaluationPlan","Nav_RecordUser","Nav_RecordUser.Nav_User",
            "Nav_Details","Nav_Details.Nav_ProductionUnit","Nav_Details.Nav_Primary","Nav_Details.Nav_Second","Nav_Details.Nav_Three",
                    "Nav_Details.Nav_EvaluationMethod","Nav_Details.Nav_EvaluationMethod.Nav_Method"});
                if (result != null && result.Nav_Details != null && result.Nav_Details.Any())
                {
                    var plan = this.GetEntity<T_PE_SAFETY_EVALUATION_PLAN>(t => t.ID == result.EVALUATION_PLAN_ID, new string[] { "Nav_Details", "Nav_Details.Nav_EvaluationUser" });
                    var evaPlanStandarized = plan.Nav_Details.Where(t => t.Nav_EvaluationUser != null).Where(c => c.Nav_EvaluationUser.FirstOrDefault(m => m.USER_ID == loginUserId && m.ROW_NO == 1)?.USER_ID == loginUserId).Select(i => i.STANDARDIZED_ID).ToList();
                    result.Nav_Details = result.Nav_Details.Where(t => evaPlanStandarized.Contains(t.PRIMARY_ELEMENTS_ID)).OrderBy(n => n.PRODUCTION_UNIT_ID).ThenBy(i => i.PRIMARY_ELEMENTS_ID).ThenBy(m => m.SECOND_ELEMENTS_ID).ToList();
                    result.STAND_TOTAL = result.Nav_Details.Sum(t => t.STANDARDIZED_SCORE + t.NON_STANDARDIZED_SCORE).Value.ToString();
                    result.RESULT_TOTAL = result.Nav_Details.Sum(t => t.RESULT_SCORE).Value.ToString();
                }
                if (result != null && result.Nav_RecordUser != null && result.Nav_RecordUser.Any())
                {
                    result.Nav_IngoreUser = result.Nav_RecordUser.Distinct(t => t.USER_ID).ToList();
                }
                return result;
            });
        }
        /// <summary>
        /// 签字人员获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetIdentityUserEdit")]
        public JsonActionResult<T_PE_SAFETY_EVALUATION_RECORD> GetIdentityUserEdit([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                if (string.IsNullOrEmpty(id))
                    this.ThrowError("030017");
                var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var result = this.GetEntity<T_PE_SAFETY_EVALUATION_RECORD>(id, new string[] {"Nav_EvaluationPlan","Nav_RecordUser","Nav_RecordUser.Nav_User",
            "Nav_Details","Nav_Details.Nav_ProductionUnit","Nav_Details.Nav_Primary","Nav_Details.Nav_Second","Nav_Details.Nav_Three",
                    "Nav_Details.Nav_EvaluationMethod","Nav_Details.Nav_EvaluationMethod.Nav_Method"});
                if (result != null && result.Nav_Details != null && result.Nav_Details.Any())
                {
                    var plan = this.GetEntity<T_PE_SAFETY_EVALUATION_PLAN>(t => t.ID == result.EVALUATION_PLAN_ID, new string[] { "Nav_Details", "Nav_Details.Nav_EvaluationUser" });
                    var evaPlanStandarized = plan.Nav_Details.Where(t => t.Nav_EvaluationUser != null).Where(c => c.Nav_EvaluationUser.FirstOrDefault(m => m.USER_ID == loginUserId && m.ROW_NO != 1)?.USER_ID == loginUserId).Select(i => i.STANDARDIZED_ID).ToList();
                    result.Nav_Details = result.Nav_Details.Where(t => evaPlanStandarized.Contains(t.PRIMARY_ELEMENTS_ID)).OrderBy(n => n.PRODUCTION_UNIT_ID).ThenBy(i => i.PRIMARY_ELEMENTS_ID).ThenBy(m => m.SECOND_ELEMENTS_ID).ToList();
                    result.STAND_TOTAL = result.Nav_Details.Sum(t => t.STANDARDIZED_SCORE + t.NON_STANDARDIZED_SCORE).Value.ToString();
                    result.RESULT_TOTAL = result.Nav_Details.Sum(t => t.RESULT_SCORE).Value.ToString();
                }
                if (result != null && result.Nav_RecordUser != null && result.Nav_RecordUser.Any())
                {
                    result.Nav_IngoreUser = result.Nav_RecordUser.Distinct(t => t.USER_ID).ToList();
                }
                return result;
            });
        }

        /// <summary>
        /// 签字人员获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetIdentityUserEditNew")]
        public JsonActionResult<T_PE_SAFETY_EVALUATION_RECORD> GetIdentityUserEditNew([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                if (string.IsNullOrEmpty(id))
                    this.ThrowError("030017");
                var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var result = this.GetEntity<T_PE_SAFETY_EVALUATION_RECORD>(id, new string[] {"Nav_RecordUser","Nav_RecordUser.Nav_User",
            "Nav_Details","Nav_Details.Nav_ProductionUnit","Nav_Details.Nav_Primary","Nav_Details.Nav_Second","Nav_Details.Nav_Three",
                    "Nav_Details.Nav_EvaluationMethod","Nav_Details.Nav_EvaluationMethod.Nav_Method"});
                if (result != null && result.Nav_Details != null && result.Nav_Details.Any())
                {
                    //var plan = this.GetEntity<T_PE_SAFETY_EVALUATION_PLAN>(t => t.ID == result.EVALUATION_PLAN_ID, new string[] { "Nav_Details", "Nav_Details.Nav_EvaluationUser" });
                    //var evaPlanStandarized = plan.Nav_Details.Where(t => t.Nav_EvaluationUser != null).Where(c => c.Nav_EvaluationUser.FirstOrDefault(m => m.USER_ID == loginUserId && m.ROW_NO != 1)?.USER_ID == loginUserId).Select(i => i.STANDARDIZED_ID).ToList();
                    result.Nav_Details = result.Nav_Details.OrderBy(n => n.NUM).ToList();
                    //OrderBy(n => n.PRODUCTION_UNIT_ID).ThenBy(i => i.PRIMARY_ELEMENTS_ID).ThenBy(m => m.SECOND_ELEMENTS_ID).ToList();
                    result.STAND_TOTAL = result.Nav_Details.Sum(t => t.STANDARDIZED_SCORE + t.NON_STANDARDIZED_SCORE).Value.ToString();
                    result.RESULT_TOTAL = result.Nav_Details.Sum(t => t.RESULT_SCORE).Value.ToString();
                }
                if (result != null && result.Nav_RecordUser != null && result.Nav_RecordUser.Any())
                {
                    result.Nav_IngoreUser = result.Nav_RecordUser.Distinct(t => t.USER_ID).ToList();
                }
                return result;
            });
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetEdit")]
        public JsonActionResult<T_PE_SAFETY_EVALUATION_RECORD> GetEdit([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                if (string.IsNullOrEmpty(id))
                    this.ThrowError("030017");
                var result = this.GetEntity<T_PE_SAFETY_EVALUATION_RECORD>(id, new string[] {"Nav_RecordUser","Nav_RecordUser.Nav_User","Nav_EvaluationPlan",
            "Nav_Details","Nav_Details.Nav_ProductionUnit","Nav_Details.Nav_Primary","Nav_Details.Nav_Second","Nav_Details.Nav_Three",
                    "Nav_Details.Nav_EvaluationMethod","Nav_Details.Nav_EvaluationMethod.Nav_Method"});
                if (result != null && result.Nav_Details != null && result.Nav_Details.Any())
                {
                    result.Nav_Details.ForEach(t => t.STANDARDIZED_SCORE = t.STANDARDIZED_SCORE > 0 ? t.STANDARDIZED_SCORE : t.NON_STANDARDIZED_SCORE);
                    result.Nav_Details = result.Nav_Details.OrderBy(n => n.NUM).ToList();
                    //OrderBy(n => n.PRODUCTION_UNIT_ID).ThenBy(i => i.PRIMARY_ELEMENTS_ID).ThenBy(m => m.SECOND_ELEMENTS_ID).ToList();
                    result.STAND_TOTAL = result.Nav_Details.Sum(t => t.STANDARDIZED_SCORE).Value.ToString();
                    result.RESULT_TOTAL = result.Nav_Details.Sum(t => t.RESULT_SCORE).Value.ToString();
                }
                if (result != null && result.Nav_RecordUser != null && result.Nav_RecordUser.Any())
                {
                    result.Nav_IngoreUser = result.Nav_RecordUser.OrderBy(m => m.ROW_NO).Distinct(t => t.USER_ID).ToList();
                }
                return result;
            });
        }
        /// <summary>
        /// 识别人确认
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("IdentityUpdate")]
        public JsonActionResult<bool> IdentityUpdate([FromBody] T_PE_SAFETY_EVALUATION_RECORD entity)
        {
            return SafeExecute(() =>
            {
                T_FM_NOTIFICATION_TASK task = null;
                var record = this.GetEntity<T_PE_SAFETY_EVALUATION_RECORD>(entity.ID, "Nav_RecordUser");
                var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (entity.TaskID != Guid.Empty)
                {
                    var currTask = GetEntity<T_FM_NOTIFICATION_TASK>(t => t.ID == entity.TaskID);
                    if (currTask != null)
                    {
                        userId = currTask.USER_ID;
                    }
                }
                var users = this.GetEntities<T_PE_SAFETY_EVALUATION_RECORD_USER>(t => t.SAFETY_EVALUATION_RECORD_ID == record.ID && t.USER_ID == userId && t.ROW_NO != 1, new BaseFilter(record.ORG_ID)).ToList();
                users.ForEach(t =>
                {
                    t.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                });
                var todoCount = this.GetCount<T_PE_SAFETY_EVALUATION_RECORD_USER>(t => t.SAFETY_EVALUATION_RECORD_ID == entity.ID && t.USER_ID != userId && t.DEAL_STATUS == 0, new BaseFilter(record.ORG_ID));
                if (todoCount == 0)
                {
                    //var taskCount= this.GetCount<T_FM_NOTIFICATION_TASK>(t => t.SOURCE_DATA_ID == record.ID && t.NOTICE_STATUS == 0, new BaseFilter(record.ORG_ID));
                    //if (taskCount == 0)
                    //{
                    record.STATUS = PFStandardStatus.Approving;
                    //取审批流水码
                    var sysFilter = new SystemCodeFilter();
                    sysFilter.CodeType = (int)PFCodeRuleType.审批流编码;
                    sysFilter.Count = 1;
                    sysFilter.OrgId = record.ORG_ID;
                    var codes = CodeRuleService.NewGenSerial(sysFilter);
                    var serialCode = codes.Split(new char[] { ',' });
                    MFlowPermitService.InsertApprove(serialCode[0], "PE029", "", entity.ID, "PE029_SHOWPRINT_NEW", entity.TaskID, true, () =>
                    {
                        if (record != null)
                            this.UpdateEntityNoCommit(record);
                        if (users != null && users.Any())
                            this.BantchSaveEntityNoCommit(users);
                        if (task != null)
                            this.UpdateEntityNoCommit(task);
                    }, null, null, null, null, null, "PE030_SHOWPRINT", null);
                    return true;
                    //}
                }
                if (entity.TaskID != Guid.Empty)
                {
                    task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                    task.SOURCE_FORMCODE = "PE030_SHOWPRINT";
                }
                UnifiedCommit(() =>
                {
                    if (record != null)
                        this.UpdateEntityNoCommit(record);
                    if (users != null && users.Any())
                        this.BantchSaveEntityNoCommit(users);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                });
                return true;
            });
        }

        /// <summary>
        /// 识别人确认
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("IdentityUpdateNew")]
        public JsonActionResult<bool> IdentityUpdateNew([FromBody] T_PE_SAFETY_EVALUATION_RECORD entity)
        {
            return SafeExecute(() =>
            {
                T_FM_NOTIFICATION_TASK task = null;
                var record = this.GetEntity<T_PE_SAFETY_EVALUATION_RECORD>(entity.ID, "Nav_RecordUser");
                var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (entity.TaskID != Guid.Empty)
                {
                    var currTask = GetEntity<T_FM_NOTIFICATION_TASK>(t => t.ID == entity.TaskID);
                    if (currTask != null)
                    {
                        userId = currTask.USER_ID;
                    }
                }
                var users = this.GetEntities<T_PE_SAFETY_EVALUATION_RECORD_USER>(t => t.SAFETY_EVALUATION_RECORD_ID == record.ID && t.USER_ID == userId, new BaseFilter(record.ORG_ID)).ToList();
                users.ForEach(t =>
                {
                    t.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                });
                var otherRecord = this.GetEntities<T_PE_SAFETY_EVALUATION_RECORD>(t => t.EVALUATION_PLAN_ID == record.EVALUATION_PLAN_ID && t.ID != record.ID, new BaseFilter(record.ORG_ID), "Nav_RecordUser");
                var i = 0;
                if (otherRecord != null && otherRecord.Any())
                {
                    foreach (var item in otherRecord)
                    {
                        if (item.Nav_RecordUser.Any())
                        {
                            foreach (var user in item.Nav_RecordUser)
                            {
                                if (user.DEAL_STATUS == 0)
                                    i++;
                            }
                        }
                    }
                }
                var todoCount = this.GetCount<T_PE_SAFETY_EVALUATION_RECORD_USER>(t => t.SAFETY_EVALUATION_RECORD_ID == entity.ID && t.USER_ID != userId && t.DEAL_STATUS == 0, new BaseFilter(record.ORG_ID));
                if (todoCount == 0)
                {
                    record.STATUS = PFStandardStatus.Archived;
                    if (i == 0)
                    {
                        //取审批流水码
                        var sysFilter = new SystemCodeFilter();
                        sysFilter.CodeType = (int)PFCodeRuleType.审批流编码;
                        sysFilter.Count = 1;
                        sysFilter.OrgId = record.ORG_ID;
                        var codes = CodeRuleService.NewGenSerial(sysFilter);
                        var serialCode = codes.Split(new char[] { ',' });
                        MFlowPermitService.InsertApprove(serialCode[0], "PE029", "", entity.ID, "PE030_SHOWPRINT", entity.TaskID, true, () =>
                        {
                            if (record != null)
                                this.UpdateEntityNoCommit(record);
                            if (users != null && users.Any())
                                this.BantchSaveEntityNoCommit(users);
                            if (task != null)
                                this.UpdateEntityNoCommit(task);
                        }, null, null, null, null, null, "PE029_SHOWPRINT", null);
                        return true;
                    }
                }
                if (entity.TaskID != Guid.Empty)
                {
                    task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                    task.SOURCE_FORMCODE = "PE029_SHOWPRINT";
                }
                UnifiedCommit(() =>
                {
                    if (record != null)
                        this.UpdateEntityNoCommit(record);
                    if (users != null && users.Any())
                        this.BantchSaveEntityNoCommit(users);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                });
                return true;
            });
        }
        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("BackUpdate")]
        public JsonActionResult<bool> BackUpdate(string id)
        {
            return SafeExecute(() =>
            {
                return ApproveCallBackService.CallBack("PE/PESafetyEvaluationRecord/BackUpdate", id);
            });
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("HomeGetOld")]
        public JsonActionResult<T_PE_SAFETY_EVALUATION_RECORD> HomeGetOld([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var result = new T_PE_SAFETY_EVALUATION_RECORD();
                if (!string.IsNullOrEmpty(filter.Keyword))
                {
                    var minetype = filter.Keyword.Split(",")[0];
                    var name = "露天矿";
                    switch (minetype)
                    {
                        case "10":
                            name = "选矿";
                            break;
                        case "20":
                            name = "尾矿";
                            break;
                        case "30":
                            name = "露天矿";
                            break;
                        default:
                            name = "露天矿";
                            break;
                    }
                    result = this.GetEntity<T_PE_SAFETY_EVALUATION_RECORD>(t => t.Nav_EvaluationPlan != null && t.Nav_EvaluationPlan.Nav_ProductionUnit != null && t.Nav_EvaluationPlan.Nav_ProductionUnit.NAME == name && t.Nav_EvaluationPlan.YEAR == DateTime.Now.Year.ToString(), new string[] {"Nav_RecordUser","Nav_RecordUser.Nav_User",
            "Nav_Details","Nav_Details.Nav_ProductionUnit","Nav_Details.Nav_Primary","Nav_Details.Nav_Second","Nav_Details.Nav_Three",
                    "Nav_Details.Nav_EvaluationMethod","Nav_Details.Nav_EvaluationMethod.Nav_Method"});
                    if (result != null && result.Nav_Details != null && result.Nav_Details.Any())
                    {
                        result.Nav_Details.ForEach(t => t.STANDARDIZED_SCORE = t.STANDARDIZED_SCORE > 0 ? t.STANDARDIZED_SCORE : t.NON_STANDARDIZED_SCORE);
                        result.Nav_Details = result.Nav_Details.OrderBy(n => n.PRODUCTION_UNIT_ID).ThenBy(i => i.PRIMARY_ELEMENTS_ID).ThenBy(m => m.SECOND_ELEMENTS_ID).ToList();
                        result.STAND_TOTAL = result.Nav_Details.Sum(t => t.STANDARDIZED_SCORE).Value.ToString();
                        result.RESULT_TOTAL = result.Nav_Details.Sum(t => t.RESULT_SCORE).Value.ToString();
                        var item = new T_PE_SAFETY_EVALUATION_RECORD_DETAIL();
                        item.CONTENTS = "共计";
                        item.STANDARDIZED_SCORE = result.STAND_TOTAL.ToString() == "" ? 1 : decimal.Parse(result.STAND_TOTAL);
                        item.RESULT_SCORE = result.RESULT_TOTAL.ToString() == "" ? 0 : decimal.Parse(result.RESULT_TOTAL);
                        result.Nav_Details.Add(item);
                    }
                    if (result != null && result.Nav_RecordUser != null && result.Nav_RecordUser.Any())
                    {
                        result.Nav_IngoreUser = result.Nav_RecordUser.Distinct(t => t.USER_ID).ToList();
                    }
                }
                return result;
            });
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("HomeGet")]
        public JsonActionResult<T_PE_SAFETY_EVALUATION_RECORD> HomeGet([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var result = new T_PE_SAFETY_EVALUATION_RECORD();
                if (!string.IsNullOrEmpty(filter.Keyword))
                {
                    try
                    {
                        var minetype = filter.Keyword.Split(",")[0];

                        #region   判断 从Redis中获取数据  有就直接返回到前端 没有就按原来的进行搜索  最后再判断存入Redis中
                        int MineType = 30;
                        try
                        {
                            MineType = int.Parse(minetype);
                        }
                        catch
                        {
                            MineType = 30;
                        }
                        var redisCode = string.Format(RedisCacheKey.HomeEvaluationRecord, APT.Infrastructure.Api.AppContext.CurrentSession.OrgId);
                        DateTime dtNow = DateTime.Now;
                        bool isRedisConfig = true;
                        var redisConfig = APT.Infrastructure.Api.ConfigurationManager.AppSettings["RedisFormConfig"];
                        List<HomeResultMineType> listHomeRedis = null;
                        if (!string.IsNullOrEmpty(redisConfig))
                            isRedisConfig = bool.Parse(redisConfig);

                        if (isRedisConfig && CsRedisManager.KeyExists(redisCode))
                            listHomeRedis = CsRedisManager.StringGet<List<HomeResultMineType>>(redisCode);

                        if (listHomeRedis != null && listHomeRedis.Count() > 0)
                        {
                            foreach (var item in listHomeRedis)
                            {
                                if (item.MineType == MineType)
                                {
                                    if (dtNow.ToString("yyyyMMddHH") == item.yyyyMMddHH)
                                    {
                                        result = item.result;
                                    }
                                    else
                                    {
                                        listHomeRedis.Remove(item);//Key不匹配 过期数据删除
                                    }
                                    break;
                                }
                            }
                        }

                        //redis获取到了数据
                        if (result != null && (!string.IsNullOrEmpty(result.RESULT_TOTAL) || !string.IsNullOrEmpty(result.RESULT_TOTAL)))
                        {
                            return result;
                        }

                        #endregion

                        var name = "露天矿";
                        List<EnumsResult> enums = DataHelper.GetEnum("FMProductionUnit");
                        if (!string.IsNullOrEmpty(minetype))
                        {
                            name = enums.FirstOrDefault(t => t.ID == int.Parse(minetype))?.NAME;
                        }
                        if (string.IsNullOrEmpty(name))
                        {
                            name = "露天矿";
                        }
                        //List<string> listName = new List<string>();
                        //List<int> listVal = new List<int>();
                        //foreach (var item in enums)
                        //{
                        //    listVal.Add(item.ID);
                        //    listName.Add(item.NAME);
                        //}
                        //var name = "露天矿";
                        //switch (minetype)
                        //{
                        //    case "10":
                        //        name = "选矿厂";
                        //        break;
                        //    case "20":
                        //        name = "尾矿库";
                        //        break;
                        //    case "30":
                        //        name = "露天矿";
                        //        break;
                        //    default:
                        //        name = "露天矿";
                        //        break;
                        //}
                        var newFilter = new BaseFilter(filter.OrgId);
                        newFilter.SelectField = new List<string> { "ID", "EVALUATION_PLAN_ID", "STATUS", "Nav_EvaluationPlan", "Nav_EvaluationPlan.YEAR", "Nav_EvaluationPlan.Nav_ProductionUnit", "Nav_EvaluationPlan.Nav_ProductionUnit.NAME" };
                        result = this.GetEntity<T_PE_SAFETY_EVALUATION_RECORD>(t => t.STATUS == PFStandardStatus.Archived && t.Nav_EvaluationPlan != null && t.Nav_EvaluationPlan.Nav_ProductionUnit != null && t.Nav_EvaluationPlan.Nav_ProductionUnit.NAME == name && t.Nav_EvaluationPlan.YEAR == DateTime.Now.Year.ToString(), newFilter);
                        if (result == null)
                        {
                            var results = this.GetEntities<T_PE_SAFETY_EVALUATION_RECORD>(t => t.STATUS == PFStandardStatus.Archived && t.Nav_EvaluationPlan != null && t.Nav_EvaluationPlan.Nav_ProductionUnit != null && t.Nav_EvaluationPlan.Nav_ProductionUnit.NAME == name, newFilter).OrderByDescending(t => t.CREATE_TIME);
                            result = results.FirstOrDefault();
                        }
                        if (result != null)
                        {
                            var records = this.GetEntities<T_PE_SAFETY_EVALUATION_RECORD>(t => t.EVALUATION_PLAN_ID == result.EVALUATION_PLAN_ID, new BaseFilter(result.ORG_ID));
                            if (records != null && records.Any())
                            {
                                var recordIds = records.Where(t => t.STATUS == PFStandardStatus.Archived).Select(record => record.ID).ToList();
                                var recordDetails = this.GetEntities<T_PE_SAFETY_EVALUATION_RECORD_DETAIL>(t => recordIds.Contains((Guid)t.SAFETY_EVALUATION_RECORD_ID), new BaseFilter(result.ORG_ID), "Nav_ProductionUnit", "Nav_Primary", "Nav_Second", "Nav_Three", "Nav_EvaluationMethod.Nav_Method");
                                result.Nav_Details = recordDetails.ToList();
                                var recordUsers = this.GetEntities<T_PE_SAFETY_EVALUATION_RECORD_USER>(t => recordIds.Contains((Guid)t.SAFETY_EVALUATION_RECORD_ID), new BaseFilter(result.ORG_ID), "Nav_User");
                                result.Nav_RecordUser = recordUsers.ToList();
                                result.Nav_Details.ForEach(t =>
                                {
                                    t.STANDARDIZED_SCORE = t.STANDARDIZED_SCORE > 0 ? t.STANDARDIZED_SCORE : t.NON_STANDARDIZED_SCORE;
                                    t.NON_STANDARDIZED_SCORE = t.STANDARDIZED_SCORE - t.RESULT_SCORE;
                                });
                                result.Nav_Details = result.Nav_Details.OrderBy(n => n.NUM).ToList();
                                var tempStand = result.Nav_Details.Sum(t => t.STANDARDIZED_SCORE).Value;
                                result.STAND_TOTAL = tempStand.ToString();
                                var tempResult = result.Nav_Details.Sum(t => t.RESULT_SCORE).Value;
                                result.RESULT_TOTAL = tempResult.ToString();
                                result.NON_STANDARDIZED_SCORE = (tempStand - tempResult).ToString();
                                var allRecordIds = records.Select(record => record.ID).ToList();
                                var approveInfo = this.GetEntity<T_PF_APPROVE>(t => allRecordIds.Contains((Guid)t.DATA_ID) && t.APPROVE_STATUS != 10);
                                if (approveInfo != null)
                                    allRecordIds.Add(approveInfo.ID);
                                var taskInfo = this.GetEntity<T_FM_NOTIFICATION_TASK>(t => allRecordIds.Contains((Guid)t.SOURCE_DATA_ID) && t.NOTICE_STATUS == 0 && t.NOTICE_TYPE != 2);
                                if (taskInfo == null)
                                    result.STANDARDIZED_RESULT = tempStand == 0 ? "0" : (tempResult / tempStand * 100).ToString("#0.00");
                                else
                                    result.STANDARDIZED_RESULT = "0";
                            }
                            var ingoreDetailTemps = new List<T_PE_SAFETY_EVALUATION_RECORD_DETAIL>();
                            var ingoreDetails = result.Nav_Details.GroupBy(t => t.PRODUCTION_UNIT_ID);
                            foreach (var detail in ingoreDetails)
                            {
                                var itemDetail = new T_PE_SAFETY_EVALUATION_RECORD_DETAIL();
                                var firstDetail = result.Nav_Details.FirstOrDefault(t => t.PRODUCTION_UNIT_ID == detail.Key.Value);
                                itemDetail.Nav_ProductionUnit = firstDetail?.Nav_ProductionUnit;
                                itemDetail.PRODUCTION_UNIT_ID = firstDetail?.PRODUCTION_UNIT_ID;
                                itemDetail.STANDARDIZED_SCORE = result.Nav_Details.Where(t => t.PRODUCTION_UNIT_ID == detail.Key.Value).Sum(m => m.STANDARDIZED_SCORE);
                                itemDetail.RESULT_SCORE = result.Nav_Details.Where(t => t.PRODUCTION_UNIT_ID == detail.Key.Value).Sum(m => m.RESULT_SCORE);
                                itemDetail.NON_STANDARDIZED_SCORE = result.STANDARDIZED_RESULT == "0" ? 0 : Math.Round((decimal)itemDetail.RESULT_SCORE / (decimal)itemDetail.STANDARDIZED_SCORE * 100, 2);
                                ingoreDetailTemps.Add(itemDetail);
                            }
                            result.Nav_IngoreDetails = ingoreDetailTemps.OrderBy(n => n.NUM).ToList();
                            //var item = new T_PE_SAFETY_EVALUATION_RECORD_DETAIL();
                            //item.DESCRIPTION = "合计";
                            //item.STANDARDIZED_SCORE = result.STAND_TOTAL.ToString() == "" ? 1 : decimal.Parse(result.STAND_TOTAL);
                            //item.RESULT_SCORE = result.RESULT_TOTAL.ToString() == "" ? 0 : decimal.Parse(result.RESULT_TOTAL);
                            //item.NON_CONFORMANCE = "标准化得分:"+ Math.Round(((decimal)item.RESULT_SCORE / (decimal)item.STANDARDIZED_SCORE * 100),2);
                            //item.GROUP_NO = "合计扣分";
                            //item.NON_STANDARDIZED_SCORE = item.STANDARDIZED_SCORE - item.RESULT_SCORE;
                            //result.Nav_Details.Add(item);
                            //newFilter.SelectField = new List<string> { "ID", "USER_ID", "GROUP_NO", "ROW_NO", "Nav_User", "DEAL_STATUS" };
                            if (result != null && result.Nav_RecordUser != null && result.Nav_RecordUser.Any())
                            {
                                result.Nav_IngoreUser = result.Nav_RecordUser.Distinct(t => t.USER_ID).ToList();
                            }
                        }
                        else
                        {
                            var standImport = this.GetEntity<T_PE_STANDARDIZED_SCORE_IMPORT>(t => t.NAME == name);
                            if (standImport != null)
                            {
                                result = new T_PE_SAFETY_EVALUATION_RECORD();
                                result.RESULT_TOTAL = standImport.SCORE == null ? "0" : standImport.SCORE;
                                result.STAND_TOTAL = "100";
                                result.Nav_Details = new List<T_PE_SAFETY_EVALUATION_RECORD_DETAIL>();
                            }
                        }

                        #region    搜索结果 判断存入Redis中

                        if (isRedisConfig)
                        {
                            try
                            {
                                if (listHomeRedis == null)
                                    listHomeRedis = new List<HomeResultMineType>();

                                listHomeRedis.Add(new HomeResultMineType()
                                {
                                    MineType = MineType,
                                    yyyyMMddHH = dtNow.ToString("yyyyMMddHH"),
                                    result = result
                                });

                                CsRedisManager.StringSet<List<HomeResultMineType>>(redisCode, listHomeRedis);
                            }
                            catch { }
                        }

                        #endregion

                    }
                    catch { }
                }
                return result;
            });
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("HomeGetNew")]
        public JsonActionResult<T_PE_SAFETY_EVALUATION_RECORD> HomeGetNew([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var result = new T_PE_SAFETY_EVALUATION_RECORD();
                result.Nav_Details = new List<T_PE_SAFETY_EVALUATION_RECORD_DETAIL>();
                if (!string.IsNullOrEmpty(filter.Keyword))
                {
                    var minetype = filter.Keyword.Split(",")[0];
                    var name = "露天矿";
                    List<EnumsResult> enums = DataHelper.GetEnum("FMProductionUnit");
                    if (!string.IsNullOrEmpty(minetype))
                    {
                        name = enums.FirstOrDefault(t => t.ID == int.Parse(minetype))?.NAME;
                    }
                    if (string.IsNullOrEmpty(name))
                    {
                        name = "露天矿";
                    }
                    //List<string> listName = new List<string>();
                    //List<int> listVal = new List<int>();
                    //foreach (var item in enums)
                    //{
                    //    listVal.Add(item.ID);
                    //    listName.Add(item.NAME);
                    //}
                    //var name = "露天矿";
                    //switch (minetype)
                    //{
                    //    case "10":
                    //        name = "选矿厂";
                    //        break;
                    //    case "20":
                    //        name = "尾矿库";
                    //        break;
                    //    case "30":
                    //        name = "露天矿";
                    //        break;
                    //    default:
                    //        name = "露天矿";
                    //        break;
                    //}
                    var newFilter = new BaseFilter(filter.OrgId);
                    newFilter.SelectField = new List<string> { "ID", "EVALUATION_PLAN_ID", "STATUS", "Nav_EvaluationPlan", "Nav_EvaluationPlan.YEAR", "Nav_EvaluationPlan.Nav_ProductionUnit", "Nav_EvaluationPlan.Nav_ProductionUnit.NAME" };
                    result = this.GetEntity<T_PE_SAFETY_EVALUATION_RECORD>(t => t.STATUS == PFStandardStatus.Archived && t.Nav_EvaluationPlan != null && t.Nav_EvaluationPlan.Nav_ProductionUnit != null && t.Nav_EvaluationPlan.Nav_ProductionUnit.NAME == name && t.Nav_EvaluationPlan.YEAR == DateTime.Now.Year.ToString(), newFilter);
                    if (result == null)
                    {
                        result = this.GetEntity<T_PE_SAFETY_EVALUATION_RECORD>(t => t.STATUS == PFStandardStatus.Archived && t.Nav_EvaluationPlan != null && t.Nav_EvaluationPlan.Nav_ProductionUnit != null && t.Nav_EvaluationPlan.Nav_ProductionUnit.NAME == name && t.Nav_EvaluationPlan.YEAR == DateTime.Now.AddYears(-1).Year.ToString(), newFilter);
                    }
                    var importNames = this.GetEntities<T_PE_STANDARDIZED_SCORE_IMPORT>(null, new BaseFilter(filter.OrgId));
                    var standScoreAutos = this.GetEntities<T_PE_STANDARDIZED_SCORE_AUTO_DETAIL>(t => t.YEAR == DateTime.Now.Year.ToString() && t.PRODUCTION_UNIT == name, new BaseFilter(filter.OrgId));
                    if (standScoreAutos == null || !standScoreAutos.Any())
                    {
                        standScoreAutos = this.GetEntities<T_PE_STANDARDIZED_SCORE_AUTO_DETAIL>(t => t.YEAR == DateTime.Now.AddYears(-1).Year.ToString() && t.PRODUCTION_UNIT == name, new BaseFilter(filter.OrgId));
                    }
                    if (standScoreAutos.Any())
                    {
                        List<EnumsResult> enums2 = DataHelper.GetEnum("PEEvaluationItemEnum");
                        foreach (var item in standScoreAutos)
                        {
                            var productionUnit = importNames.FirstOrDefault(t => t.NAME == item.PRODUCTION_UNIT);
                            var primary = importNames.FirstOrDefault(t => t.NAME == item.Primary && t.PARENT_ID == productionUnit.ID);
                            var second = importNames.FirstOrDefault(t => t.NAME == item.Second && t.PARENT_ID == productionUnit.ID);
                            var three = importNames.FirstOrDefault(t => t.NAME == item.Three && t.PARENT_ID == productionUnit.ID);
                            T_PE_SAFETY_EVALUATION_RECORD_DETAIL detail = new T_PE_SAFETY_EVALUATION_RECORD_DETAIL();
                            detail.PRODUCTION_UNIT_ID = productionUnit.ID;
                            detail.PRIMARY_ELEMENTS_ID = primary.ID;
                            detail.SECOND_ELEMENTS_ID = second.ID;
                            detail.THREE_ELEMENTS_ID = three.ID;
                            detail.CONTENTS = item.CONTENTS;
                            detail.STANDARDIZED_SCORE = decimal.Parse(item.STANDARDIZED_SCORE);
                            detail.RESULT_SCORE = decimal.Parse(item.RESULT_SCORE);
                            detail.DESCRIPTION = item.DESCRIPTION;
                            detail.IS_AUTO = item.IS_AUTO;
                            detail.EVALUATION_ITEM = enums2.FirstOrDefault(t => t.NAME == item.EVALUATION_ITEM)?.ID;
                            detail.NUM = item.NUM;
                            result.Nav_Details.Add(detail);
                        }
                    }
                    if (result != null)
                    {
                        var records = this.GetEntities<T_PE_SAFETY_EVALUATION_RECORD>(t => t.EVALUATION_PLAN_ID == result.EVALUATION_PLAN_ID, new BaseFilter(result.ORG_ID));
                        if (records != null && records.Any())
                        {
                            var recordIds = records.Where(t => t.STATUS == PFStandardStatus.Archived).Select(record => record.ID).ToList();
                            var recordDetails = this.GetEntities<T_PE_SAFETY_EVALUATION_RECORD_DETAIL>(t => recordIds.Contains((Guid)t.SAFETY_EVALUATION_RECORD_ID), new BaseFilter(result.ORG_ID), "Nav_ProductionUnit", "Nav_Primary", "Nav_Second", "Nav_Three", "Nav_EvaluationMethod.Nav_Method");
                            var autos = result.Nav_Details.Where(t => t.IS_AUTO == true).ToList();
                            if (autos.Any())
                            {
                                foreach (var item in autos)
                                {
                                    var recordDetail = recordDetails.FirstOrDefault(t => t.CONTENTS == item.CONTENTS);
                                    item.RESULT_SCORE = recordDetail.RESULT_SCORE;
                                }
                            }
                            var recordUsers = this.GetEntities<T_PE_SAFETY_EVALUATION_RECORD_USER>(t => recordIds.Contains((Guid)t.SAFETY_EVALUATION_RECORD_ID), new BaseFilter(result.ORG_ID), "Nav_User");
                            result.Nav_RecordUser = recordUsers.ToList();
                            result.Nav_Details.ForEach(t =>
                            {
                                t.STANDARDIZED_SCORE = t.STANDARDIZED_SCORE > 0 ? t.STANDARDIZED_SCORE : t.NON_STANDARDIZED_SCORE;
                                t.NON_STANDARDIZED_SCORE = t.STANDARDIZED_SCORE - t.RESULT_SCORE;
                            });
                            result.Nav_Details = result.Nav_Details.OrderBy(n => n.NUM).ToList();
                            var tempStand = result.Nav_Details.Sum(t => t.STANDARDIZED_SCORE).Value;
                            result.STAND_TOTAL = tempStand.ToString();
                            var tempResult = result.Nav_Details.Sum(t => t.RESULT_SCORE).Value;
                            result.RESULT_TOTAL = tempResult.ToString();
                            result.NON_STANDARDIZED_SCORE = (tempStand - tempResult).ToString();
                            var allRecordIds = records.Select(record => record.ID).ToList();
                            var approveInfo = this.GetEntity<T_PF_APPROVE>(t => allRecordIds.Contains((Guid)t.DATA_ID) && t.APPROVE_STATUS != 10);
                            if (approveInfo != null)
                                allRecordIds.Add(approveInfo.ID);
                            var taskInfo = this.GetEntity<T_FM_NOTIFICATION_TASK>(t => allRecordIds.Contains((Guid)t.SOURCE_DATA_ID) && t.NOTICE_STATUS == 0 && t.NOTICE_TYPE != 2);
                            if (taskInfo == null)
                                result.STANDARDIZED_RESULT = tempStand == 0 ? "0" : (tempResult / tempStand * 100).ToString("#0.00");
                            else
                                result.STANDARDIZED_RESULT = "0";
                        }
                        var ingoreDetailTemps = new List<T_PE_SAFETY_EVALUATION_RECORD_DETAIL>();
                        var ingoreDetails = result.Nav_Details.GroupBy(t => t.PRODUCTION_UNIT_ID);
                        foreach (var detail in ingoreDetails)
                        {
                            var itemDetail = new T_PE_SAFETY_EVALUATION_RECORD_DETAIL();
                            var firstDetail = result.Nav_Details.FirstOrDefault(t => t.PRODUCTION_UNIT_ID == detail.Key.Value);
                            itemDetail.Nav_ProductionUnit = firstDetail?.Nav_ProductionUnit;
                            itemDetail.PRODUCTION_UNIT_ID = firstDetail?.PRODUCTION_UNIT_ID;
                            itemDetail.STANDARDIZED_SCORE = result.Nav_Details.Where(t => t.PRODUCTION_UNIT_ID == detail.Key.Value).Sum(m => m.STANDARDIZED_SCORE);
                            itemDetail.RESULT_SCORE = result.Nav_Details.Where(t => t.PRODUCTION_UNIT_ID == detail.Key.Value).Sum(m => m.RESULT_SCORE);
                            itemDetail.NON_STANDARDIZED_SCORE = result.STANDARDIZED_RESULT == "0" ? 0 : Math.Round((decimal)itemDetail.RESULT_SCORE / (decimal)itemDetail.STANDARDIZED_SCORE * 100, 2);
                            ingoreDetailTemps.Add(itemDetail);
                        }
                        result.Nav_IngoreDetails = ingoreDetailTemps.OrderBy(n => n.NUM).ToList();
                        //var item = new T_PE_SAFETY_EVALUATION_RECORD_DETAIL();
                        //item.DESCRIPTION = "合计";
                        //item.STANDARDIZED_SCORE = result.STAND_TOTAL.ToString() == "" ? 1 : decimal.Parse(result.STAND_TOTAL);
                        //item.RESULT_SCORE = result.RESULT_TOTAL.ToString() == "" ? 0 : decimal.Parse(result.RESULT_TOTAL);
                        //item.NON_CONFORMANCE = "标准化得分:"+ Math.Round(((decimal)item.RESULT_SCORE / (decimal)item.STANDARDIZED_SCORE * 100),2);
                        //item.GROUP_NO = "合计扣分";
                        //item.NON_STANDARDIZED_SCORE = item.STANDARDIZED_SCORE - item.RESULT_SCORE;
                        //result.Nav_Details.Add(item);
                        //newFilter.SelectField = new List<string> { "ID", "USER_ID", "GROUP_NO", "ROW_NO", "Nav_User", "DEAL_STATUS" };
                        if (result != null && result.Nav_RecordUser != null && result.Nav_RecordUser.Any())
                        {
                            result.Nav_IngoreUser = result.Nav_RecordUser.Distinct(t => t.USER_ID).ToList();
                        }
                    }
                    else
                    {
                        var standImport = this.GetEntity<T_PE_STANDARDIZED_SCORE_IMPORT>(t => t.NAME == name);
                        if (standImport != null)
                        {
                            result = new T_PE_SAFETY_EVALUATION_RECORD();
                            result.RESULT_TOTAL = standImport.SCORE == null ? "0" : standImport.SCORE;
                            result.STAND_TOTAL = "100";
                            result.Nav_Details = new List<T_PE_SAFETY_EVALUATION_RECORD_DETAIL>();
                        }
                    }
                }
                return result;
            });
        }
        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("FullOrderPaged")]
        public PagedActionResult<T_PE_SAFETY_EVALUATION_RECORD> FullOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            var result = new PagedActionResult<T_PE_SAFETY_EVALUATION_RECORD>();
            var list = new List<T_PE_SAFETY_EVALUATION_RECORD>();
            var temp = this.GetEntities<T_PE_SAFETY_EVALUATION_RECORD>(null, new BaseFilter(pageFilter.OrgId), "Nav_EvaluationPlan.Nav_ProductionUnit");
            if (temp != null && temp.Any())
            {
                var groupTemps = temp.GroupBy(t => new { YEAR = t.Nav_EvaluationPlan.YEAR, PRODUCTION_UNIT = t.Nav_EvaluationPlan.Nav_ProductionUnit.NAME }).Distinct().ToList();
                if (groupTemps != null && groupTemps.Any())
                {
                    foreach (var item in groupTemps)
                    {
                        T_PE_SAFETY_EVALUATION_RECORD record = new T_PE_SAFETY_EVALUATION_RECORD();
                        record.ID = item.FirstOrDefault().ID;
                        record.YEAR = item.Key.YEAR;
                        record.PRODUCTION_UNIT = item.Key.PRODUCTION_UNIT;
                        list.Add(record);
                    }
                    result.Data = list.OrderByDescending(t => t.YEAR).ThenBy(m => m.PRODUCTION_UNIT);
                    result.TotalCount = list.Count;
                }
            }
            return result;
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("FullGet")]
        public JsonActionResult<T_PE_SAFETY_EVALUATION_RECORD> FullGet([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                T_PE_SAFETY_EVALUATION_RECORD result = null;
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID")?.Value;
                if (string.IsNullOrEmpty(id.ToString()))
                {
                    var resultTemps = this.GetEntities<T_PE_SAFETY_EVALUATION_RECORD>(t => t.Nav_EvaluationPlan != null && t.Nav_EvaluationPlan.YEAR == DateTime.Now.Year.ToString(), new BaseFilter(filter.OrgId), "Nav_EvaluationPlan").ToList();
                    if (!resultTemps.Any())
                    {
                        var temp = this.GetEntities<T_PE_SAFETY_EVALUATION_RECORD>(t => t.Nav_EvaluationPlan != null, new BaseFilter(filter.OrgId), "Nav_EvaluationPlan").OrderByDescending(t => t.CREATE_TIME).FirstOrDefault();
                        if (temp != null)
                        {
                            resultTemps = this.GetEntities<T_PE_SAFETY_EVALUATION_RECORD>(t => t.Nav_EvaluationPlan != null && t.Nav_EvaluationPlan.YEAR == temp.CREATE_TIME.Value.Year.ToString(), new BaseFilter(filter.OrgId), "Nav_EvaluationPlan").ToList();
                        }
                    }
                    result = resultTemps.OrderByDescending(m => m.CREATE_TIME).FirstOrDefault();
                    if (result != null)
                    {
                        var records = this.GetEntities<T_PE_SAFETY_EVALUATION_RECORD>(t => t.EVALUATION_PLAN_ID == result.EVALUATION_PLAN_ID, new BaseFilter(result.ORG_ID));
                        if (records != null && records.Any())
                        {
                            var recordIds = records.Select(record => record.ID).ToList();
                            var recordDetails = this.GetEntities<T_PE_SAFETY_EVALUATION_RECORD_DETAIL>(t => recordIds.Contains((Guid)t.SAFETY_EVALUATION_RECORD_ID), new BaseFilter(result.ORG_ID), "Nav_ProductionUnit", "Nav_Primary", "Nav_Second", "Nav_Three", "Nav_EvaluationMethod.Nav_Method");
                            result.Nav_Details = recordDetails.ToList();
                            var recordUsers = this.GetEntities<T_PE_SAFETY_EVALUATION_RECORD_USER>(t => recordIds.Contains((Guid)t.SAFETY_EVALUATION_RECORD_ID), new BaseFilter(result.ORG_ID), "Nav_User");
                            result.Nav_RecordUser = recordUsers.ToList();
                        }
                        result.Nav_Details.ForEach(t =>
                        {
                            t.STANDARDIZED_SCORE = t.STANDARDIZED_SCORE > 0 ? t.STANDARDIZED_SCORE : t.NON_STANDARDIZED_SCORE;
                            t.NON_STANDARDIZED_SCORE = t.STANDARDIZED_SCORE - t.RESULT_SCORE;
                        });
                        result.Nav_Details = result.Nav_Details.OrderBy(n => n.NUM).ToList();
                        //OrderBy(n => n.PRODUCTION_UNIT_ID).ThenBy(i => i.PRIMARY_ELEMENTS_ID).ThenBy(m => m.SECOND_ELEMENTS_ID).ToList();
                        if (result != null && result.Nav_RecordUser != null && result.Nav_RecordUser.Any())
                        {
                            result.Nav_IngoreUser = result.Nav_RecordUser.OrderBy(m => m.ROW_NO).Distinct(t => t.USER_ID).ToList();
                        }
                    }
                }
                else
                {
                    result = this.GetEntity<T_PE_SAFETY_EVALUATION_RECORD>(id.ToString(), "Nav_EvaluationPlan", "Nav_RecordUser.Nav_User");
                    var recordDetails = this.GetEntities<T_PE_SAFETY_EVALUATION_RECORD_DETAIL>(t => t.SAFETY_EVALUATION_RECORD_ID == result.ID, new BaseFilter(result.ORG_ID), "Nav_ProductionUnit", "Nav_Primary", "Nav_Second", "Nav_Three", "Nav_EvaluationMethod.Nav_Method");
                    result.Nav_Details = recordDetails.ToList();
                    result.Nav_Details.ForEach(t =>
                    {
                        t.STANDARDIZED_SCORE = t.STANDARDIZED_SCORE > 0 ? t.STANDARDIZED_SCORE : t.NON_STANDARDIZED_SCORE;
                        t.NON_STANDARDIZED_SCORE = t.STANDARDIZED_SCORE - t.RESULT_SCORE;
                    });
                    result.Nav_Details = result.Nav_Details.OrderBy(n => n.NUM).ToList();
                    //OrderBy(n => n.PRODUCTION_UNIT_ID).ThenBy(i => i.PRIMARY_ELEMENTS_ID).ThenBy(m => m.SECOND_ELEMENTS_ID).ToList();
                    if (result != null && result.Nav_RecordUser != null && result.Nav_RecordUser.Any())
                    {
                        result.Nav_IngoreUser = result.Nav_RecordUser.OrderBy(m => m.ROW_NO).Distinct(t => t.USER_ID).ToList();
                    }
                }
                result.STAND_TOTAL = result.Nav_Details.Sum(t => t.STANDARDIZED_SCORE).Value.ToString();
                result.RESULT_TOTAL = result.Nav_Details.Sum(t => t.RESULT_SCORE).Value.ToString();
                result.NON_STANDARDIZED_SCORE = result.Nav_Details.Sum(t => t.NON_STANDARDIZED_SCORE).Value.ToString();
                return result;
            });
        }

        /// <summary>
        /// 新增/编辑
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdateDetail")]
        public JsonActionResult<bool> FullUpdateDetail([FromBody] T_PE_SAFETY_EVALUATION_RECORD entity)
        {
            return SafeExecute(() =>
            {
                var details = entity.Nav_Details;
                if (details != null && details.Any())
                {
                    details.ForEach(t =>
                    {
                        if (t.RESULT_SCORE > t.STANDARDIZED_SCORE)
                            this.ThrowError("040007");
                    });
                }
                UnifiedCommit(() =>
                {
                    if (details != null && details.Any())
                        this.BantchSaveEntityNoCommit(details);
                });
                return true;
            });
        }


        /// <summary>
        /// 首页数据组合 Redis
        /// </summary>
        public class HomeResultMineType
        {
            /// <summary>
            /// 生产单元 Key1
            /// </summary>
            public int MineType { get; set; }
            /// <summary>
            /// 时间 Key2   根据2个key 获取与更新
            /// </summary>
            public string yyyyMMddHH { get; set; }

            /// <summary>
            /// 存储信息
            /// </summary>
            public T_PE_SAFETY_EVALUATION_RECORD result { get; set; }
        }
    }
}
