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.Domain.IServices.OP;
using APT.BaseData.Services.Services.FM;
using APT.BaseData.Services.Services.OP;
using APT.Infrastructure.Api;
using APT.Infrastructure.Core;
using APT.Migrations;
using APT.MS.Domain.Entities.BI;
using APT.MS.Domain.Entities.BS;
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 InfluxData.Net.InfluxDb.Enums;
using log4net.Core;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using MySqlX.XDevAPI.Common;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using static APT.SC.WebApi.Controllers.Api.BI.BIKanBanController;
using static Google.Protobuf.WireFormat;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;
using static NPOI.HSSF.Util.HSSFColor;

namespace APT.SC.WebApi.Controllers.Api.BI
{
    /// <summary>
    ///  看板
    /// </summary>
    [Route("api/BI/BIKanBanController")]
    public class BIKanBanController : APTApiController<T_FM_NOTIFICATION_TASK>
    {
        IOPTenantDBConnService OPTenantDBConnService { get; set; }
        public BIKanBanController(IOPTenantDBConnService opTenantDBConnService)
        {
            OPTenantDBConnService = opTenantDBConnService;
        }

        /// <summary>
        /// 返回所有
        /// </summary>
        public class ReturnAll
        {
            //风险等级占比
            public List<RiskTypeRate> riskTypeRate { get; set; }
            //当日工作票排名前三
            public List<JobTodayTop3> jobTodayTop3 { get; set; }
            //当日工作票统计数量
            public List<JobTodayQty> jobTodayQty { get; set; }
            //隐患整改率
            public HiddenRectify hiddenRectify { get; set; }

            //隐患统计数据
            public HiddenSummary hiddenSummary { get; set; }
            //各事项排名前三
            public List<TaskTop3> taskTop3 { get; set; }
            //作业现场完成情况统计
            public List<JobFinishRate> jobFinishRate { get; set; }
            //各公司安全检查统计
            public List<SafeCheckSum> safeCheckSum { get; set; }
            //各公司危险作业统计
            public List<LinkSum> linkSum { get; set; }

            public List<SETRAINSHOW> listSETrainSum { get; set; }
        }

        /// <summary>
        /// 风险等级占比
        /// </summary>
        public class RiskTypeRate
        {
            public string riskType { get; set; }
            public int count { get; set; }
            public string rate { get; set; }
        }
        /// <summary>
        /// 当日工作票排名前三
        /// </summary>
        public class JobTodayTop3
        {
            public int totalQty { get; set; }
            public int num { get; set; }
            public string company { get; set; }
            public List<JobTodayDetail> details { get; set; }
        }
        public class JobTodayDetail
        {
            public string company { get; set; }
            public string jobName { get; set; }
            public int qty { get; set; }
        }
        /// <summary>
        /// 当日工作票统计数量
        /// </summary>
        public class JobTodayQty
        {
            public int qty { get; set; }
            public Guid workTypeId { get; set; }

            public string name { get; set; }
        }
        /// <summary>
        /// 隐患整改率
        /// </summary>
        public class HiddenRectify
        {
            public int qty { get; set; }

            public int ontimeQty { get; set; }
            public int delayQty { get; set; }

            public string rate { get; set; }
        }
        /// <summary>
        /// 隐患统计数据
        /// </summary>
        public class HiddenSummary
        {
            public int majorQty { get; set; }

            public int generalQty { get; set; }
            public int unfinishQty { get; set; }

            public int monthMajorQty { get; set; }

            public int unfinishMonthMajorQty { get; set; }
            public int monthGeneralQty { get; set; }
            public int unfinishMonthGeneralQty { get; set; }
        }
        /// <summary>
        /// 各事项排名前三
        /// </summary>
        public class TaskTopTemp
        {
            public int totalQty { get; set; }
            public int qty { get; set; }
            public string company { get; set; }
            public string type { get; set; }
        }
        public class TaskTop3
        {
            public int totalQty { get; set; }
            public string company { get; set; }
            public List<TaskTopDetail> details { get; set; }
        }
        public class TaskTopDetail
        {
            public string name { get; set; }
            public int qty { get; set; }
        }
        /// <summary>
        /// 作业现场完成情况统计
        /// </summary>
        public class JobFinishRate
        {
            public string name { get; set; }
            public int qty { get; set; }
            public int finishQty { get; set; }
            public string rate { get; set; }
        }
        /// <summary>
        /// 各公司安全检查统计
        /// </summary>
        public class SafeCheckSum
        {
            public string company { get; set; }
            public int qty { get; set; }
            public int num { get; set; }
        }
        /// <summary>
        /// 各公司危险作业统计
        /// </summary>
        public class LinkSum
        {
            public string name { get; set; }
            public int qty { get; set; }
        }
        /// <summary>
        /// 培训教育学时获取
        /// </summary>
        public class SETRAIN
        {
            /// <summary>
            /// 公司名称
            /// </summary>
            public string CN { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public Guid ORG_ID { get; set; }

            /// <summary>
            /// 培训时长
            /// </summary>
            public decimal TRAIN_HOUR { get; set; }

            /// <summary>
            /// 开始时间
            /// </summary>
            public DateTime START_TIME { get; set; }
        }
        public class SETRAINSHOW
        {
            /// <summary>
            /// 公司名称
            /// </summary>
            public string CN { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public Guid ORG_ID { get; set; }

            /// <summary>
            /// 当前年月
            /// </summary>
            public DateTime dtNowYM { get; set; }
            /// <summary>
            /// 当前年月-1
            /// </summary>
            public DateTime dtNowYM_1 { get; set; }
            public DateTime dtNowYM_2 { get; set; }
            public DateTime dtNowYM_3 { get; set; }
            public DateTime dtNowYM_4 { get; set; }
            public DateTime dtNowYM_5 { get; set; }

            /// <summary>
            /// 当前月 培训时长总和 
            /// </summary>
            public decimal SUM_TRAIN_HOUR { get; set; }

            /// <summary>
            /// 当前月-1 培训时长总和
            /// </summary>
            public decimal SUM_TRAIN_HOUR_1 { get; set; }
            /// <summary>
            /// 当前月-2 培训时长总和
            /// </summary>
            public decimal SUM_TRAIN_HOUR_2 { get; set; }
            /// <summary>
            /// 当前月-3 培训时长总和
            /// </summary>
            public decimal SUM_TRAIN_HOUR_3 { get; set; }
            /// <summary>
            /// 当前月-4 培训时长总和
            /// </summary>
            public decimal SUM_TRAIN_HOUR_4 { get; set; }
            /// <summary>
            /// 当前月-5 培训时长总和
            /// </summary>
            public decimal SUM_TRAIN_HOUR_5 { get; set; }

        }
        /// <summary>
        /// 返回看板所有接口
        /// </summary>
        /// <param name="filter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("ReturnAllData")]
        public JsonActionResult<ReturnAll> ReturnAllData([FromBody] KeywordFilter filter)
        {
            //string connhead = ConfigurationManager.ConnectionStrings["head"];
            JsonActionResult<ReturnAll> result = new JsonActionResult<ReturnAll>();
            result.Data = new ReturnAll();
            DataTable tableRisk = new DataTable();
            DataTable tableJob = new DataTable();
            DataTable tableJobGroup = new DataTable();
            DataTable tableHidden = new DataTable();
            DataTable tableTask = new DataTable();
            DataTable tableJobRate = new DataTable();
            DataTable tableSafeCheck = new DataTable();
            DataTable tableLink = new DataTable();

            //培训教育 对应统计
            var ListAllORG = GetEntities<T_FM_ORGANIZATION>(e => !e.IS_DELETED && e.CODE != "003", null, null).OrderBy(e => e.TENANT_CODE).ToList();
            string strConn = OPTenantDBConnService.GetConnByORGID(filter.OrgId.Value);//获取数据库链接
            List<string> listVNAME = new List<string>() { "vhome_Train_Hour" };//, "vhome_risk_type_data"  
            DataSet ds = new DataSet();
            GETDBDATA(strConn, listVNAME, ref ds);//获取视图 数据  listVNAME 与 ds.Tables 一一对应
            result.Data.listSETrainSum = GetTrainInfo(ds.Tables[0], ListAllORG);
            using (SqlConnection connection = new SqlConnection(strConn))
            {
                try
                {
                    connection.Open();
                    //风险等级占比
                    string sqlRisk = "select * from vhome_risk_type_data ";
                    SqlCommand comRisk = new SqlCommand(sqlRisk, connection);
                    SqlDataAdapter riskData = new SqlDataAdapter(comRisk);
                    riskData.Fill(tableRisk);
                    result.Data.riskTypeRate = RiskTypeRateData(tableRisk);
                    //当日工作票排名前三
                    //string sqlJob = "select * from vhome_jobtop3_today ";
                    //SqlCommand comJob = new SqlCommand(sqlJob, connection);
                    //SqlDataAdapter jobData = new SqlDataAdapter(comJob);
                    //jobData.Fill(tableJob);
                    //string sqlJobGroup = "select* from vhome_jobdata_today_group";
                    //SqlCommand comJobGroup = new SqlCommand(sqlJobGroup, connection);
                    //SqlDataAdapter jobGroupData = new SqlDataAdapter(comJobGroup);
                    //jobGroupData.Fill(tableJobGroup);
                    //result.Data.jobTodayTop3 = JobTodayTopData(filter.OrgId.Value, tableJob, tableJobGroup);
                    //当日工作票的统计数量
                    string sqlJob = "select * from vhome_jobToday ORDER BY NUM";
                    SqlCommand comJob = new SqlCommand(sqlJob, connection);
                    SqlDataAdapter jobData = new SqlDataAdapter(comJob);
                    jobData.Fill(tableJob);
                    result.Data.jobTodayQty = JobTodayQtyData(tableJob);
                    //隐患统计数据
                    string sqlHidden = "select * from vhome_hiddenSummary";
                    SqlCommand comHidden = new SqlCommand(sqlHidden, connection);
                    SqlDataAdapter hiddenData = new SqlDataAdapter(comHidden);
                    hiddenData.Fill(tableHidden);
                    result.Data.hiddenSummary = HiddenSummaryData(tableHidden);
                    //隐患整改率
                    //string sqlHidden = "select * from vhome_hidden_data_result ";
                    //SqlCommand comHidden = new SqlCommand(sqlHidden, connection);
                    //SqlDataAdapter hiddenData = new SqlDataAdapter(comHidden);
                    //hiddenData.Fill(tableHidden);
                    //result.Data.hiddenRectify = HiddenRectifyData(tableHidden);
                    //各事项排名前三
                    //string sqlTask = "select * from vhome_task_data_result ";
                    //SqlCommand comTask = new SqlCommand(sqlTask, connection);
                    //SqlDataAdapter taskData = new SqlDataAdapter(comTask);
                    //taskData.Fill(tableTask);
                    //result.Data.taskTop3 = TaskTopData(tableTask);
                    //作业现场完成情况统计
                    //string sqlJobRate = "select * from vhome_jobrecord_data ";
                    //SqlCommand comJobRate = new SqlCommand(sqlJobRate, connection);
                    //SqlDataAdapter jobRateData = new SqlDataAdapter(comJobRate);
                    //jobRateData.Fill(tableJobRate);
                    //result.Data.jobFinishRate = jobFinishRateData(tableJobRate);
                    //各公司安全检查统计
                    //string sqlSafecCheck = "select * from vhome_check_total ";
                    //SqlCommand comSafecCheck = new SqlCommand(sqlSafecCheck, connection);
                    //SqlDataAdapter safecCheckData = new SqlDataAdapter(comSafecCheck);
                    //safecCheckData.Fill(tableSafeCheck);
                    //result.Data.safeCheckSum = safeCheckSumData(tableSafeCheck);
                    //各公司危险分类统计
                    //string sqlLink = "select * from vhome_operationLink_data ";
                    //SqlCommand comLink = new SqlCommand(sqlLink, connection);
                    //SqlDataAdapter linkData = new SqlDataAdapter(comLink);
                    //linkData.Fill(tableLink);
                    //result.Data.linkSum = linkSumData(tableLink);

                    connection.Close();
                }
                catch (Exception ex)
                {
                    if (!string.IsNullOrEmpty(ex.StackTrace))
                        throw new Exception("错误日志：[StackTrace]" + ex.StackTrace);
                    else
                        throw new Exception("【" + HttpContext.Request.Path + "】错误日志：[Message]" + ex.Message);
                }
            }
            return result;
        }
        /// <summary>
        /// 获取视图数据 
        /// </summary>
        /// <param name="conn"></param>
        /// <param name="listVNAME"></param>
        /// <param name="DataADP">数据集</param>
        /// <exception cref="Exception"></exception>
        private void GETDBDATA(string conn, List<string> listVNAME, ref DataSet ds)
        {
            List<RiskTypeRate> result = new List<RiskTypeRate>();
            //DataTable Table = new DataTable();
            ds = new DataSet();
            using (SqlConnection connection = new SqlConnection(conn))
            {
                try
                {
                    connection.Open();
                    string sql = string.Empty;
                    foreach (var item in listVNAME)
                    {
                        sql += string.Format(" select * from {0} ", item);
                    }

                    using (SqlCommand Com = new SqlCommand(sql, connection))
                    {
                        SqlDataAdapter DataADP = new SqlDataAdapter(Com);
                        DataADP.Fill(ds);
                    }
                    connection.Close();
                }
                catch (Exception ex)
                {
                    if (!string.IsNullOrEmpty(ex.StackTrace))
                        throw new Exception("错误日志：[StackTrace]" + ex.StackTrace);
                    else
                        throw new Exception("【" + HttpContext.Request.Path + "】错误日志：[Message]" + ex.Message);
                }
            }
        }
        /// <summary>
        /// 风险等级占比
        /// </summary>
        /// <param name="filter">分页过滤实体</param>
        public List<RiskTypeRate> RiskTypeRateData(DataTable Table)
        {
            List<RiskTypeRate> result = new List<RiskTypeRate>();
            if (Table != null && Table.Rows.Count > 0)
            {
                foreach (DataRow item in Table.Rows)
                {
                    result.Add(new RiskTypeRate()
                    {
                        riskType = item["风险类别"] != null ? item["风险类别"].ToString() : null,
                        count = int.Parse(item["数量"].ToString()) != 0 ? int.Parse(item["数量"].ToString()) : 0,
                        rate = item["占比"] != null ? item["占比"].ToString() : "0"
                    });
                }
            }
            return result;
        }

        /// <summary>
        /// 当日工作票排名前三
        /// </summary>
        /// <param name="filter">参数</param>
        /// <returns></returns>
        public List<JobTodayTop3> JobTodayTopData(Guid orgId, DataTable Table, DataTable Table2)
        {
            List<JobTodayTop3> result = new List<JobTodayTop3>();
            var details = new List<JobTodayDetail>();
            if (Table != null && Table.Rows.Count > 0)
            {
                foreach (DataRow item in Table.Rows)
                {
                    var JobTodayTop3 = new JobTodayTop3();
                    JobTodayTop3.totalQty = int.Parse(item["今日总数"].ToString()) != 0 ? int.Parse(item["今日总数"].ToString()) : 0;
                    JobTodayTop3.num = int.Parse(item["排名"].ToString()) != 0 ? int.Parse(item["排名"].ToString()) : 0;
                    JobTodayTop3.company = item["公司名称"] != null ? item["公司名称"].ToString() : "";
                    result.Add(JobTodayTop3);
                }
            }
            if (Table2 != null && Table2.Rows.Count > 0)
            {
                foreach (DataRow item2 in Table2.Rows)
                {
                    var JobTodayDetail = new JobTodayDetail();
                    JobTodayDetail.qty = int.Parse(item2["cnt"].ToString()) != 0 ? int.Parse(item2["cnt"].ToString()) : 0;
                    JobTodayDetail.jobName = item2["stepid"] != null ? item2["stepid"].ToString() : null;
                    JobTodayDetail.company = item2["db_name"] != null ? item2["db_name"].ToString() : null;
                    details.Add(JobTodayDetail);
                }
            }
            if (result != null && result.Any())
            {
                foreach (var da in result)
                {
                    var temps = details.Where(t => t.company == da.company).ToList();
                    if (temps.Any())
                    {
                        var detailTemps = new List<JobTodayDetail>();
                        foreach (var de in temps)
                        {
                            var JobTodayDetail = new JobTodayDetail();
                            JobTodayDetail.qty = de.qty;
                            JobTodayDetail.jobName = de.jobName;
                            JobTodayDetail.company = de.company;
                            detailTemps.Add(JobTodayDetail);
                        }
                        da.details = detailTemps;
                    }
                }
            }
            return result;
        }
        /// <summary>
        /// 当日工作票统计数量
        /// </summary>
        /// <param name="filter">参数</param>
        /// <returns></returns>
        public List<JobTodayQty> JobTodayQtyData(DataTable Table)
        {
            List<JobTodayQty> result = new List<JobTodayQty>();
            if (Table != null && Table.Rows.Count > 0)
            {
                foreach (DataRow item in Table.Rows)
                {
                    result.Add(new JobTodayQty()
                    {
                        qty = int.Parse(Table.Rows[0]["QTY"].ToString()) != 0 ? int.Parse(Table.Rows[0]["QTY"].ToString()) : 0,
                        workTypeId = Guid.Parse(Table.Rows[0]["WORK_PERMIT_TYPE_ID"].ToString()),
                        name = Table.Rows[0]["NAME"] != null ? Table.Rows[0]["NAME"].ToString() : null
                    });
                }
            }
            return result;
        }
        /// <summary>
        /// 隐患整改率
        /// </summary>
        /// <param name="filter">参数</param>
        /// <returns></returns>
        public HiddenRectify HiddenRectifyData(DataTable Table)
        {
            HiddenRectify result = new HiddenRectify();
            if (Table != null && Table.Rows.Count > 0)
            {
                result.qty = int.Parse(Table.Rows[0]["隐患数"].ToString()) != 0 ? int.Parse(Table.Rows[0]["隐患数"].ToString()) : 0;
                result.ontimeQty = int.Parse(Table.Rows[0]["按期整改数"].ToString()) != 0 ? int.Parse(Table.Rows[0]["按期整改数"].ToString()) : 0;
                result.delayQty = int.Parse(Table.Rows[0]["延期整改数"].ToString()) != 0 ? int.Parse(Table.Rows[0]["延期整改数"].ToString()) : 0;
                result.rate = Table.Rows[0]["整改率"] != null ? Table.Rows[0]["整改率"].ToString() : null;
            }
            return result;
        }
        /// <summary>
        /// 隐患统计数据
        /// </summary>
        /// <param name="filter">参数</param>
        /// <returns></returns>
        public HiddenSummary HiddenSummaryData(DataTable Table)
        {
            HiddenSummary result = new HiddenSummary();
            if (Table != null && Table.Rows.Count > 0)
            {
                result.majorQty = int.Parse(Table.Rows[0]["majorQty"].ToString()) != 0 ? int.Parse(Table.Rows[0]["majorQty"].ToString()) : 0;
                result.generalQty = int.Parse(Table.Rows[0]["generalQty"].ToString()) != 0 ? int.Parse(Table.Rows[0]["generalQty"].ToString()) : 0;
                result.unfinishQty = int.Parse(Table.Rows[0]["unfinishQty"].ToString()) != 0 ? int.Parse(Table.Rows[0]["unfinishQty"].ToString()) : 0;
                result.monthMajorQty = int.Parse(Table.Rows[0]["monthMajorQty"].ToString()) != 0 ? int.Parse(Table.Rows[0]["monthMajorQty"].ToString()) : 0;
                result.unfinishMonthMajorQty = int.Parse(Table.Rows[0]["unfinishMonthMajorQty"].ToString()) != 0 ? int.Parse(Table.Rows[0]["unfinishMonthMajorQty"].ToString()) : 0;
                result.monthGeneralQty = int.Parse(Table.Rows[0]["monthGeneralQty"].ToString()) != 0 ? int.Parse(Table.Rows[0]["monthGeneralQty"].ToString()) : 0;
                result.unfinishMonthGeneralQty = int.Parse(Table.Rows[0]["unfinishMonthGeneralQty"].ToString()) != 0 ? int.Parse(Table.Rows[0]["unfinishMonthGeneralQty"].ToString()) : 0;
            }
            return result;
        }
        /// <summary>
        /// 各事项排名前三
        /// </summary>
        /// <param name="filter">参数</param>
        /// <returns></returns>
        public List<TaskTop3> TaskTopData(DataTable Table)
        {
            List<TaskTop3> result = new List<TaskTop3>();
            var dataTemps = new List<TaskTopTemp>();
            if (Table != null && Table.Rows.Count > 0)
            {
                foreach (DataRow item in Table.Rows)
                {
                    var JobTodayTop3 = new TaskTopTemp();
                    JobTodayTop3.totalQty = int.Parse(item["待办总数"].ToString()) != 0 ? int.Parse(item["待办总数"].ToString()) : 0;
                    JobTodayTop3.qty = int.Parse(item["数量"].ToString()) != 0 ? int.Parse(item["数量"].ToString()) : 0;
                    JobTodayTop3.company = item["公司名称"] != null ? item["公司名称"].ToString() : "";
                    JobTodayTop3.type = item["类型"] != null ? item["类型"].ToString() : "";
                    dataTemps.Add(JobTodayTop3);
                }
            }
            if (dataTemps != null && dataTemps.Any())
            {
                var dataGroup = dataTemps.GroupBy(t => new { t.company, t.totalQty }).ToList();
                foreach (var da in dataGroup)
                {
                    var TaskTop3 = new TaskTop3();
                    TaskTop3.company = da.Key.company;
                    TaskTop3.totalQty = da.Key.totalQty;
                    var temps = dataTemps.Where(t => t.company == da.Key.company).ToList();
                    if (temps.Any())
                    {
                        var detailTemps = new List<TaskTopDetail>();
                        foreach (var de in temps)
                        {
                            var JobTodayDetail = new TaskTopDetail();
                            JobTodayDetail.qty = de.qty;
                            JobTodayDetail.name = de.type;
                            detailTemps.Add(JobTodayDetail);
                        }
                        TaskTop3.details = detailTemps;
                    }
                    result.Add(TaskTop3);
                }
            }
            return result;
        }


        /// <summary>
        /// 作业现场完成情况统计
        /// </summary>
        /// <param name="filter">参数</param>
        /// <returns></returns>
        public List<JobFinishRate> jobFinishRateData(DataTable Table)
        {
            List<JobFinishRate> result = new List<JobFinishRate>();
            if (Table != null && Table.Rows.Count > 0)
            {
                foreach (DataRow item in Table.Rows)
                {
                    result.Add(new JobFinishRate()
                    {
                        name = item["表单名称"] != null ? item["表单名称"].ToString() : null,
                        qty = int.Parse(item["总数"].ToString()) != 0 ? int.Parse(item["总数"].ToString()) : 0,
                        finishQty = int.Parse(item["完成数"].ToString()) != 0 ? int.Parse(item["完成数"].ToString()) : 0,
                        rate = item["完成率"] != null ? item["完成率"].ToString() : null,
                    });
                }
            }
            return result;
        }


        /// <summary>
        /// 各公司安全检查统计
        /// </summary>
        /// <param name="filter">参数</param>
        /// <returns></returns>
        public List<SafeCheckSum> safeCheckSumData(DataTable Table)
        {
            List<SafeCheckSum> result = new List<SafeCheckSum>();
            if (Table != null && Table.Rows.Count > 0)
            {
                foreach (DataRow item in Table.Rows)
                {
                    result.Add(new SafeCheckSum()
                    {
                        company = item["公司名称"] != null ? item["公司名称"].ToString() : null,
                        qty = int.Parse(item["数量"].ToString()) != 0 ? int.Parse(item["数量"].ToString()) : 0,
                        num = int.Parse(item["排名"].ToString()) != 0 ? int.Parse(item["排名"].ToString()) : 0,
                    });
                }
            }
            return result;
        }
        /// <summary>
        /// 各公司危险作业统计
        /// </summary>
        /// <param name="filter">参数</param>
        /// <returns></returns>
        public List<LinkSum> linkSumData(DataTable Table)
        {
            List<LinkSum> result = new List<LinkSum>();
            if (Table != null && Table.Rows.Count > 0)
            {
                foreach (DataRow item in Table.Rows)
                {
                    result.Add(new LinkSum()
                    {
                        name = item["NAME"] != null ? item["NAME"].ToString() : null,
                        qty = !string.IsNullOrEmpty(item["cnt"].ToString()) && int.Parse(item["cnt"].ToString()) != 0 ? int.Parse(item["cnt"].ToString()) : 0
                    });
                }
            }
            return result;
        }
        /// <summary>
        /// 数据整理 培训教育
        /// </summary>
        /// <param name="dtTRAIN"></param>
        /// <param name="listORG"></param>
        /// <returns></returns>
        private List<SETRAINSHOW> GetTrainInfo(DataTable dtTRAIN, List<T_FM_ORGANIZATION> listORG)
        {
            List<SETRAIN> ListTRAIN = DataHelper.TableToList<SETRAIN>(dtTRAIN);
            List<SETRAINSHOW> dtInfo = new List<SETRAINSHOW>();
            //所有公司  按月 倒推 6 个月的数据
            List<DateTime> listDate = new List<DateTime>();
            DateTime dtNowYM = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-01 00:00:00"));
            for (int i = 0; i < 6; i++)
            {
                listDate.Add(dtNowYM.AddMonths(-1 * i));
            }
            foreach (var item in listORG)
            {
                SETRAINSHOW SUMCNPer = new SETRAINSHOW();
                SUMCNPer.ORG_ID = item.ORG_ID.Value;
                SUMCNPer.CN = item.NAME;
                SUMCNPer.dtNowYM = dtNowYM;
                SUMCNPer.dtNowYM_1 = listDate[1];
                SUMCNPer.dtNowYM_2 = listDate[2];
                SUMCNPer.dtNowYM_3 = listDate[3];
                SUMCNPer.dtNowYM_4 = listDate[4];
                SUMCNPer.dtNowYM_5 = listDate[5];
                SUMCNPer.SUM_TRAIN_HOUR = ListTRAIN.Where(e => e.ORG_ID == SUMCNPer.ORG_ID && e.START_TIME.Year == listDate[0].Year && e.START_TIME.Month == listDate[0].Month).Sum(e => e.TRAIN_HOUR);
                SUMCNPer.SUM_TRAIN_HOUR_1 = ListTRAIN.Where(e => e.ORG_ID == SUMCNPer.ORG_ID && e.START_TIME.Year == listDate[1].Year && e.START_TIME.Month == listDate[1].Month).Sum(e => e.TRAIN_HOUR);
                SUMCNPer.SUM_TRAIN_HOUR_2 = ListTRAIN.Where(e => e.ORG_ID == SUMCNPer.ORG_ID && e.START_TIME.Year == listDate[2].Year && e.START_TIME.Month == listDate[2].Month).Sum(e => e.TRAIN_HOUR);
                SUMCNPer.SUM_TRAIN_HOUR_3 = ListTRAIN.Where(e => e.ORG_ID == SUMCNPer.ORG_ID && e.START_TIME.Year == listDate[3].Year && e.START_TIME.Month == listDate[3].Month).Sum(e => e.TRAIN_HOUR);
                SUMCNPer.SUM_TRAIN_HOUR_4 = ListTRAIN.Where(e => e.ORG_ID == SUMCNPer.ORG_ID && e.START_TIME.Year == listDate[4].Year && e.START_TIME.Month == listDate[4].Month).Sum(e => e.TRAIN_HOUR);
                SUMCNPer.SUM_TRAIN_HOUR_5 = ListTRAIN.Where(e => e.ORG_ID == SUMCNPer.ORG_ID && e.START_TIME.Year == listDate[5].Year && e.START_TIME.Month == listDate[5].Month).Sum(e => e.TRAIN_HOUR);
                dtInfo.Add(SUMCNPer);
            }
            return dtInfo;
        }


        /// <summary>
        /// 获取子页 班前会 及时完成率
        /// </summary>
        /// <param name="filter"></param>
        [HttpPost, Route("TeamManage")]
        public JsonActionResult<List<dynamic>> TeamManage([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                Dictionary<string, object> dic = new Dictionary<string, object>();
                DateTime dtSecrch = DateTime.Now;
                if (string.IsNullOrEmpty(filter.Parameter1))
                {
                    filter.Parameter1 = dtSecrch.ToString("yyyy-MM-dd");
                }
                //年度查询
                if (!string.IsNullOrEmpty(filter.Parameter1))
                {
                    try
                    {
                        dtSecrch = Convert.ToDateTime(filter.Parameter1);
                    }
                    catch
                    {
                        dtSecrch = DateTime.Now;
                    }
                }
                dtSecrch = Convert.ToDateTime(dtSecrch.ToString("yyyy-MM-01 00:00:00"));
                dic.Add("@dtMin", dtSecrch.ToString("yyyy-MM-dd 00:00:00"));
                dic.Add("@dtMax", dtSecrch.AddMonths(1).AddSeconds(-1).ToString("yyyy-MM-dd 23:59:59"));

                List<dynamic> listResult = new List<dynamic>();
                try
                {
                    string strConn = OPTenantDBConnService.GetConnByORGID(filter.OrgId.Value);
                    DataSet ds = DBHelper.ExecProcedure(strConn, "proc_HomeSubTeamMeetingRecord", dic, HttpContext.Request.Path);
                    string percent = "";
                    if (ds != null && ds.Tables != null && ds.Tables.Count > 0)
                    {
                        foreach (DataRow item in ds.Tables[0].Rows)
                        {
                            percent = item[0].ToString();
                            if (percent.Contains("."))
                                percent = Convert.ToDouble(item[0].ToString()).ToString("0.00");
                            listResult.Add(new
                            {
                                companyName = item["CNAME"],
                                rate = percent + "%"
                            });
                        }
                    }
                }
                catch { }
                return listResult;
            });
        }


        /// <summary>
        /// 获取子页 隐患治理
        /// </summary>
        /// <param name="filter"></param>
        [HttpPost, Route("HiddenManage")]
        public JsonActionResult<HiddenManage> HiddenManage([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                //Parameter1 传入 年份（搜索年份对应任意时间）  不传取 对应月份的时间 
                //Parameter2 传入 月份（搜索月份对应任意时间）  不传 取当前时间
                //Parameter3 传入 ORGID 如果有
                Dictionary<string, object> dic = new Dictionary<string, object>();
                DateTime dtSecrch = DateTime.Now;
                //string ORGID = "";
                if (!string.IsNullOrEmpty(filter.Parameter2))
                {
                    try
                    {
                        dtSecrch = Convert.ToDateTime(Convert.ToDateTime(filter.Parameter2).ToString("yyyy-MM-01 00:00:00"));
                    }
                    catch
                    {
                        dtSecrch = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-01 00:00:00"));
                    }
                }
                //if (!string.IsNullOrEmpty(filter.Parameter3))
                //{
                //    try
                //    {
                //        ORGID = (new Guid(filter.Parameter3)).ToString();
                //    }
                //    catch
                //    {
                //        ORGID = "";
                //    }
                //}

                dic.Add("@dtMonthMin", dtSecrch.ToString("yyyy-MM-dd 00:00:00"));
                dic.Add("@dtMonthMax", dtSecrch.AddMonths(1).AddSeconds(-1).ToString("yyyy-MM-dd HH:mm:ss"));
                //dic.Add("@OrgId", ORGID.ToString());

                if (!string.IsNullOrEmpty(filter.Parameter1))
                {
                    try
                    {
                        dtSecrch = Convert.ToDateTime(filter.Parameter1);
                    }
                    catch
                    {
                        dtSecrch = DateTime.Now;
                    }
                }
                dic.Add("@dtMin", dtSecrch.ToString("yyyy-01-01 00:00:00"));
                if (dtSecrch.Year == DateTime.Now.Year)
                {
                    dic.Add("@dtMax", "");
                }
                else
                {
                    dic.Add("@dtMax", dtSecrch.ToString("yyyy-12-31 23:59:59"));
                }

                HiddenManage listResult = new HiddenManage();
                try
                {
                    string strConn = OPTenantDBConnService.GetConnByORGID(filter.OrgId.Value);
                    DataSet ds = DBHelper.ExecProcedure(strConn, "proc_HomeSubHiddenManage", dic, HttpContext.Request.Path);
                    if (ds != null && ds.Tables != null && ds.Tables.Count > 0)
                    {
                        List<dynamic> hiddenRanking = new List<dynamic>();
                        //int NUM = 1;
                        foreach (DataRow item in ds.Tables[0].Rows)
                        {
                            hiddenRanking.Add(new
                            {
                                //NUM = NUM,
                                companyName = item["companyName"],
                                ORG_ID = item["ORG_ID"],
                                hiddenName = item["DESCREPTION"],
                                qty = item["dc"],
                            });
                            //NUM++;
                        }
                        listResult.hiddenRanking = hiddenRanking;
                        //if (string.IsNullOrEmpty(ORGID))
                        //{
                        //全部搜索 3张表
                        List<dynamic> hiddenList = new List<dynamic>();
                        DataTable dt = ds.Tables[1];
                        foreach (DataRow item in dt.Rows)
                        {
                            hiddenList.Add(new
                            {
                                companyName = item["companyName"],
                                generalCount = item["generalCount"],
                                majorCount = item["majorCount"],
                            });
                        }
                        listResult.hiddenList = hiddenList;

                        List<dynamic> hiddenRectifyList = new List<dynamic>();
                        dt = ds.Tables[2];
                        foreach (DataRow item in dt.Rows)
                        {
                            hiddenRectifyList.Add(new
                            {
                                companyName = item["companyName"],
                                generalCount = item["generalCount"],
                                majorCount = item["majorCount"],
                                majorCountNo = item["majorCountNo"],
                                generalCountNo = item["generalCountNo"],
                            });
                        }
                        listResult.hiddenRectifyList = hiddenRectifyList;
                        //}
                    }
                }
                catch { }
                return listResult;
            });
        }

        /// <summary>
        /// 获取子页 风险管控
        /// </summary>
        /// <param name="filter"></param>
        [HttpPost, Route("RiskManage")]
        public JsonActionResult<RiskManage> RiskManage([FromBody] KeywordFilter filter)
        {
            JsonActionResult<RiskManage> result = new JsonActionResult<RiskManage>();
            result.Data = new RiskManage();
            DataTable tableRiskList = new DataTable();
            DataTable tableRiskType = new DataTable();
            List<RiskTempList> riskTempList = new List<RiskTempList>();
            List<RiskList> riskList = new List<RiskList>();
            List<RiskTypeList> riskTypeList = new List<RiskTypeList>();
            List<T_FM_ORGANIZATION> orgList = new List<T_FM_ORGANIZATION>();
            string strConn = OPTenantDBConnService.GetConnByORGID(filter.OrgId.Value);//获取数据库链接
            using (var context = new MigrationContext(strConn))
            {
                Expression<Func<T_FM_ORGANIZATION, bool>> expression = e => !e.IS_DELETED;
                Dictionary<string, DbOrder> orders = new Dictionary<string, DbOrder>();
                orders.Add("CREATE_TIME", DbOrder.DESC);
                orgList = context.GetOrderEntities(expression, orders, null).ToList();
            }
            using (SqlConnection connection = new SqlConnection(strConn))
            {
                try
                {
                    connection.Open();
                    //各家公司风险列表、各家公司风险图
                    string sqlRisk = "select * from vhome_library_risklist_data";
                    SqlCommand comRisk = new SqlCommand(sqlRisk, connection);
                    SqlDataAdapter riskData = new SqlDataAdapter(comRisk);
                    riskData.Fill(tableRiskList);
                    if (tableRiskList != null && tableRiskList.Rows.Count > 0)
                    {
                        foreach (DataRow item in tableRiskList.Rows)
                        {
                            RiskTempList risk = new RiskTempList();
                            risk.companyName = item["companyName"] != null ? item["companyName"].ToString() : null;
                            risk.cnt = int.Parse(item["cnt"].ToString()) != 0 ? int.Parse(item["cnt"].ToString()) : 0;
                            risk.riskType = item["riskType"] != null ? item["riskType"].ToString() : null;
                            riskTempList.Add(risk);
                        }
                    }
                    //各家公司风险类别图
                    string sqlRiskType = "select RISK_NAME as typeName,count(1) as qty from vhome_library_data GROUP BY RISK_NAME ORDER BY qty desc";
                    SqlCommand comRiskType = new SqlCommand(sqlRiskType, connection);
                    SqlDataAdapter riskTypeData = new SqlDataAdapter(comRiskType);
                    riskTypeData.Fill(tableRiskType);
                    if (tableRiskType != null && tableRiskType.Rows.Count > 0)
                    {
                        foreach (DataRow item in tableRiskType.Rows)
                        {
                            RiskTypeList risk = new RiskTypeList();
                            risk.typeName = item["typeName"] != null ? item["typeName"].ToString() : null;
                            risk.qty = int.Parse(item["qty"].ToString()) != 0 ? int.Parse(item["qty"].ToString()) : 0;
                            riskTypeList.Add(risk);
                        }
                    }
                    connection.Close();
                }
                catch (Exception ex)
                {
                    if (!string.IsNullOrEmpty(ex.StackTrace))
                        throw new Exception("错误日志：[StackTrace]" + ex.StackTrace);
                    else
                        throw new Exception("【" + HttpContext.Request.Path + "】错误日志：[Message]" + ex.Message);
                }
            }
            //行转列
            var groupList = riskTempList
    .GroupBy(x => x.companyName)
    .Select(g =>
    {
        // 先把当前公司的风险类型和数量转成字典，避免多次遍历分组
        var riskDict = g.ToDictionary(x => x.riskType, x => x.cnt);

        return new RiskList
        {
            companyName = g.Key,
            majorCount = riskDict.TryGetValue(SKEvaluateLevelEnum.重大风险.GetDescription(), out var major) ? major : 0,
            largerCount = riskDict.TryGetValue(SKEvaluateLevelEnum.较大风险.GetDescription(), out var larger) ? larger : 0,
            generalCount = riskDict.TryGetValue(SKEvaluateLevelEnum.一般风险.GetDescription(), out var general) ? general : 0,
            lowCount = riskDict.TryGetValue(SKEvaluateLevelEnum.低风险.GetDescription(), out var low) ? low : 0,
            totalCount = riskDict.Sum(x => x.Value)
        };
    })
    .ToList();
            if (orgList != null && orgList.Any())
            {
                foreach (var item in orgList)
                {
                    var first = groupList.FirstOrDefault(t => t.companyName == item.NAME);
                    RiskList risk = new RiskList();
                    risk.companyName = item.NAME;
                    if (first != null)
                    {
                        risk.majorCount = first.majorCount;
                        risk.largerCount = first.largerCount;
                        risk.generalCount = first.generalCount;
                        risk.lowCount = first.lowCount;
                        risk.totalCount = first.totalCount;
                    }
                    else
                    {
                        risk.majorCount = 0;
                        risk.largerCount = 0;
                        risk.generalCount = 0;
                        risk.lowCount = 0;
                        risk.totalCount = 0;
                    }
                    riskList.Add(risk);
                }
            }
            result.Data.riskList = riskList;
            result.Data.riskTypeList = riskTypeList;
            return result;

        }
        /// <summary>
        /// 获取子页 危险作业清单
        /// </summary>
        /// <param name="filter"></param>
        [HttpPost, Route("JobManage")]
        public JsonActionResult<List<JobManage>> JobManage([FromBody] KeywordFilter filter)
        {
            JsonActionResult<List<JobManage>> result = new JsonActionResult<List<JobManage>>();
            var list = new List<JobManage>();
            DataTable tableList = new DataTable();
            string strConn = OPTenantDBConnService.GetConnByORGID(filter.OrgId.Value);//获取数据库链接
            using (SqlConnection connection = new SqlConnection(strConn))
            {
                try
                {
                    connection.Open();
                    //当日危险作业清单
                    string sql = "select * from vhome_jobTodayList";
                    SqlCommand com = new SqlCommand(sql, connection);
                    SqlDataAdapter data = new SqlDataAdapter(com);
                    data.Fill(tableList);
                    if (tableList != null && tableList.Rows.Count > 0)
                    {
                        foreach (DataRow item in tableList.Rows)
                        {
                            JobManage job = new JobManage();
                            job.companyName = item["companyName"] != null ? item["companyName"].ToString() : null;
                            job.startDate = item["JOB_DATE"] != null ? item["JOB_DATE"].ToString() : null;
                            job.endDate = item["JOB_END_DATE"] != null ? item["JOB_END_DATE"].ToString() : null;
                            job.jobName = item["stepName"] != null ? item["stepName"].ToString() : null;
                            job.areaName = item["areaName"] != null ? item["areaName"].ToString() : null;
                            job.place = item["JOB_LOCATION"] != null ? item["JOB_LOCATION"].ToString() : null;
                            job.users = item["userNames"] != null ? item["userNames"].ToString() : null;
                            job.monitor = item["monitorName"] != null ? item["monitorName"].ToString() : null;
                            job.approveUsers = item["approveNames"] != null ? item["approveNames"].ToString() : null;
                            list.Add(job);
                        }
                    }
                    connection.Close();
                }
                catch (Exception ex)
                {
                    if (!string.IsNullOrEmpty(ex.StackTrace))
                        throw new Exception("错误日志：[StackTrace]" + ex.StackTrace);
                    else
                        throw new Exception("【" + HttpContext.Request.Path + "】错误日志：[Message]" + ex.Message);
                }
            }
            result.Data = list;
            return result;

        }
    }

    /// <summary>
    /// 隐患治理 返参
    /// </summary>
    public class HiddenManage
    {
        /// <summary>
        /// 隐患数量统计
        /// </summary>
        public List<dynamic> hiddenList { get; set; }
        /// <summary>
        /// 月度隐患处理统计
        /// </summary>
        public List<dynamic> hiddenRectifyList { get; set; }
        /// <summary>
        /// 隐患排序
        /// </summary>
        public List<dynamic> hiddenRanking { get; set; }
    }
    /// <summary>
    /// 风险管控 返参
    /// </summary>
    public class RiskManage
    {
        /// <summary>
        /// 各家公司风险列表、各家公司风险图
        /// </summary>
        public List<RiskList> riskList { get; set; }
        /// <summary>
        /// 各家公司风险类别图
        /// </summary>
        public List<RiskTypeList> riskTypeList { get; set; }
    }
    public class RiskTempList
    {
        /// <summary>
        /// 公司名称
        /// </summary>
        public string companyName { get; set; }
        /// <summary>
        /// 风险类别
        /// </summary>
        public string riskType { get; set; }
        /// <summary>
        /// 数量
        /// </summary>
        public int? cnt { get; set; }
    }
    public class RiskList
    {
        /// <summary>
        /// 公司名称
        /// </summary>
        public string companyName { get; set; }
        /// <summary>
        /// 重大风险数量
        /// </summary>
        public int? majorCount { get; set; }
        /// <summary>
        /// 较大风险数量
        /// </summary>
        public int? largerCount { get; set; }
        /// <summary>
        /// 一般风险数量
        /// </summary>
        public int? generalCount { get; set; }
        /// <summary>
        /// 低风险数量
        /// </summary>
        public int? lowCount { get; set; }
        /// <summary>
        /// 小计数量
        /// </summary>
        public int? totalCount { get; set; }
    }
    public class RiskTypeList
    {
        /// <summary>
        /// 风险类别
        /// </summary>
        public string typeName { get; set; }
        /// <summary>
        /// 数量
        /// </summary>
        public int? qty { get; set; }
    }
    public class JobManage
    {
        /// <summary>
        /// 公司名称
        /// </summary>
        public string companyName { get; set; }
        /// <summary>
        /// 开始时间
        /// </summary>
        public string startDate { get; set; }
        /// <summary>
        /// 结束时间
        /// </summary>
        public string endDate { get; set; }
        /// <summary>
        /// 作业名称
        /// </summary>
        public string jobName { get; set; }
        /// <summary>
        /// 作业区域
        /// </summary>
        public string areaName { get; set; }
        /// <summary>
        /// 作业地点
        /// </summary>
        public string place { get; set; }
        /// <summary>
        /// 作业人员
        /// </summary>
        public string users { get; set; }
        /// <summary>
        /// 监护人
        /// </summary>
        public string monitor { get; set; }
        /// <summary>
        /// 审批领导
        /// </summary>
        public string approveUsers { get; set; }
    }
}
