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.Enums;
using APT.Utility;
using InfluxData.Net.InfluxDb.Enums;
using log4net.Core;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
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 HiddenRectify hiddenRectify { 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 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 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 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 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 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;
        }

    }
}
