using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Entities.OP;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.IServices.FM;
using APT.BaseData.Services.Services.FM;
using APT.Infrastructure.Api;
using APT.Infrastructure.Core;
using APT.Migrations;
using APT.MS.Domain.Entities.BI;
using APT.MS.Domain.Entities.FO;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Entities.SC.BI;
using APT.MS.Domain.Entities.SE;
using APT.MS.Domain.Entities.SK;
using APT.MS.Domain.Enums;
using APT.MS.Domain.Enums.SK;
using APT.Utility;
using log4net.Core;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using static Google.Protobuf.WireFormat;

namespace APT.SC.WebApi.Controllers.Api.BI
{
    /// <summary>
    ///  年度监测汇总
    /// </summary>
    [Route("api/BI/BIController")]
    public class BIController : APTApiController<T_FM_WORK_TICKET_COMPLETION>
    {

        public class GoViewDataReturn
        {
            public int code { get; set; }
            public int count { get; set; }
            public string msg { get; set; }
            public object data { get; set; }
        }
        public class EchartsDataset
        {
            public string[] dimensions { get; set; }
            public List<object> source { get; set; }
        }
        public class addItem
        {
            public string 班组名称 { get; set; }
            public int 待办 { get; set; }
            public int 总数 { get; set; }


        }
        /// <summary>
        /// 班前会议数量统计
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("PreShiftMeetingCount")]
        public GoViewDataReturn PreShiftMeetingCount(string param)
        {
            //var paramArr = param.Trim('"').Split("|");
            Guid orgId = getOrgIdByTenant(this.Request.Headers["Tenant"]);
            GoViewDataReturn goViewDataReturn = new GoViewDataReturn()
            {
                msg = "",
                code = 200
            };
            var result = GetEntities<T_FM_DEPARTMENT_COMPLETION>(t => t.FORM_NAME == "班前会议", new BaseFilter(orgId));
            EchartsDataset dataset = new EchartsDataset();
            dataset.dimensions = new string[] { "班组名称", "待办", "总数" };
            dataset.source = new List<object>();
            foreach (var item in result)
            {
                var test = new addItem
                {
                    班组名称 = item.TEAM_NAME,
                    待办 = item.WAITTING_COUNT,
                    总数 = item.TOTAL_COUNT
                };
                dataset.source.Add(test);
            }
            goViewDataReturn.data = dataset;
            return goViewDataReturn;
        }
        private Guid getOrgIdByTenant(string Tenant)
        {
            Guid orgId = Guid.Empty;
            if (Tenant.Equals("0001"))//XLK
            {
                orgId = Guid.Parse("b043b28b-bbc3-c452-6052-4fba1457abfa");
            }
            else if (Tenant.Equals("A0000024"))//豫鹭
            {
                orgId = Guid.Parse("d9871ba8-0eec-9e4a-bb87-7d5a540d8913");
            }
            else if (Tenant.Equals("A0000025"))//金鼎
            {
                orgId = Guid.Parse("8b3c41aa-51b1-7ce9-1879-248a038c1b5c");
            }
            else if (Tenant.Equals("0002"))//龙岩稀土
            {
                orgId = Guid.Parse("8f1cf418-8bf3-ea3f-7a6d-fc5d61247008");
            }
            return orgId;
        }
        /// <summary>
        /// 返回系统用户数
        /// </summary>
        /// <param name="pageFilter">返回系统用户数</param>
        /// <returns></returns>
        [HttpPost, Route("userCount")]
        public JsonActionResult<int> userCount([FromBody] KeywordFilter filter)
        {
            return SafeExecute<int>(() =>
            {
                return GetCount<T_FM_USER>(t => t.ENABLE_STATUS == 0, new BaseFilter(filter.GetOrgId()));
            });
        }

        /// <summary>
        /// 风险库统计
        /// </summary>
        /// <param name="pageFilter">返回系统用户数</param>
        /// <returns></returns>
        [HttpPost, Route("savesouceDepartment")]
        public JsonActionResult<bool> savesouceDepartment([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var riskFilter = new BaseFilter(filter.GetOrgId());
                riskFilter.Include = new string[] { "Nav_DepartmentLiable.Nav_Parent.Nav_Parent" };
                var all = GetEntities<T_HM_EVALUATE_RISK>(t => t.STATUS == (int)HMOperationStepEnum.有效 && t.DEPARTMENT_LIABLE_ID != null && t.SOURCE_DEPARTMENT_ID == null, riskFilter);
                foreach (var entity in all)
                {
                    if (entity.Nav_DepartmentLiable.DEPARTMENT_TYPE == (int)FMDepartmentType.Class)
                    {
                        entity.SOURCE_DEPARTMENT_ID = entity.Nav_DepartmentLiable.Nav_Parent.Nav_Parent.ID;
                    }
                    if (entity.Nav_DepartmentLiable.DEPARTMENT_TYPE == (int)FMDepartmentType.Workshop)
                    {
                        entity.SOURCE_DEPARTMENT_ID = entity.Nav_DepartmentLiable.Nav_Parent.ID;
                    }
                    if (entity.Nav_DepartmentLiable.DEPARTMENT_TYPE == (int)FMDepartmentType.Department)
                    {
                        entity.SOURCE_DEPARTMENT_ID = entity.DEPARTMENT_LIABLE_ID;
                    }
                    entity.Nav_DepartmentLiable = null;
                }
                this.UnifiedCommit(() =>
                {
                    BantchUpdateEntityNoCommit(all);
                });
                return true;
            });
        }
        /// <summary>
        /// 风险库统计
        /// </summary>
        /// <param name="pageFilter">返回系统用户数</param>
        /// <returns></returns>
        [HttpPost, Route("updateStatus")]
        public JsonActionResult<bool> updateStatus([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var riskFilter = new BaseFilter(filter.GetOrgId());
                var all = GetEntities<T_FO_PRE_SHIFT_MEETING_RECORD>(t => t.PRE_MEETING_STATUS != FOPreMeetingStatusEnum.归档, riskFilter);
                foreach (var item in all)
                {
                    var num = GetCount<T_FO_PRE_SHIFT_MEETING_RECORD_USER>(t => t.PRE_SHIFT_MEETING_RECORD_ID == item.ID && t.DEAL_STATUS == 0, riskFilter);
                    if (num == 0)
                    {
                        item.PRE_MEETING_STATUS = FOPreMeetingStatusEnum.归档;
                        UpdateEntity(item);
                    }
                }
                var all2 = GetEntities<T_FO_CURRENT_CLASS_RECORD>(t => t.SHIFT_STATUS != 4, riskFilter);
                foreach (var item in all2)
                {
                    var num = GetCount<T_FO_CURRENT_CLASS_RECORD_USER>(t => t.CURRENT_CLASS_RECORD_ID == item.ID && t.USER_SHIFT_STATUS == 0, riskFilter);
                    if (num == 0)
                    {
                        item.SHIFT_STATUS = 4;
                        UpdateEntity(item);
                    }
                }
                var all3 = GetEntities<T_FO_CHANGE_SHIFT_RECORD>(t => t.SHIFT_STATUS != 3, riskFilter);
                foreach (var item in all3)
                {
                    var num1 = GetCount<T_FO_CHANGE_SHIFT_RECORD_PRE_USER>(t => t.CHANGE_SHIFT_RECORD_ID == item.ID && t.USER_SHIFT_STATUS == 0, riskFilter);
                    var num2 = GetCount<T_FO_CHANGE_SHIFT_RECORD_PRE_USER>(t => t.CHANGE_SHIFT_RECORD_ID == item.ID && t.USER_SHIFT_STATUS == 0, riskFilter);
                    if (num1 == 0 && num2 == 0)
                    {
                        item.SHIFT_STATUS = 3;
                        UpdateEntity(item);
                    }
                }
                var all4 = GetEntities<T_FO_TEAM_ACTIVITY>(t => t.TA_STATUS == 1, riskFilter);
                foreach (var item in all4)
                {
                    var num1 = GetCount<T_FO_TEAM_ACTIVITY_USER>(t => t.TEAM_ACTIVITY_ID == item.ID && t.SIGN_IN_STATUS == 0, riskFilter);
                    if (num1 == 0)
                    {
                        item.TA_STATUS = 2;
                        UpdateEntity(item);
                    }
                }
                return true;
            });
        }
        public class riskData
        {
            public List<riskLevelCountModel> RISKLEVELCOUNTS { get; set; }
            public List<areaCountModel> AREACOUNTS { get; set; }
            public List<dateCountModel> DATECOUNTS { get; set; }
            public int RISKTOTALCOUNT { get; set; }
            public int HAZARDTOTALCOUNT { get; set; }
            public int MEASURESTOTALCOUNT { get; set; }

        }
        public class areaCountModel
        {
            public string AREANAME { get; set; }
            public int AREACOUNT { get; set; }
            public int AREATYPE { get; set; }
        }
        public class riskLevelCountModel
        {
            public string NAME { get; set; }
            public int LEVEL1 { get; set; }
            public int LEVEL2 { get; set; }
            public int LEVEL3 { get; set; }
            public int LEVEL4 { get; set; }
        }
        public class dateCountModel
        {
            public DateTime DATE { get; set; }
            public int COUNT { get; set; }
            public int TYPE { get; set; }
        }
        /// <summary>
        /// 风险库统计
        /// </summary>
        /// <param name="pageFilter">返回系统用户数</param>
        /// <returns></returns>
        [HttpPost, Route("getRiskData")]
        public JsonActionResult<riskData> getRiskData([FromBody] KeywordFilter filter)
        {
            return SafeExecute<riskData>(() =>
            {
                var riskFilter = new BaseFilter(filter.GetOrgId());
                riskFilter.SelectField = new string[] { "AREA_ID", "Nav_Area.NAME", "EVALUATE_LEVEL", "Nav_SourceDepartment.NAME", "CREATE_TIME" };
                IEnumerable<T_HM_EVALUATE_RISK> allrisk = null;
                if (filter.Parameter1 != null)
                {
                    allrisk = GetEntities<T_HM_EVALUATE_RISK>(t => t.STATUS == (int)HMOperationStepEnum.有效 && t.SOURCE_DEPARTMENT_ID != null && t.MineType == int.Parse(filter.Parameter1), riskFilter);
                }
                else
                {
                    allrisk = GetEntities<T_HM_EVALUATE_RISK>(t => t.STATUS == (int)HMOperationStepEnum.有效 && t.SOURCE_DEPARTMENT_ID != null, riskFilter);
                }
                var hazardFilter = new BaseFilter(filter.GetOrgId());
                hazardFilter.SelectField = new string[] { "CREATE_TIME" };
                var allhazard = GetEntities<T_HM_EVALUATE_HAZARD>(t => t.STATUS == (int)HMOperationStepEnum.有效, hazardFilter);
                var measureFilter = new BaseFilter(filter.GetOrgId());
                measureFilter.SelectField = new string[] { "NAME" };
                var measure1 = GetEntities<T_HM_INDIVIDUAL_MEASURES>(t => t.IS_DELETED == false, measureFilter).Select(t => t.NAME).Distinct().Count();
                var measure2 = GetEntities<T_HM_EDUCATION_MEASURES>(t => t.IS_DELETED == false, measureFilter).Select(t => t.NAME).Distinct().Count();
                var measure3 = GetEntities<T_HM_EMERGENCY_MEASURES>(t => t.IS_DELETED == false, measureFilter).Select(t => t.NAME).Distinct().Count();
                var measure4 = GetEntities<T_HM_ENGINEERING_MEASURES>(t => t.IS_DELETED == false, measureFilter).Select(t => t.NAME).Distinct().Count();
                var measure5 = GetEntities<T_HM_MANAGEMENT_MEASURES>(t => t.IS_DELETED == false, measureFilter).Select(t => t.NAME).Distinct().Count();
                //var distinctDepartment = allrisk.Select(t => new { t.SOURCE_DEPARTMENT_ID, t.Nav_SourceDepartment.NAME }).Distinct();
                var distinctDepartment = GetEntities<T_FM_DEPARTMENT>(t => t.DEPARTMENT_TYPE == 10, new BaseFilter(filter.GetOrgId()));

                riskData riskData = new riskData();
                List<riskLevelCountModel> item1s = new List<riskLevelCountModel>();
                List<areaCountModel> item2s = new List<areaCountModel>();
                List<dateCountModel> item3s = new List<dateCountModel>();

                foreach (var department in distinctDepartment)
                {
                    riskLevelCountModel item = new riskLevelCountModel();
                    item.NAME = department.NAME;
                    item.LEVEL1 = allrisk.Count(t => t.SOURCE_DEPARTMENT_ID == department.ID && t.EVALUATE_LEVEL == EvaluateLevelEnum.一级);
                    item.LEVEL2 = allrisk.Count(t => t.SOURCE_DEPARTMENT_ID == department.ID && t.EVALUATE_LEVEL == EvaluateLevelEnum.二级);
                    item.LEVEL3 = allrisk.Count(t => t.SOURCE_DEPARTMENT_ID == department.ID && t.EVALUATE_LEVEL == EvaluateLevelEnum.三级);
                    item.LEVEL4 = allrisk.Count(t => t.SOURCE_DEPARTMENT_ID == department.ID && t.EVALUATE_LEVEL == EvaluateLevelEnum.四级);
                    item1s.Add(item);
                }
                var distinctArea = allrisk.Select(t => new { t.AREA_ID, AreaName = t.Nav_Area.NAME, SourceDepartmentName = t.Nav_SourceDepartment.NAME }).Distinct();
                foreach (var area in distinctArea)
                {

                    if (area.SourceDepartmentName.Contains("矿山") || area.SourceDepartmentName.Contains("选矿"))
                    {
                        areaCountModel item = new areaCountModel();

                        if (area.SourceDepartmentName.Contains("矿山"))
                        {
                            item.AREATYPE = 0;
                        }
                        else
                        {
                            item.AREATYPE = 1;
                        }
                        item.AREANAME = area.AreaName;
                        item.AREACOUNT = allrisk.Count(t => t.AREA_ID == area.AREA_ID);
                        item2s.Add(item);
                    }
                }
                var currMonth = DateTime.Now.Month;
                DateTime today = DateTime.Today;
                for (var i = 1; i < currMonth + 1; i++)
                {
                    DateTime endOfMonth = new DateTime(today.Year, i, 1).AddMonths(1).AddSeconds(-1);
                    dateCountModel riskDate = new dateCountModel();
                    riskDate.DATE = endOfMonth;
                    riskDate.COUNT = allrisk.Count(t => t.CREATE_TIME <= endOfMonth);
                    riskDate.TYPE = 0;
                    item3s.Add(riskDate);
                    dateCountModel hazardDate = new dateCountModel();
                    hazardDate.DATE = endOfMonth;
                    hazardDate.COUNT = allhazard.Count(t => t.CREATE_TIME <= endOfMonth); ;
                    hazardDate.TYPE = 1;
                    item3s.Add(hazardDate);
                }
                riskData.RISKLEVELCOUNTS = item1s.OrderByDescending(t => t.LEVEL4).ToList();
                riskData.AREACOUNTS = item2s.OrderBy(t => t.AREACOUNT).ToList();
                riskData.DATECOUNTS = item3s.OrderBy(t => t.DATE).ToList();
                riskData.RISKTOTALCOUNT = allrisk.Count();
                riskData.HAZARDTOTALCOUNT = allhazard.Count();
                riskData.MEASURESTOTALCOUNT = measure1 + measure2 + measure3 + measure4 + measure5;
                return riskData;
            });
        }
        public class riskPerformanceData
        {
            public List<dateCountModel> DATECOUNTS { get; set; }
            public PerformanceModel CHARTFXDJ1 { get; set; }
            public List<PerformanceModel1> CHARTFXDJ2 { get; set; }
            public List<PerformanceModel> CHARTLIST { get; set; }
            public List<PerformanceModel> TEAMLIST { get; set; }
            public List<PerformanceModel> AREALIST { get; set; }
            public List<PerformanceModel> RISKTYPELIST { get; set; }
            public List<PerformanceModel> SCDYLIST { get; set; }
            public List<PerformanceModel> CJLIST { get; set; }
            public PerformanceModel CHARTZYRW1 { get; set; }
            public List<PerformanceModel1> CHARTZYRW2 { get; set; }


            public riskPerformanceData()
            {
                CHARTLIST = new List<PerformanceModel>();
                TEAMLIST = new List<PerformanceModel>();
                AREALIST = new List<PerformanceModel>();
                RISKTYPELIST = new List<PerformanceModel>();
                SCDYLIST = new List<PerformanceModel>();
                CJLIST = new List<PerformanceModel>();
            }

        }
        public class PerformanceModel1
        {
            public string name { get; set; }

            public int value { get; set; }
        }
        public class PerformanceModel
        {
            public List<string> NAME { get; set; }
            public List<int> LEVEL1 { get; set; }
            public List<int> LEVEL2 { get; set; }
            public List<int> LEVEL3 { get; set; }
            public List<int> LEVEL4 { get; set; }
            public List<int> TOTAL { get; set; }

            public PerformanceModel()
            {
                NAME = new List<string>();
                LEVEL1 = new List<int>();
                LEVEL2 = new List<int>();
                LEVEL3 = new List<int>();
                LEVEL4 = new List<int>();
                TOTAL = new List<int>();
            }

        }
        public PerformanceModel SortByTotal(PerformanceModel item)
        {
            // 创建临时列表用于保存排序后的索引
            List<int> sortedIndexes = Enumerable.Range(0, item.TOTAL.Count)
                .OrderByDescending(index => item.TOTAL[index])
                .ToList();

            // 新建排序后的数组
            List<string> sortedName = new List<string>();
            List<int> sortedLevel1 = new List<int>();
            List<int> sortedLevel2 = new List<int>();
            List<int> sortedLevel3 = new List<int>();
            List<int> sortedLevel4 = new List<int>();

            // 按照排序后的索引填充新的数组
            for (int i = 0; i < sortedIndexes.Count; i++)
            {
                sortedName.Add(item.NAME[sortedIndexes[i]]);
                sortedLevel1.Add(item.LEVEL1[sortedIndexes[i]]);
                sortedLevel2.Add(item.LEVEL2[sortedIndexes[i]]);
                sortedLevel3.Add(item.LEVEL3[sortedIndexes[i]]);
                sortedLevel4.Add(item.LEVEL4[sortedIndexes[i]]);
            }

            // 将排序后的数组赋值回原对象
            item.NAME = sortedName.GetRange(0, Math.Min(8, item.NAME.Count));
            item.LEVEL1 = sortedLevel1.GetRange(0, Math.Min(8, item.NAME.Count));
            item.LEVEL2 = sortedLevel2.GetRange(0, Math.Min(8, item.NAME.Count));
            item.LEVEL3 = sortedLevel3.GetRange(0, Math.Min(8, item.NAME.Count));
            item.LEVEL4 = sortedLevel4.GetRange(0, Math.Min(8, item.NAME.Count));

            return item;
        }
        /// <summary>
        /// 风险库统计
        /// </summary>
        /// <param name="pageFilter">返回系统用户数</param>
        /// <returns></returns>
        [HttpPost, Route("getRiskPerformanceDataOld")]
        public JsonActionResult<riskPerformanceData> getRiskPerformanceDataOld([FromBody] KeywordFilter filter)
        {
            return SafeExecute<riskPerformanceData>(() =>
            {
                var riskFilter = new BaseFilter(filter.GetOrgId());
                riskFilter.SelectField = new string[] { "EVALUATE_LEVEL", "CREATE_TIME", "MineType", "SOURCE_DEPARTMENT_ID", "TYPE_ID", "LEVEL", "AREA_ID", "DEPARTMENT_LIABLE_ID" };
                IEnumerable<T_HM_EVALUATE_RISK> allrisk = null;
                allrisk = GetEntities<T_HM_EVALUATE_RISK>(t => t.STATUS == (int)HMOperationStepEnum.有效 && t.SOURCE_DEPARTMENT_ID != null, riskFilter);
                var hazardFilter = new BaseFilter(filter.GetOrgId());
                hazardFilter.SelectField = new string[] { "CREATE_TIME" };
                var allhazard = GetEntities<T_HM_EVALUATE_HAZARD>(t => t.STATUS == (int)HMOperationStepEnum.有效, hazardFilter);
                riskPerformanceData riskPerformanceData = new riskPerformanceData();
                List<dateCountModel> item3s = new List<dateCountModel>();
                var distinctType = GetEntities<T_HM_RISK_TYPE>(t => t.IS_DELETED == false, new BaseFilter(filter.GetOrgId()));
                var distinctDepartment = GetEntities<T_FM_DEPARTMENT>(t => t.DEPARTMENT_TYPE == 10, new BaseFilter(filter.GetOrgId()));
                var distinctArea = GetEntities<T_HM_RISK_AREA>(t => t.IS_DELETED == false, new BaseFilter(filter.GetOrgId()));
                var distinctTeamDepartment = GetEntities<T_FM_DEPARTMENT>(t => t.DEPARTMENT_TYPE == 20, new BaseFilter(filter.GetOrgId()));

                #region 1
                PerformanceModel CHARTFXDJ1 = new PerformanceModel();
                CHARTFXDJ1.NAME = new List<string> { "一级", "二级", "三级", "四级" };
                var type1 = allrisk.Count(t => t.EVALUATE_LEVEL == EvaluateLevelEnum.一级);
                var type2 = allrisk.Count(t => t.EVALUATE_LEVEL == EvaluateLevelEnum.二级);
                var type3 = allrisk.Count(t => t.EVALUATE_LEVEL == EvaluateLevelEnum.三级);
                var type4 = allrisk.Count(t => t.EVALUATE_LEVEL == EvaluateLevelEnum.四级);
                CHARTFXDJ1.LEVEL1 = new List<int> { type1, type2, type3, type4 };
                riskPerformanceData.CHARTFXDJ1 = CHARTFXDJ1;
                #endregion
                #region 2
                List<PerformanceModel1> model2s = new List<PerformanceModel1> { };
                PerformanceModel1 model1 = new PerformanceModel1();
                PerformanceModel1 model2 = new PerformanceModel1();
                PerformanceModel1 model3 = new PerformanceModel1();
                PerformanceModel1 model4 = new PerformanceModel1();

                model1.name = "一级";
                model1.value = allrisk.Count(t => t.EVALUATE_LEVEL == EvaluateLevelEnum.一级);
                model2s.Add(model1);
                model2.name = "二级";
                model2.value = allrisk.Count(t => t.EVALUATE_LEVEL == EvaluateLevelEnum.二级);
                model2s.Add(model2);
                model3.name = "三级";
                model3.value = allrisk.Count(t => t.EVALUATE_LEVEL == EvaluateLevelEnum.三级);
                model2s.Add(model3);
                model4.name = "四级";
                model4.value = allrisk.Count(t => t.EVALUATE_LEVEL == EvaluateLevelEnum.四级);
                model2s.Add(model4);
                riskPerformanceData.CHARTFXDJ2 = model2s;
                #endregion


                #region 3
                PerformanceModel modelMineType = new PerformanceModel();
                foreach (FMProductionUnit mineType in Enum.GetValues(typeof(FMProductionUnit)))
                {
                    var mineTypeName = mineType.GetDescription();
                    var mineTypeInt = mineType.GetInt();
                    modelMineType.NAME.Add(mineTypeName);
                    modelMineType.LEVEL1.Add(allrisk.Count(t => t.MineType == mineTypeInt && t.EVALUATE_LEVEL == EvaluateLevelEnum.一级));
                    modelMineType.LEVEL2.Add(allrisk.Count(t => t.MineType == mineTypeInt && t.EVALUATE_LEVEL == EvaluateLevelEnum.二级));
                    modelMineType.LEVEL3.Add(allrisk.Count(t => t.MineType == mineTypeInt && t.EVALUATE_LEVEL == EvaluateLevelEnum.三级));
                    modelMineType.LEVEL4.Add(allrisk.Count(t => t.MineType == mineTypeInt && t.EVALUATE_LEVEL == EvaluateLevelEnum.四级));
                }
                riskPerformanceData.CHARTLIST.Add(modelMineType);
                #endregion

                #region 4
                PerformanceModel modelFXLB = new PerformanceModel();
                foreach (var type in distinctType)
                {
                    var countLevel1 = allrisk.Count(t => t.TYPE_ID == type.ID && t.EVALUATE_LEVEL == EvaluateLevelEnum.一级);
                    var countLevel2 = allrisk.Count(t => t.TYPE_ID == type.ID && t.EVALUATE_LEVEL == EvaluateLevelEnum.二级);
                    var countLevel3 = allrisk.Count(t => t.TYPE_ID == type.ID && t.EVALUATE_LEVEL == EvaluateLevelEnum.三级);
                    var countLevel4 = allrisk.Count(t => t.TYPE_ID == type.ID && t.EVALUATE_LEVEL == EvaluateLevelEnum.四级);
                    var totalCount = countLevel1 + countLevel2 + countLevel3 + countLevel4;
                    if (totalCount == 0)
                    {
                        continue;
                    }
                    modelFXLB.NAME.Add(type.NAME);
                    modelFXLB.LEVEL1.Add(countLevel1);
                    modelFXLB.LEVEL2.Add(countLevel2);
                    modelFXLB.LEVEL3.Add(countLevel3);
                    modelFXLB.LEVEL4.Add(countLevel4);
                    modelFXLB.TOTAL.Add(totalCount);
                }
                var newModelFXLB = SortByTotal(modelFXLB);
                riskPerformanceData.CHARTLIST.Add(modelFXLB);
                #endregion

                #region 5
                PerformanceModel modelZRDY = new PerformanceModel();
                foreach (var department in distinctDepartment)
                {
                    var countLevel1 = allrisk.Count(t => t.SOURCE_DEPARTMENT_ID == department.ID && t.EVALUATE_LEVEL == EvaluateLevelEnum.一级);
                    var countLevel2 = allrisk.Count(t => t.SOURCE_DEPARTMENT_ID == department.ID && t.EVALUATE_LEVEL == EvaluateLevelEnum.二级);
                    var countLevel3 = allrisk.Count(t => t.SOURCE_DEPARTMENT_ID == department.ID && t.EVALUATE_LEVEL == EvaluateLevelEnum.三级);
                    var countLevel4 = allrisk.Count(t => t.SOURCE_DEPARTMENT_ID == department.ID && t.EVALUATE_LEVEL == EvaluateLevelEnum.四级);
                    if (countLevel1 + countLevel2 + countLevel3 + countLevel4 == 0)
                    {
                        continue;
                    }
                    modelZRDY.NAME.Add(department.NAME);
                    modelZRDY.LEVEL1.Add(countLevel1);
                    modelZRDY.LEVEL2.Add(countLevel2);
                    modelZRDY.LEVEL3.Add(countLevel3);
                    modelZRDY.LEVEL4.Add(countLevel4);
                }
                riskPerformanceData.CHARTLIST.Add(modelZRDY);
                #endregion

                #region 6
                PerformanceModel modelDepartmentType = new PerformanceModel();
                foreach (FMDepartmentType level in Enum.GetValues(typeof(FMDepartmentType)))
                {
                    var levelName = level.GetDescription();
                    modelDepartmentType.NAME.Add(levelName);
                    modelDepartmentType.LEVEL1.Add(allrisk.Count(t => t.LEVEL == level && t.EVALUATE_LEVEL == EvaluateLevelEnum.一级));
                    modelDepartmentType.LEVEL2.Add(allrisk.Count(t => t.LEVEL == level && t.EVALUATE_LEVEL == EvaluateLevelEnum.二级));
                    modelDepartmentType.LEVEL3.Add(allrisk.Count(t => t.LEVEL == level && t.EVALUATE_LEVEL == EvaluateLevelEnum.三级));
                    modelDepartmentType.LEVEL4.Add(allrisk.Count(t => t.LEVEL == level && t.EVALUATE_LEVEL == EvaluateLevelEnum.四级));
                }
                riskPerformanceData.CHARTLIST.Add(modelDepartmentType);
                #endregion

                #region 7
                PerformanceModel modelArea = new PerformanceModel();
                foreach (var area in distinctArea)
                {
                    var countLevel1 = allrisk.Count(t => t.AREA_ID == area.ID && t.EVALUATE_LEVEL == EvaluateLevelEnum.一级);
                    var countLevel2 = allrisk.Count(t => t.AREA_ID == area.ID && t.EVALUATE_LEVEL == EvaluateLevelEnum.二级);
                    var countLevel3 = allrisk.Count(t => t.AREA_ID == area.ID && t.EVALUATE_LEVEL == EvaluateLevelEnum.三级);
                    var countLevel4 = allrisk.Count(t => t.AREA_ID == area.ID && t.EVALUATE_LEVEL == EvaluateLevelEnum.四级);
                    var totalArea = countLevel1 + countLevel2 + countLevel3 + countLevel4;
                    if (totalArea == 0)
                    {
                        continue;
                    }
                    modelArea.NAME.Add(area.NAME);
                    modelArea.LEVEL1.Add(countLevel1);
                    modelArea.LEVEL2.Add(countLevel2);
                    modelArea.LEVEL3.Add(countLevel3);
                    modelArea.LEVEL4.Add(countLevel4);
                    modelArea.TOTAL.Add(totalArea);
                }
                var newModelArea = SortByTotal(modelArea);
                riskPerformanceData.CHARTLIST.Add(newModelArea);
                #endregion

                #region 8
                var minTypeArr = new int[] { 30, 10, 20, 0 };
                var levelArr = new int[] { 3, 0, 1, 2 };
                foreach (var minetype in minTypeArr)
                {
                    var templevel1 = allrisk.Where(t => t.MineType == minetype && t.EVALUATE_LEVEL == EvaluateLevelEnum.一级);
                    var templevel2 = allrisk.Where(t => t.MineType == minetype && t.EVALUATE_LEVEL == EvaluateLevelEnum.二级);
                    var templevel3 = allrisk.Where(t => t.MineType == minetype && t.EVALUATE_LEVEL == EvaluateLevelEnum.三级);
                    var templevel4 = allrisk.Where(t => t.MineType == minetype && t.EVALUATE_LEVEL == EvaluateLevelEnum.四级);

                    PerformanceModel modelSCDY = new PerformanceModel();
                    modelSCDY.NAME = new List<string> { "公司", "部门", "车间", "班组" };
                    modelSCDY.LEVEL1 = new List<int> { templevel1.Count(t => (int)t.LEVEL == levelArr[0]), templevel1.Count(t => (int)t.LEVEL == levelArr[1]), templevel1.Count(t => (int)t.LEVEL == levelArr[2]), templevel1.Count(t => (int)t.LEVEL == levelArr[3]) };
                    modelSCDY.LEVEL2 = new List<int> { templevel2.Count(t => (int)t.LEVEL == levelArr[0]), templevel2.Count(t => (int)t.LEVEL == levelArr[1]), templevel2.Count(t => (int)t.LEVEL == levelArr[2]), templevel2.Count(t => (int)t.LEVEL == levelArr[3]) };
                    modelSCDY.LEVEL3 = new List<int> { templevel3.Count(t => (int)t.LEVEL == levelArr[0]), templevel3.Count(t => (int)t.LEVEL == levelArr[1]), templevel3.Count(t => (int)t.LEVEL == levelArr[2]), templevel3.Count(t => (int)t.LEVEL == levelArr[3]) };
                    modelSCDY.LEVEL4 = new List<int> { templevel4.Count(t => (int)t.LEVEL == levelArr[0]), templevel4.Count(t => (int)t.LEVEL == levelArr[1]), templevel4.Count(t => (int)t.LEVEL == levelArr[2]), templevel4.Count(t => (int)t.LEVEL == levelArr[3]) };
                    riskPerformanceData.SCDYLIST.Add(modelSCDY);
                }
                #endregion
                #region 9
                foreach (var level in levelArr)
                {
                    var templevel1 = allrisk.Where(t => (int)t.LEVEL == level && t.EVALUATE_LEVEL == EvaluateLevelEnum.一级);
                    var templevel2 = allrisk.Where(t => (int)t.LEVEL == level && t.EVALUATE_LEVEL == EvaluateLevelEnum.二级);
                    var templevel3 = allrisk.Where(t => (int)t.LEVEL == level && t.EVALUATE_LEVEL == EvaluateLevelEnum.三级);
                    var templevel4 = allrisk.Where(t => (int)t.LEVEL == level && t.EVALUATE_LEVEL == EvaluateLevelEnum.四级);

                    PerformanceModel modelCJ = new PerformanceModel();
                    modelCJ.NAME = new List<string> { "露天矿", "选矿厂", "尾矿厂", "职能部门" };
                    modelCJ.LEVEL1 = new List<int> { templevel1.Count(t => (int)t.MineType == minTypeArr[0]), templevel1.Count(t => (int)t.MineType == minTypeArr[1]), templevel1.Count(t => (int)t.MineType == minTypeArr[2]), templevel1.Count(t => (int)t.MineType == minTypeArr[3]) };
                    modelCJ.LEVEL2 = new List<int> { templevel2.Count(t => (int)t.MineType == minTypeArr[0]), templevel2.Count(t => (int)t.MineType == minTypeArr[1]), templevel2.Count(t => (int)t.MineType == minTypeArr[2]), templevel2.Count(t => (int)t.MineType == minTypeArr[3]) };
                    modelCJ.LEVEL3 = new List<int> { templevel3.Count(t => (int)t.MineType == minTypeArr[0]), templevel3.Count(t => (int)t.MineType == minTypeArr[1]), templevel3.Count(t => (int)t.MineType == minTypeArr[2]), templevel3.Count(t => (int)t.MineType == minTypeArr[3]) };
                    modelCJ.LEVEL4 = new List<int> { templevel4.Count(t => (int)t.MineType == minTypeArr[0]), templevel4.Count(t => (int)t.MineType == minTypeArr[1]), templevel4.Count(t => (int)t.MineType == minTypeArr[2]), templevel4.Count(t => (int)t.MineType == minTypeArr[3]) };
                    riskPerformanceData.CJLIST.Add(modelCJ);
                }
                #endregion
                #region 10
                List<PerformanceModel> SubZRDY = new List<PerformanceModel>();
                foreach (int minetype in minTypeArr)
                {
                    PerformanceModel modelSubZRDY = new PerformanceModel();
                    foreach (var team in distinctTeamDepartment)
                    {
                        var countLevel1 = allrisk.Count(t => t.DEPARTMENT_LIABLE_ID == team.ID && t.MineType == minetype && t.EVALUATE_LEVEL == EvaluateLevelEnum.一级);
                        var countLevel2 = allrisk.Count(t => t.DEPARTMENT_LIABLE_ID == team.ID && t.MineType == minetype && t.EVALUATE_LEVEL == EvaluateLevelEnum.二级);
                        var countLevel3 = allrisk.Count(t => t.DEPARTMENT_LIABLE_ID == team.ID && t.MineType == minetype && t.EVALUATE_LEVEL == EvaluateLevelEnum.三级);
                        var countLevel4 = allrisk.Count(t => t.DEPARTMENT_LIABLE_ID == team.ID && t.MineType == minetype && t.EVALUATE_LEVEL == EvaluateLevelEnum.四级);
                        var totalZRDY = countLevel1 + countLevel2 + countLevel3 + countLevel4;
                        if (totalZRDY == 0)
                        {
                            continue;
                        }
                        modelSubZRDY.NAME.Add(team.NAME);
                        modelSubZRDY.LEVEL1.Add(countLevel1);
                        modelSubZRDY.LEVEL2.Add(countLevel2);
                        modelSubZRDY.LEVEL3.Add(countLevel3);
                        modelSubZRDY.LEVEL4.Add(countLevel4);
                        modelSubZRDY.TOTAL.Add(totalZRDY);
                    }
                    SubZRDY.Add(SortByTotal(modelSubZRDY));
                }
                riskPerformanceData.TEAMLIST = SubZRDY;
                #endregion
                #region 11
                List<PerformanceModel> SubQY = new List<PerformanceModel>();
                foreach (int minetype in minTypeArr)
                {
                    PerformanceModel modelSubQY = new PerformanceModel();
                    foreach (var area in distinctArea)
                    {
                        var countLevel1 = allrisk.Count(t => t.AREA_ID == area.ID && t.MineType == minetype && t.EVALUATE_LEVEL == EvaluateLevelEnum.一级);
                        var countLevel2 = allrisk.Count(t => t.AREA_ID == area.ID && t.MineType == minetype && t.EVALUATE_LEVEL == EvaluateLevelEnum.二级);
                        var countLevel3 = allrisk.Count(t => t.AREA_ID == area.ID && t.MineType == minetype && t.EVALUATE_LEVEL == EvaluateLevelEnum.三级);
                        var countLevel4 = allrisk.Count(t => t.AREA_ID == area.ID && t.MineType == minetype && t.EVALUATE_LEVEL == EvaluateLevelEnum.四级);
                        var totalZRDY = countLevel1 + countLevel2 + countLevel3 + countLevel4;
                        if (totalZRDY == 0)
                        {
                            continue;
                        }
                        modelSubQY.NAME.Add(area.NAME);
                        modelSubQY.LEVEL1.Add(countLevel1);
                        modelSubQY.LEVEL2.Add(countLevel2);
                        modelSubQY.LEVEL3.Add(countLevel3);
                        modelSubQY.LEVEL4.Add(countLevel4);
                        modelSubQY.TOTAL.Add(totalZRDY);
                    }
                    SubQY.Add(SortByTotal(modelSubQY));
                }
                riskPerformanceData.AREALIST = SubQY;
                #endregion
                #region 12
                List<PerformanceModel> SubFXLB = new List<PerformanceModel>();
                foreach (int minetype in minTypeArr)
                {
                    PerformanceModel modelSubFXLB = new PerformanceModel();
                    foreach (var type in distinctType)
                    {
                        var countLevel1 = allrisk.Count(t => t.TYPE_ID == type.ID && t.MineType == minetype && t.EVALUATE_LEVEL == EvaluateLevelEnum.一级);
                        var countLevel2 = allrisk.Count(t => t.TYPE_ID == type.ID && t.MineType == minetype && t.EVALUATE_LEVEL == EvaluateLevelEnum.二级);
                        var countLevel3 = allrisk.Count(t => t.TYPE_ID == type.ID && t.MineType == minetype && t.EVALUATE_LEVEL == EvaluateLevelEnum.三级);
                        var countLevel4 = allrisk.Count(t => t.TYPE_ID == type.ID && t.MineType == minetype && t.EVALUATE_LEVEL == EvaluateLevelEnum.四级);
                        var totalZRDY = countLevel1 + countLevel2 + countLevel3 + countLevel4;
                        if (totalZRDY == 0)
                        {
                            continue;
                        }
                        modelSubFXLB.NAME.Add(type.NAME);
                        modelSubFXLB.LEVEL1.Add(countLevel1);
                        modelSubFXLB.LEVEL2.Add(countLevel2);
                        modelSubFXLB.LEVEL3.Add(countLevel3);
                        modelSubFXLB.LEVEL4.Add(countLevel4);
                        modelSubFXLB.TOTAL.Add(totalZRDY);
                    }
                    SubFXLB.Add(SortByTotal(modelSubFXLB));
                }
                riskPerformanceData.RISKTYPELIST = SubFXLB;
                #endregion
                #region 13

                PerformanceModel CHARTZYRW1 = new PerformanceModel();
                var allzyrw = GetEntities<T_HM_OPERATION_LINK>(t => t.IS_DELETED == false, new BaseFilter(filter.GetOrgId()));
                CHARTZYRW1.NAME = new List<string> { "许可作业", "关键任务", "一般任务" };
                var zy1 = allzyrw.Count(t => t.TASK_LEVEL == 1);
                var zy2 = allzyrw.Count(t => t.TASK_LEVEL == 2);
                var zy3 = allzyrw.Count(t => t.TASK_LEVEL == 3);
                CHARTZYRW1.LEVEL1 = new List<int> { zy1, zy2, zy3 };
                riskPerformanceData.CHARTZYRW1 = CHARTZYRW1;
                #endregion
                #region 2
                List<PerformanceModel1> modelZyrws = new List<PerformanceModel1> { };
                PerformanceModel1 modelZyrw1 = new PerformanceModel1();
                PerformanceModel1 modelZyrw2 = new PerformanceModel1();
                PerformanceModel1 modelZyrw3 = new PerformanceModel1();

                modelZyrw1.name = "许可作业";
                modelZyrw1.value = allzyrw.Count(t => t.TASK_LEVEL == 1);
                modelZyrws.Add(modelZyrw1);
                modelZyrw2.name = "关键任务";
                modelZyrw2.value = allzyrw.Count(t => t.TASK_LEVEL == 2);
                modelZyrws.Add(modelZyrw2);
                modelZyrw3.name = "一般任务";
                modelZyrw3.value = allzyrw.Count(t => t.TASK_LEVEL == 3);
                modelZyrws.Add(modelZyrw3);
                riskPerformanceData.CHARTZYRW2 = modelZyrws;
                #endregion
                #region
                var currMonth = DateTime.Now.Month;
                DateTime today = DateTime.Today;
                for (var i = 1; i < currMonth + 1; i++)
                {
                    DateTime endOfMonth = new DateTime(today.Year, i, 1).AddMonths(1).AddSeconds(-1);
                    dateCountModel riskDate = new dateCountModel();
                    riskDate.DATE = endOfMonth;
                    riskDate.COUNT = allrisk.Count(t => t.CREATE_TIME <= endOfMonth);
                    riskDate.TYPE = 0;
                    item3s.Add(riskDate);
                    dateCountModel hazardDate = new dateCountModel();
                    hazardDate.DATE = endOfMonth;
                    hazardDate.COUNT = allhazard.Count(t => t.CREATE_TIME <= endOfMonth); ;
                    hazardDate.TYPE = 1;
                    item3s.Add(hazardDate);
                }
                #endregion

                riskPerformanceData.DATECOUNTS = item3s.OrderBy(t => t.DATE).ToList();
                return riskPerformanceData;
            });
        }
        /// <summary>
        /// 风险库统计新
        /// </summary>
        /// <param name="pageFilter">返回系统用户数</param>
        /// <returns></returns>
        [HttpPost, Route("getRiskPerformanceData")]
        public JsonActionResult<riskPerformanceData> getRiskPerformanceData([FromBody] KeywordFilter filter)
        {
            return SafeExecute<riskPerformanceData>(() =>
            {
                var riskFilter = new BaseFilter(filter.GetOrgId());
                riskFilter.SelectField = new string[] { "EVALUATE_LEVEL", "CREATE_TIME", "PRODUCTION_UNIT_ID", "TYPE_ID", "AREA_ID", "ID" };
                IEnumerable<T_SK_ENTERPRISE_LIBRARY> allrisk = null;
                allrisk = GetEntities<T_SK_ENTERPRISE_LIBRARY>(t => t.ENABLE_STATUS == 0 && t.PRODUCTION_UNIT_ID != null, riskFilter);
                var libTempIds = allrisk.Select(t => t.ID);
                var details = GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL>(t => libTempIds.Contains(t.ENTERPRISE_LIBRARY_ID), new BaseFilter(filter.GetOrgId()));
                //var departs = GetEntities<T_SK_ENTERPRISE_LIBRARY_DEPART>(t => libIds.Contains(t.ENTERPRISE_LIBRARY_ID), new BaseFilter(filter.GetOrgId()));
                //var depIds = departs.Select(t=>t.DEPARTMENT_ID).Distinct();
                var libDetailIds = allrisk.Select(t => t.ID);
                var detailContents = GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT>(t => libDetailIds.Contains(t.ENTERPRISE_LIBRARY_DETAIL_ID), new BaseFilter(filter.GetOrgId()));
                var libDetailContentIds = detailContents.Select(t => t.ID);
                var detailContentChecks = GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART>(t => libDetailContentIds.Contains(t.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID), new BaseFilter(filter.GetOrgId()));
                var checkIds = detailContentChecks.Select(t => t.CHECK_TYPE_ID).Distinct();
                var hazardFilter = new BaseFilter(filter.GetOrgId());
                riskPerformanceData riskPerformanceData = new riskPerformanceData();
                List<dateCountModel> item3s = new List<dateCountModel>();
                var libType = allrisk.Select(t => t.TYPE_ID).Distinct().ToList();
                var distinctType = GetEntities<T_SK_RISK_TYPE>(t => libType.Contains(t.ID), new BaseFilter(filter.GetOrgId()));
                var departments = GetEntities<T_FM_DEPARTMENT>(t => t.ENABLE_STATUS == 0, new BaseFilter(filter.GetOrgId()));
                var distinctArea = GetEntities<T_SK_RISK_AREA>(t => t.IS_DELETED == false, new BaseFilter(filter.GetOrgId()));
                var distinctTeamDepartment = departments.Where(t => t.DEPARTMENT_TYPE == 20);
                #region 1
                PerformanceModel CHARTFXDJ1 = new PerformanceModel();
                CHARTFXDJ1.NAME = new List<string> { "重大风险", "较大风险", "一般风险", "低风险" };
                var type1 = allrisk.Count(t => t.EVALUATE_LEVEL == SKEvaluateLevelEnum.重大风险);
                var type2 = allrisk.Count(t => t.EVALUATE_LEVEL == SKEvaluateLevelEnum.较大风险);
                var type3 = allrisk.Count(t => t.EVALUATE_LEVEL == SKEvaluateLevelEnum.一般风险);
                var type4 = allrisk.Count(t => t.EVALUATE_LEVEL == SKEvaluateLevelEnum.低风险);
                CHARTFXDJ1.LEVEL1 = new List<int> { type1, type2, type3, type4 };
                riskPerformanceData.CHARTFXDJ1 = CHARTFXDJ1;
                #endregion
                #region 2
                List<PerformanceModel1> model2s = new List<PerformanceModel1> { };
                PerformanceModel1 model1 = new PerformanceModel1();
                PerformanceModel1 model2 = new PerformanceModel1();
                PerformanceModel1 model3 = new PerformanceModel1();
                PerformanceModel1 model4 = new PerformanceModel1();

                model1.name = "重大风险";
                model1.value = allrisk.Count(t => t.EVALUATE_LEVEL == SKEvaluateLevelEnum.重大风险);
                model2s.Add(model1);
                model2.name = "较大风险";
                model2.value = allrisk.Count(t => t.EVALUATE_LEVEL == SKEvaluateLevelEnum.较大风险);
                model2s.Add(model2);
                model3.name = "一般风险";
                model3.value = allrisk.Count(t => t.EVALUATE_LEVEL == SKEvaluateLevelEnum.一般风险);
                model2s.Add(model3);
                model4.name = "低风险";
                model4.value = allrisk.Count(t => t.EVALUATE_LEVEL == SKEvaluateLevelEnum.低风险);
                model2s.Add(model4);
                riskPerformanceData.CHARTFXDJ2 = model2s;
                #endregion


                #region 3
                var productionUnits = this.GetEntities<T_FM_USER_PRODUCTION_UNIT_SET>(t => t.IS_DELETED == false, new BaseFilter(filter.OrgId));
                var productIds = productionUnits.OrderBy(m => m.ID).Select(t => t.ID).ToList();
                PerformanceModel modelMineType = new PerformanceModel();
                foreach (var id in productIds)
                {
                    var mineTypeName = productionUnits.FirstOrDefault(t => t.ID == id)?.NAME;
                    modelMineType.NAME.Add(mineTypeName);
                    modelMineType.LEVEL1.Add(allrisk.Count(t => t.PRODUCTION_UNIT_ID == id && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.重大风险));
                    modelMineType.LEVEL2.Add(allrisk.Count(t => t.PRODUCTION_UNIT_ID == id && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.较大风险));
                    modelMineType.LEVEL3.Add(allrisk.Count(t => t.PRODUCTION_UNIT_ID == id && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.一般风险));
                    modelMineType.LEVEL4.Add(allrisk.Count(t => t.PRODUCTION_UNIT_ID == id && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.低风险));
                }
                riskPerformanceData.CHARTLIST.Add(modelMineType);
                #endregion

                #region 4
                PerformanceModel modelFXLB = new PerformanceModel();
                foreach (var type in distinctType)
                {
                    var countLevel1 = allrisk.Count(t => t.TYPE_ID == type.ID && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.重大风险);
                    var countLevel2 = allrisk.Count(t => t.TYPE_ID == type.ID && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.较大风险);
                    var countLevel3 = allrisk.Count(t => t.TYPE_ID == type.ID && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.一般风险);
                    var countLevel4 = allrisk.Count(t => t.TYPE_ID == type.ID && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.低风险);
                    var totalCount = countLevel1 + countLevel2 + countLevel3 + countLevel4;
                    if (totalCount == 0)
                    {
                        continue;
                    }
                    modelFXLB.NAME.Add(type.NAME);
                    modelFXLB.LEVEL1.Add(countLevel1);
                    modelFXLB.LEVEL2.Add(countLevel2);
                    modelFXLB.LEVEL3.Add(countLevel3);
                    modelFXLB.LEVEL4.Add(countLevel4);
                    modelFXLB.TOTAL.Add(totalCount);
                }
                var newModelFXLB = SortByTotal(modelFXLB);
                riskPerformanceData.CHARTLIST.Add(modelFXLB);
                #endregion

                #region 5
                //抓管控层级子表
                riskFilter.SelectField = new string[] { "ENTERPRISE_LIBRARY_ID", "DEPARTMENT_TYPE", "DEPARTMENT_ID", "USER_ID", "APPROVE_ROLE_ID", "ID" };
                var libMeasures = GetEntities<T_SK_ENTERPRISE_LIBRARY_DEPART>(t => t.IS_DELETED == false, riskFilter);
                var departIds = libMeasures.Select(t => t.DEPARTMENT_ID).Distinct().ToList();
                var distinctDepartment = departments.Where(t => departIds.Contains(t.ID)).ToList();
                PerformanceModel modelZRDY = new PerformanceModel();
                foreach (var department in distinctDepartment)
                {
                    var libIds = libMeasures.Where(t => t.DEPARTMENT_ID == department.ID).Select(m => m.ENTERPRISE_LIBRARY_ID).Distinct().ToList();
                    var countLevel1 = allrisk.Count(t => libIds.Contains(t.ID) && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.重大风险);
                    var countLevel2 = allrisk.Count(t => libIds.Contains(t.ID) && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.较大风险);
                    var countLevel3 = allrisk.Count(t => libIds.Contains(t.ID) && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.一般风险);
                    var countLevel4 = allrisk.Count(t => libIds.Contains(t.ID) && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.低风险);
                    if (countLevel1 + countLevel2 + countLevel3 + countLevel4 == 0)
                    {
                        continue;
                    }
                    modelZRDY.NAME.Add(department.NAME);
                    modelZRDY.LEVEL1.Add(countLevel1);
                    modelZRDY.LEVEL2.Add(countLevel2);
                    modelZRDY.LEVEL3.Add(countLevel3);
                    modelZRDY.LEVEL4.Add(countLevel4);
                }
                riskPerformanceData.CHARTLIST.Add(modelZRDY);
                #endregion

                #region 6
                PerformanceModel modelDepartmentType = new PerformanceModel();
                foreach (SKDepartmentTypeEnum level in Enum.GetValues(typeof(SKDepartmentTypeEnum)))
                {
                    var libIds = libMeasures.Where(t => t.DEPARTMENT_TYPE == level).Select(m => m.ENTERPRISE_LIBRARY_ID).Distinct().ToList();
                    var levelName = level.GetDescription();
                    modelDepartmentType.NAME.Add(levelName);
                    modelDepartmentType.LEVEL1.Add(allrisk.Count(t => libIds.Contains(t.ID) && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.重大风险));
                    modelDepartmentType.LEVEL2.Add(allrisk.Count(t => libIds.Contains(t.ID) && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.较大风险));
                    modelDepartmentType.LEVEL3.Add(allrisk.Count(t => libIds.Contains(t.ID) && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.一般风险));
                    modelDepartmentType.LEVEL4.Add(allrisk.Count(t => libIds.Contains(t.ID) && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.低风险));
                }
                riskPerformanceData.CHARTLIST.Add(modelDepartmentType);
                #endregion

                #region 7
                PerformanceModel modelArea = new PerformanceModel();
                foreach (var area in distinctArea)
                {
                    var countLevel1 = allrisk.Count(t => t.AREA_ID == area.ID && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.重大风险);
                    var countLevel2 = allrisk.Count(t => t.AREA_ID == area.ID && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.较大风险);
                    var countLevel3 = allrisk.Count(t => t.AREA_ID == area.ID && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.一般风险);
                    var countLevel4 = allrisk.Count(t => t.AREA_ID == area.ID && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.低风险);
                    var totalArea = countLevel1 + countLevel2 + countLevel3 + countLevel4;
                    if (totalArea == 0)
                    {
                        continue;
                    }
                    modelArea.NAME.Add(area.NAME);
                    modelArea.LEVEL1.Add(countLevel1);
                    modelArea.LEVEL2.Add(countLevel2);
                    modelArea.LEVEL3.Add(countLevel3);
                    modelArea.LEVEL4.Add(countLevel4);
                    modelArea.TOTAL.Add(totalArea);
                }
                var newModelArea = SortByTotal(modelArea);
                riskPerformanceData.CHARTLIST.Add(newModelArea);
                #endregion

                #region 8
                var levelArr = new int[] { 5, 10, 15, 20 };
                var names= new string[] { "露天矿", "选矿厂", "地下矿", "尾矿库" }.ToList();
                var productUnitIds = productionUnits.Where(t => names.Contains(t.NAME)).OrderBy(t=>t.NAME == "尾矿库").ThenBy(t => t.NAME == "地下矿").ThenBy(t => t.NAME == "选矿厂").ThenBy(t => t.NAME == "露天矿").Select(m => m.ID).ToList();
                foreach (var id in productUnitIds)
                {
                    var mineTypeName = productionUnits.FirstOrDefault(t => t.ID == id)?.NAME;
                    var templevel1 = allrisk.Where(t => t.PRODUCTION_UNIT_ID == id && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.重大风险).ToList();
                    var templevel2 = allrisk.Where(t => t.PRODUCTION_UNIT_ID == id && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.较大风险).ToList();
                    var templevel3 = allrisk.Where(t => t.PRODUCTION_UNIT_ID == id && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.一般风险).ToList();
                    var templevel4 = allrisk.Where(t => t.PRODUCTION_UNIT_ID == id && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.低风险).ToList();
                    var libIds1 = libMeasures.Where(t => t.DEPARTMENT_TYPE.GetInt() == levelArr[0]).Select(m => m.ENTERPRISE_LIBRARY_ID).Distinct().ToList();
                    var libIds2 = libMeasures.Where(t => t.DEPARTMENT_TYPE.GetInt() == levelArr[1]).Select(m => m.ENTERPRISE_LIBRARY_ID).Distinct().ToList();
                    var libIds3 = libMeasures.Where(t => t.DEPARTMENT_TYPE.GetInt() == levelArr[2]).Select(m => m.ENTERPRISE_LIBRARY_ID).Distinct().ToList();
                    var libIds4 = libMeasures.Where(t => t.DEPARTMENT_TYPE.GetInt() == levelArr[3]).Select(m => m.ENTERPRISE_LIBRARY_ID).Distinct().ToList();
                    PerformanceModel modelSCDY = new PerformanceModel();
                    modelSCDY.NAME = new List<string> { "公司", "部门", "车间", "班组" };
                    modelSCDY.LEVEL1 = new List<int> { templevel1.Count(t => libIds1.Contains(t.ID)), templevel1.Count(t => libIds2.Contains(t.ID)), templevel1.Count(t => libIds3.Contains(t.ID)), templevel1.Count(t => libIds4.Contains(t.ID)) };
                    modelSCDY.LEVEL2 = new List<int> { templevel2.Count(t => libIds1.Contains(t.ID)), templevel2.Count(t => libIds2.Contains(t.ID)), templevel2.Count(t => libIds3.Contains(t.ID)), templevel2.Count(t => libIds4.Contains(t.ID)) };
                    modelSCDY.LEVEL3 = new List<int> { templevel3.Count(t => libIds1.Contains(t.ID)), templevel3.Count(t => libIds2.Contains(t.ID)), templevel3.Count(t => libIds3.Contains(t.ID)), templevel3.Count(t => libIds4.Contains(t.ID)) };
                    modelSCDY.LEVEL4 = new List<int> { templevel4.Count(t => libIds1.Contains(t.ID)), templevel4.Count(t => libIds2.Contains(t.ID)), templevel4.Count(t => libIds3.Contains(t.ID)), templevel4.Count(t => libIds4.Contains(t.ID)) };
                    riskPerformanceData.SCDYLIST.Add(modelSCDY);
                }
                #endregion
                #region 9
                foreach (var level in levelArr)
                {
                    var libIds1 = libMeasures.Where(t => t.DEPARTMENT_TYPE.GetInt() == level).Select(m => m.ENTERPRISE_LIBRARY_ID).Distinct().ToList();
                    //var libIds2 = libMeasures.Where(t => t.DEPARTMENT_TYPE.GetInt() == levelArr[1]).Select(m => m.ENTERPRISE_LIBRARY_ID).Distinct().ToList();
                    //var libIds3 = libMeasures.Where(t => t.DEPARTMENT_TYPE.GetInt() == levelArr[2]).Select(m => m.ENTERPRISE_LIBRARY_ID).Distinct().ToList();
                    //var libIds4 = libMeasures.Where(t => t.DEPARTMENT_TYPE.GetInt() == levelArr[3]).Select(m => m.ENTERPRISE_LIBRARY_ID).Distinct().ToList();
                    var templevel1 = allrisk.Where(t => libIds1.Contains(t.ID) && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.重大风险);
                    var templevel2 = allrisk.Where(t => libIds1.Contains(t.ID) && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.较大风险);
                    var templevel3 = allrisk.Where(t => libIds1.Contains(t.ID) && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.一般风险);
                    var templevel4 = allrisk.Where(t => libIds1.Contains(t.ID) && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.低风险);

                    PerformanceModel modelCJ = new PerformanceModel();
                    modelCJ.NAME = new List<string> { "露天矿", "选矿厂", "地下矿", "尾矿库" };
                    var minTypeArr = productionUnits.Where(t => modelCJ.NAME.Contains(t.NAME)).OrderBy(t => t.NAME == "尾矿库").ThenBy(t => t.NAME == "地下矿").ThenBy(t => t.NAME == "选矿厂").ThenBy(t => t.NAME == "露天矿").Select(m => m.ID).ToList();
                    modelCJ.LEVEL1 = new List<int> { templevel1.Count(t => t.PRODUCTION_UNIT_ID == minTypeArr[0]), templevel1.Count(t => t.PRODUCTION_UNIT_ID == minTypeArr[1]), templevel1.Count(t => t.PRODUCTION_UNIT_ID == minTypeArr[2]), templevel1.Count(t => t.PRODUCTION_UNIT_ID == minTypeArr[3]) };
                    modelCJ.LEVEL2 = new List<int> { templevel2.Count(t => t.PRODUCTION_UNIT_ID == minTypeArr[0]), templevel2.Count(t => t.PRODUCTION_UNIT_ID == minTypeArr[1]), templevel2.Count(t => t.PRODUCTION_UNIT_ID == minTypeArr[2]), templevel2.Count(t => t.PRODUCTION_UNIT_ID == minTypeArr[3]) };
                    modelCJ.LEVEL3 = new List<int> { templevel3.Count(t => t.PRODUCTION_UNIT_ID == minTypeArr[0]), templevel3.Count(t => t.PRODUCTION_UNIT_ID == minTypeArr[1]), templevel3.Count(t => t.PRODUCTION_UNIT_ID == minTypeArr[2]), templevel3.Count(t => t.PRODUCTION_UNIT_ID == minTypeArr[3]) };
                    modelCJ.LEVEL4 = new List<int> { templevel4.Count(t => t.PRODUCTION_UNIT_ID == minTypeArr[0]), templevel4.Count(t => t.PRODUCTION_UNIT_ID == minTypeArr[1]), templevel4.Count(t => t.PRODUCTION_UNIT_ID == minTypeArr[2]), templevel4.Count(t => t.PRODUCTION_UNIT_ID == minTypeArr[3]) };
                    riskPerformanceData.CJLIST.Add(modelCJ);
                }
                #endregion
                #region 10
                List<PerformanceModel> SubZRDY = new List<PerformanceModel>();
                foreach (var id in productUnitIds)
                {
                    PerformanceModel modelSubZRDY = new PerformanceModel();
                    foreach (var department in distinctDepartment)
                    {
                        var libIds = libMeasures.Where(t => t.DEPARTMENT_ID == department.ID).Select(m => m.ENTERPRISE_LIBRARY_ID).Distinct().ToList();
                        var countLevel1 = allrisk.Count(t => libIds.Contains(t.ID) && t.PRODUCTION_UNIT_ID == id && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.重大风险);
                        var countLevel2 = allrisk.Count(t => libIds.Contains(t.ID) && t.PRODUCTION_UNIT_ID == id && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.较大风险);
                        var countLevel3 = allrisk.Count(t => libIds.Contains(t.ID) && t.PRODUCTION_UNIT_ID == id && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.一般风险);
                        var countLevel4 = allrisk.Count(t => libIds.Contains(t.ID) && t.PRODUCTION_UNIT_ID == id && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.低风险);
                        var totalZRDY = countLevel1 + countLevel2 + countLevel3 + countLevel4;
                        if (totalZRDY == 0)
                        {
                            continue;
                        }
                        modelSubZRDY.NAME.Add(department.NAME);
                        modelSubZRDY.LEVEL1.Add(countLevel1);
                        modelSubZRDY.LEVEL2.Add(countLevel2);
                        modelSubZRDY.LEVEL3.Add(countLevel3);
                        modelSubZRDY.LEVEL4.Add(countLevel4);
                        modelSubZRDY.TOTAL.Add(totalZRDY);
                    }
                    SubZRDY.Add(SortByTotal(modelSubZRDY));
                }
                riskPerformanceData.TEAMLIST = SubZRDY;
                #endregion
                #region 11
                List<PerformanceModel> SubQY = new List<PerformanceModel>();
                foreach (var id in productUnitIds)
                {
                    PerformanceModel modelSubQY = new PerformanceModel();
                    foreach (var area in distinctArea)
                    {
                        var countLevel1 = allrisk.Count(t => t.AREA_ID == area.ID && t.PRODUCTION_UNIT_ID == id && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.重大风险);
                        var countLevel2 = allrisk.Count(t => t.AREA_ID == area.ID && t.PRODUCTION_UNIT_ID == id && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.较大风险);
                        var countLevel3 = allrisk.Count(t => t.AREA_ID == area.ID && t.PRODUCTION_UNIT_ID == id && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.一般风险);
                        var countLevel4 = allrisk.Count(t => t.AREA_ID == area.ID && t.PRODUCTION_UNIT_ID == id && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.低风险);
                        var totalZRDY = countLevel1 + countLevel2 + countLevel3 + countLevel4;
                        if (totalZRDY == 0)
                        {
                            continue;
                        }
                        modelSubQY.NAME.Add(area.NAME);
                        modelSubQY.LEVEL1.Add(countLevel1);
                        modelSubQY.LEVEL2.Add(countLevel2);
                        modelSubQY.LEVEL3.Add(countLevel3);
                        modelSubQY.LEVEL4.Add(countLevel4);
                        modelSubQY.TOTAL.Add(totalZRDY);
                    }
                    SubQY.Add(SortByTotal(modelSubQY));
                }
                riskPerformanceData.AREALIST = SubQY;
                #endregion
                #region 12
                List<PerformanceModel> SubFXLB = new List<PerformanceModel>();
                foreach (var id in productUnitIds)
                {
                    PerformanceModel modelSubFXLB = new PerformanceModel();
                    foreach (var type in distinctType)
                    {
                        var countLevel1 = allrisk.Count(t => t.TYPE_ID == type.ID && t.PRODUCTION_UNIT_ID == id && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.重大风险);
                        var countLevel2 = allrisk.Count(t => t.TYPE_ID == type.ID && t.PRODUCTION_UNIT_ID == id && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.较大风险);
                        var countLevel3 = allrisk.Count(t => t.TYPE_ID == type.ID && t.PRODUCTION_UNIT_ID == id && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.一般风险);
                        var countLevel4 = allrisk.Count(t => t.TYPE_ID == type.ID && t.PRODUCTION_UNIT_ID == id && t.EVALUATE_LEVEL == SKEvaluateLevelEnum.低风险);
                        var totalZRDY = countLevel1 + countLevel2 + countLevel3 + countLevel4;
                        if (totalZRDY == 0)
                        {
                            continue;
                        }
                        modelSubFXLB.NAME.Add(type.NAME);
                        modelSubFXLB.LEVEL1.Add(countLevel1);
                        modelSubFXLB.LEVEL2.Add(countLevel2);
                        modelSubFXLB.LEVEL3.Add(countLevel3);
                        modelSubFXLB.LEVEL4.Add(countLevel4);
                        modelSubFXLB.TOTAL.Add(totalZRDY);
                    }
                    SubFXLB.Add(SortByTotal(modelSubFXLB));
                }
                riskPerformanceData.RISKTYPELIST = SubFXLB;
                #endregion
                #region 13

                PerformanceModel CHARTZYRW1 = new PerformanceModel();
                var allzyrw = GetEntities<T_HM_OPERATION_LINK>(t => t.IS_DELETED == false, new BaseFilter(filter.GetOrgId()));
                CHARTZYRW1.NAME = new List<string> { "许可作业", "关键任务", "一般任务" };
                var zy1 = allzyrw.Count(t => t.TASK_LEVEL == 1);
                var zy2 = allzyrw.Count(t => t.TASK_LEVEL == 2);
                var zy3 = allzyrw.Count(t => t.TASK_LEVEL == 3);
                CHARTZYRW1.LEVEL1 = new List<int> { zy1, zy2, zy3 };
                riskPerformanceData.CHARTZYRW1 = CHARTZYRW1;
                #endregion
                #region 2
                List<PerformanceModel1> modelZyrws = new List<PerformanceModel1> { };
                PerformanceModel1 modelZyrw1 = new PerformanceModel1();
                PerformanceModel1 modelZyrw2 = new PerformanceModel1();
                PerformanceModel1 modelZyrw3 = new PerformanceModel1();

                modelZyrw1.name = "许可作业";
                modelZyrw1.value = allzyrw.Count(t => t.TASK_LEVEL == 1);
                modelZyrws.Add(modelZyrw1);
                modelZyrw2.name = "关键任务";
                modelZyrw2.value = allzyrw.Count(t => t.TASK_LEVEL == 2);
                modelZyrws.Add(modelZyrw2);
                modelZyrw3.name = "一般任务";
                modelZyrw3.value = allzyrw.Count(t => t.TASK_LEVEL == 3);
                modelZyrws.Add(modelZyrw3);
                riskPerformanceData.CHARTZYRW2 = modelZyrws;
                #endregion
                #region
                var currMonth = DateTime.Now.Month;
                DateTime today = DateTime.Today;
                for (var i = 1; i < currMonth + 1; i++)
                {
                    DateTime endOfMonth = new DateTime(today.Year, i, 1).AddMonths(1).AddSeconds(-1);
                    dateCountModel riskDate = new dateCountModel();
                    riskDate.DATE = endOfMonth;
                    riskDate.COUNT = allrisk.Count(t => t.CREATE_TIME <= endOfMonth);
                    riskDate.TYPE = 0;
                    item3s.Add(riskDate);
                    //dateCountModel hazardDate = new dateCountModel();
                    //hazardDate.DATE = endOfMonth;
                    //hazardDate.COUNT = allhazard.Count(t => t.CREATE_TIME <= endOfMonth); ;
                    //hazardDate.TYPE = 1;
                    //item3s.Add(hazardDate);
                }
                #endregion

                riskPerformanceData.DATECOUNTS = item3s.OrderBy(t => t.DATE).ToList();
                return riskPerformanceData;
            });
        }
        public class safeTrainData
        {
            /// 年度培训计划完成率
            public int NUM1 { get; set; }
            /// 安全培训教育
            public int NUM2 { get; set; }
            /// 三级安全教育
            public int NUM3 { get; set; }
            /// 学时达标率
            public int NUM4 { get; set; }
            /// 培训优良率
            public int NUM5 { get; set; }
            /// 培训考核通过率
            public int NUM6 { get; set; }
            /// 题库总条数
            public int NUM7 { get; set; }
            public List<trainRecords> trainRecords { get; set; }
            public List<dateCountModel> dateCountModel { get; set; }


        }
        public class trainRecords
        {
            /// 课程名称
            public string NAME { get; set; }
            /// 培训起止时间
            public string TIMERANGE { get; set; }
            /// 应参训人数
            public int SHOULD_TRAINER { get; set; }
            /// 实际参训人数
            public int ACTUAL_TRAINER { get; set; }
            /// 参训率
            public string TRAINER_RATE { get; set; }
            /// 考核方式
            public string METHOD { get; set; }
            /// 通过率
            public string PASS_RATE { get; set; }
            /// 效果评估(优良率)
            public string EFFORT_RATE { get; set; }
        }
        /// <summary>
        /// 安全培训教育统计分析
        /// </summary>
        /// <param name="filter">返回系统用户数</param>
        /// <returns></returns>
        [HttpPost, Route("getSafeTrainData")]
        public JsonActionResult<safeTrainData> getSafeTrainData([FromBody] KeywordFilter filter)
        {
            return SafeExecute<safeTrainData>(() =>
            {
                var riskFilter = new BaseFilter(filter.GetOrgId());
                riskFilter.Include = new string[] { "Nav_Notify.Nav_TrainUserList", "Nav_Users", "Nav_Notify" };
                DateTime time = DateTime.Parse(filter.Parameter1);
                DateTime currYear = DateTime.Parse(time.Year + " 01-01 00:00:00");
                var startTime = time.AddDays(1 - time.Day);
                var endTime = time.AddDays(1 - time.Day).AddMonths(1);
                var records = GetEntities<T_SE_TRAIN_RECORD>(t => t.CREATE_TIME >= currYear && !t.IS_DELETED && t.STATUS != SETrainRecordStatus.已取消, riskFilter);
                var currMonthrecords = records.Where(t => t.CREATE_TIME > startTime && t.CREATE_TIME < endTime).OrderByDescending(t => t.Nav_Notify.TRAIN_START_TIME);//.OrderBy
                var recordids = currMonthrecords.Select(t => t.ID);
                var examFilter = new BaseFilter(filter.GetOrgId());
                examFilter.SelectField = new string[] { "USER_ID", "RECORD_ID", "SCORE" };
                var exams = GetEntities<T_SE_TRAIN_RECORD_PAPER>(t => recordids.Contains(t.RECORD_ID), examFilter).DistinctBy(t => t.USER_ID);
                var notifyIds = currMonthrecords.Select(t => t.NOTIFY_ID);
                var effectFilter = new BaseFilter(filter.GetOrgId());
                effectFilter.Include = new string[] { "Nav_ResultList" };
                var effects = GetEntities<T_SE_TRAINING_EFFECT_EVALUATION>(t => notifyIds.Contains((Guid)t.SURVEY_ID), effectFilter);

                List<trainRecords> trainRecords = new List<trainRecords>();
                int countPer = 0;
                int countPass = 0;
                foreach (var item in currMonthrecords)
                {
                    trainRecords trainRecord = new trainRecords();
                    trainRecord.NAME = item.Nav_Notify.NAME;
                    if (item.Nav_Notify.TRAIN_START_TIME.HasValue && item.Nav_Notify.TRAIN_END_TIME.HasValue && item.Nav_Notify.TRAIN_START_TIME.Value.Date == item.Nav_Notify.TRAIN_END_TIME.Value.Date)
                    {
                        trainRecord.TIMERANGE = item.Nav_Notify.TRAIN_START_TIME + " - " + item.Nav_Notify.TRAIN_END_TIME.Value.ToString("HH:mm:ss");
                    }
                    else
                    {
                        trainRecord.TIMERANGE = item.Nav_Notify.TRAIN_START_TIME + "-" + item.Nav_Notify.TRAIN_END_TIME;
                    }
                    trainRecord.SHOULD_TRAINER = item.Nav_Notify.Nav_TrainUserList.Where(e => !e.IS_DELETED).Count();//
                    trainRecord.ACTUAL_TRAINER = item.Nav_Users.Where(e => !e.IS_DELETED && e.OK).Count();//有签到

                    //trainRecord.METHOD = item.Nav_Notify.Nav_TrainCheckType.NAME;
                    //if (item.Nav_Notify.Nav_TrainCheckType.NAME == "笔试")

                    trainRecord.METHOD = item.Nav_Notify.CHECKTYPE.GetDescription();


                    #region      考试通过率  //T_SE_TRAIN_RECORD_USER SEExaminationResultsEnum? EXAMINATION_RESULTS { get; set; }

                    countPer = item.Nav_Users.Where(e => !e.IS_DELETED).Count();
                    countPass = item.Nav_Users.Where(e => !e.IS_DELETED && e.EXAMINATION_RESULTS.HasValue && e.EXAMINATION_RESULTS.Value == SEExaminationResultsEnum.合格).Count();
                    if (countPer == 0)
                    {
                        trainRecord.PASS_RATE = "1";
                    }
                    else
                    {
                        trainRecord.PASS_RATE = (countPass * 1.00 / countPer).ToString();
                    }

                    //if (item.Nav_Notify.CHECKTYPE == PlanCheckType.InOnLine)
                    //{
                    //    var currExams = exams.Where(t => t.RECORD_ID == item.ID);
                    //    //var currCount = currExams.Count();
                    //    var currCount = trainRecord.ACTUAL_TRAINER;//分母应该是 有参加培训的人数
                    //    if (currCount > 0)
                    //    {
                    //        var passExams = currExams.Where(t => t.SCORE >= 80);
                    //        var passCount = passExams.Count();
                    //        var rate = (passCount * 1.0 / currCount);
                    //        trainRecord.PASS_RATE = rate.ToString();
                    //        var ccc = (3 * 1.00 / 10).ToString();
                    //    }
                    //    else
                    //    {
                    //        trainRecord.PASS_RATE = "0";
                    //    }
                    //}
                    //else
                    //{
                    //    trainRecord.PASS_RATE = "1";
                    //} 

                    #endregion

                    if (item.Nav_Notify.NEED_EVALUATION == SETrainNeedSuvey.是)
                    {
                        var effect = effects.FirstOrDefault(t => t.SURVEY_ID == item.NOTIFY_ID);
                        if (effect != null)
                        {
                            var effectResult = effect.Nav_ResultList;
                            double sumTotal = 0;
                            foreach (var item2 in effectResult)
                            {
                                double num1 = Convert.ToDouble(item2.GOOD_RATION.Replace("%", ""));
                                double num2 = Convert.ToDouble(item2.BETTER_RATION.Replace("%", ""));
                                sumTotal += num1;
                                sumTotal += num2;
                            }
                            trainRecord.EFFORT_RATE = (1.00 * sumTotal / effectResult.Count()).ToString();
                        }
                        else
                        {
                            trainRecord.EFFORT_RATE = "100";
                        }
                    }
                    else
                    {
                        trainRecord.EFFORT_RATE = "-";

                    }
                    trainRecords.Add(trainRecord);
                }
                List<dateCountModel> item3s = new List<dateCountModel>();
                DateTime today = DateTime.Today;
                for (var i = 1; i < DateTime.Now.Month + 1; i++)
                {
                    DateTime startTime1 = new DateTime(today.Year, i, 1);
                    DateTime endTime1 = new DateTime(today.Year, i, 1).AddMonths(1).AddSeconds(-1);
                    dateCountModel riskDate = new dateCountModel();
                    riskDate.DATE = startTime1;
                    riskDate.COUNT = records.Count(t => t.CREATE_TIME >= startTime1 && t.CREATE_TIME <= endTime1);
                    item3s.Add(riskDate);
                }
                safeTrainData safeTrainData = new safeTrainData();
                safeTrainData.NUM1 = 1;
                safeTrainData.NUM2 = records.Count();
                safeTrainData.NUM3 = GetCount<T_SE_THREE_LEVEL_SAFE_EDU_CARD>(t => t.IS_DELETED == false, new BaseFilter(filter.GetOrgId()));
                safeTrainData.NUM4 = 13;
                safeTrainData.NUM5 = 14;
                safeTrainData.NUM6 = 15;
                safeTrainData.NUM7 = GetCount<T_SE_TEST>(t => t.IS_DELETED == false, new BaseFilter(filter.GetOrgId()));
                safeTrainData.trainRecords = trainRecords;
                safeTrainData.dateCountModel = item3s;
                return safeTrainData;
            });
        }
        ///// <summary>
        ///// 获取版本号
        ///// </summary>
        ///// <param name="pageFilter">获取版本号</param>
        ///// <returns></returns>
        //[HttpPost, Route("getVersion")]
        //public JsonActionResult<dynamic> getVersion([FromBody] KeywordFilter filter)
        //{
        //    return SafeExecute<dynamic>(() =>
        //    {
        //        dynamic ret = new System.Dynamic.ExpandoObject();
        //        using (var context = new MigrationContext(ConfigurationManager.ConnectionStrings["default"]))
        //        {
        //            var version = context.GetEntity<T_OP_VERSION>(i => i.IS_DELETED == false, new string[] { "VERSION_NO" });
        //            if (version != null)
        //            {
        //                ret = version.VERSION_NO;
        //            }
        //        }
        //        return ret;
        //    });
        //}

        public class notificationData
        {
            /// 模块
            public string NAME1 { get; set; }
            /// 表单名称
            public string NAME2 { get; set; }
            /// 待办数
            public double NAME3 { get; set; }
            /// 完成数
            public double NAME4 { get; set; }
            /// 完成率
            public string NAME5 { get; set; }
            /// 及时完成率
            public string NAME6 { get; set; }
            /// 总数
            public double NAME7 { get; set; }

        }
        /// <summary>
        /// 待办统计
        /// </summary>
        /// <param name="pageFilter">待办统计</param>
        /// <returns></returns>
        [HttpPost, Route("getNotificationTask")]
        public JsonActionResult<List<notificationData>> getNotificationTask([FromBody] KeywordFilter filter)
        {
            return SafeExecute<List<notificationData>>(() =>
            {
                dynamic ret = new System.Dynamic.ExpandoObject();
                var riskFilter = new BaseFilter(filter.GetOrgId());
                riskFilter.SelectField = new string[] { "NOTICE_STATUS", "SOURCE_FORMCODE" };
                DateTime currYear = DateTime.Parse(filter.Parameter1);
                var records = GetEntities<T_FM_NOTIFICATION_TASK>(t => t.CREATE_TIME > currYear, riskFilter);

                var formFilter = new BaseFilter(filter.GetOrgId());
                riskFilter.SelectField = new string[] { "CODE", "NAME" };
                var pfForms = GetEntities<T_PF_FORM>(t => t.IS_DELETED == false, riskFilter).Select(t => new { t.CODE, t.NAME }).Distinct();
                List<notificationData> notificationDatas = new List<notificationData>();

                foreach (var item in pfForms)
                {
                    var total = records.Where(t => t.SOURCE_FORMCODE == item.CODE);
                    double totalCount = total.Count();
                    if (totalCount > 0)
                    {

                        notificationData notificationData = new notificationData();
                        notificationData.NAME1 = item.CODE;
                        notificationData.NAME2 = item.NAME;
                        notificationData.NAME3 = total.Count(t => t.NOTICE_STATUS == 0);
                        notificationData.NAME4 = total.Count(t => t.NOTICE_STATUS > 0);
                        notificationData.NAME5 = ((notificationData.NAME4 / totalCount) * 100).ToString("0.00");
                        var inTime = total.Count(t => t.NOTICE_STATUS == 1);
                        notificationData.NAME6 = ((inTime / totalCount) * 100).ToString("0.00");
                        notificationData.NAME7 = totalCount;
                        notificationDatas.Add(notificationData);
                    }
                }
                return notificationDatas;
            });
        }

        public class schedulingData
        {
            /// 模块
            public string NAME1 { get; set; }
            /// 表单名称
            public string NAME2 { get; set; }
            /// 待办数
            public string NAME3 { get; set; }
            /// 完成数
            public string NAME4 { get; set; }
            /// 完成率
            public string NAME5 { get; set; }
            /// 及时完成率
            public string NAME6 { get; set; }
            /// 总数
            public int NAME7 { get; set; }

        }
        /// <summary>
        /// 待办统计
        /// </summary>
        /// <param name="pageFilter">待办统计</param>
        /// <returns></returns>
        [HttpPost, Route("getScheduling")]
        public JsonActionResult<List<schedulingData>> getScheduling([FromBody] KeywordFilter filter)
        {
            return SafeExecute<List<schedulingData>>(() =>
            {
                dynamic ret = new System.Dynamic.ExpandoObject();
                var filter1 = new BaseFilter(filter.GetOrgId());
                filter1.SelectField = new string[] { "ID", "NAME" };
                var teams = GetEntities<T_FM_TEAM>(t => t.ENABLE_STATUS == 0, filter1);

                var filter2 = new BaseFilter(filter.GetOrgId());
                filter2.SelectField = new string[] { "TEAM_ID", "DATE_TIME", "START_TIME", "END_TIME", "RUN_STATUS", "SHIFT_CLASS_RUN_STATUS" };
                DateTime today = DateTime.Now.AddDays(-3);
                var schedulings = GetEntities<T_FM_DEPARTMENT_SCHEDULING>(t => t.DATE_TIME > today, filter2).OrderBy(t => t.START_TIME);
                List<schedulingData> sDatas = new List<schedulingData>();

                foreach (var item in teams)
                {
                    var total = schedulings.Where(t => t.TEAM_ID == item.ID);
                    double totalCount = total.Count();
                    if (totalCount > 0)
                    {
                        schedulingData Data = new schedulingData();
                        Data.NAME1 = item.NAME;
                        var day1count = total.Count(t => t.DATE_TIME.Day == DateTime.Now.AddDays(-1).Day);
                        var day2count = total.Count(t => t.DATE_TIME.Day == DateTime.Now.AddDays(0).Day);
                        var day3count = total.Count(t => t.DATE_TIME.Day == DateTime.Now.AddDays(1).Day);
                        var day4count = total.Count(t => t.DATE_TIME.Day == DateTime.Now.AddDays(2).Day);
                        var day5count = total.Count(t => t.DATE_TIME.Day == DateTime.Now.AddDays(3).Day);
                        var day6count = total.Count(t => t.DATE_TIME.Day == DateTime.Now.AddDays(4).Day);
                        var day1 = total.FirstOrDefault(t => t.DATE_TIME.Day == DateTime.Now.AddDays(-1).Day);
                        var day2 = total.FirstOrDefault(t => t.DATE_TIME.Day == DateTime.Now.AddDays(0).Day);
                        var day3 = total.FirstOrDefault(t => t.DATE_TIME.Day == DateTime.Now.AddDays(1).Day);
                        var day4 = total.FirstOrDefault(t => t.DATE_TIME.Day == DateTime.Now.AddDays(2).Day);
                        var day5 = total.FirstOrDefault(t => t.DATE_TIME.Day == DateTime.Now.AddDays(3).Day);


                        Data.NAME2 = day1 != null ? day1count + "|" + (day1.RUN_STATUS ? "✔" : "❌") + "|" + (day1.SHIFT_CLASS_RUN_STATUS ? "✔" : "❌") + "|" + day1.START_TIME.ToShortTimeString() + "~" + day1.END_TIME.ToShortTimeString() : "";
                        Data.NAME3 = day2 != null ? day2count + "|" + (day2.RUN_STATUS ? "✔" : "❌") + "|" + (day2.SHIFT_CLASS_RUN_STATUS ? "✔" : "❌") + "|" + day2.START_TIME.ToShortTimeString() + "~" + day2.END_TIME.ToShortTimeString() : "";
                        Data.NAME4 = day3 != null ? day3count + "|" + (day3.RUN_STATUS ? "✔" : "❌") + "|" + (day3.SHIFT_CLASS_RUN_STATUS ? "✔" : "❌") + "|" + day3.START_TIME.ToShortTimeString() + "~" + day3.END_TIME.ToShortTimeString() : "";
                        Data.NAME5 = day4 != null ? day4count + "|" + (day4.RUN_STATUS ? "✔" : "❌") + "|" + (day4.SHIFT_CLASS_RUN_STATUS ? "✔" : "❌") + "|" + day4.START_TIME.ToShortTimeString() + "~" + day4.END_TIME.ToShortTimeString() : "";
                        Data.NAME6 = day5 != null ? day5count + "|" + (day5.RUN_STATUS ? "✔" : "❌") + "|" + (day5.SHIFT_CLASS_RUN_STATUS ? "✔" : "❌") + "|" + day5.START_TIME.ToShortTimeString() + "~" + day5.END_TIME.ToShortTimeString() : "";
                        Data.NAME7 = day2 != null ? day2.START_TIME.Hour : 0;
                        sDatas.Add(Data);
                    }
                }
                var orderData = sDatas.OrderBy(t => t.NAME1).ThenBy(t => t.NAME7).ToList();
                return orderData;
            });
        }

    }
}
