using AngleSharp.Css.Values;
using AngleSharp.Dom;
using Masuit.Tools;
using Masuit.Tools.DateTimeExt;
using Masuit.Tools.Models;
using Microsoft.EntityFrameworkCore;
using NLog.LayoutRenderers.Wrappers;
using PVDEMCS.Common;
using PVDEMCS.Common.Constant;
using PVDEMCS.Common.DI;
using PVDEMCS.Common.EF;
using PVDEMCS.Common.Tools;
using PVDEMCS.Services.Models;
using PVDEMCS.Services.Repositories.Entities;
using SixLabors.ImageSharp.Processing.Processors.Transforms;
using System;
using System.Text.RegularExpressions;

namespace PVDEMCS.Services.Repositories.Impl
{

    /*
     * 设备数据记录与统计 数据层 实现
     */
    internal class EquipmentRecordRepository : IEquipmentRecordRepository
    {
        private ISysConfigRepository _configRepository;
        public EquipmentRecordRepository(ISysConfigRepository configRepository)
        {
            _configRepository = configRepository;
        }

        #region 设备状态记录

        /// <summary>
        /// 获取设备状态记录分页列表
        /// </summary>
        /// <param name="equipmentId">设备Id</param>
        /// <param name="equipmentName">设备名称</param>
        /// <param name="equipmentCode">设备编号</param>
        /// <param name="equipmentType">设备类型</param>
        /// <param name="begTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <param name="page">当前页</param>
        /// <param name="size">页大小</param>
        /// <returns></returns>
        public Result<PagedList<EquipmentRecord>> GetEquipmentRecordPageList(string equipmentId, string equipmentName, string equipmentCode, string equipmentType, DateTime? begTime, DateTime? endTime, int page, int size)
        {
            using (var context = new EFContext())
            {
                var query = QueryEquipmentRecord(equipmentId, equipmentName, equipmentCode, equipmentType, begTime, endTime, context);

                var pageList = query.OrderByDescending(f => f.StartTime).ToPagedList(page, size);

                return new Result<PagedList<EquipmentRecord>>(pageList);
            }
        }

        /// <summary>
        /// 获取设备状态记录列表
        /// </summary>
        /// <param name="equipmentId">设备Id</param>
        /// <param name="equipmentName">设备名称</param>
        /// <param name="equipmentCode">设备编号</param>
        /// <param name="equipmentType">设备类型</param>
        /// <param name="begTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <returns></returns>
        public Result<List<EquipmentRecord>> GetEquipmentRecordList(string equipmentId, string equipmentName, string equipmentCode, string equipmentType, DateTime? begTime, DateTime? endTime)
        {
            using (var context = new EFContext())
            {
                var query = QueryEquipmentRecord(equipmentId, equipmentName, equipmentCode, equipmentType, begTime, endTime, context);

                var list = query.OrderByDescending(f => f.StartTime).ToList();

                return new Result<List<EquipmentRecord>>(list);
            }
        }

        private IQueryable<EquipmentRecord> QueryEquipmentRecord(string equipmentId, string equipmentName, string equipmentCode, string equipmentType, DateTime? begTime, DateTime? endTime, EFContext context)
        {
            var query = from record in context.EquipmentRecords
                        join equipment in context.EquipmentInfos.Where(f => !f.IsDelete) on record.EquipmentId equals equipment.Id
                        select new EquipmentRecord
                        {
                            Id = record.Id,
                            EquipmentId = equipment.Id,
                            EquipmentName = equipment.EquipmentName,
                            EquipmentCode = equipment.EquipmentCode,
                            EquipmentType = equipment.EquipmentType,
                            StartTime = record.StartTime,
                            EndTime = record.EndTime,
                            State = record.State,
                        };
            if (!equipmentId.IsNullOrEmpty())
            {
                query = query.Where(f => f.EquipmentId == equipmentId);
            }
            if (!equipmentName.IsNullOrEmpty())
            {
                query = query.Where(f => f.EquipmentName.StartsWith(equipmentName));
            }
            if (!equipmentCode.IsNullOrEmpty())
            {
                query = query.Where(f => f.EquipmentCode.StartsWith(equipmentCode));
            }
            if (!equipmentType.IsNullOrEmpty())
            {
                query = query.Where(f => f.EquipmentType == equipmentType);
            }
            if (begTime.HasValue)
            {
                query = query.Where(f => f.StartTime >= begTime);
            }
            if (endTime.HasValue)
            {
                query = query.Where(f => f.StartTime <= endTime);
            }
            return query;
        }

        /// <summary>
        /// 批量添加或更新设备状态记录
        /// 1.如果设备最新记录状态没有改变则更新结束时间
        /// 2.如果没有记录则添加记录
        /// </summary>
        /// <param name="equipmentId">设备Id</param>
        /// <param name="state">设备状态，运行:Run，待机:Stop，报警:Alarm</param>
        /// <param name="dateTime">记录时间</param>
        /// <returns></returns>
        public Result AddUpdateEquipmentRecord(string equipmentId, string state, DateTime dateTime)
        {
            using (var context = new EFContext())
            {
                //降低查询数据量
                var endDateTime = dateTime.AddDays(-3);
                var entity = context.EquipmentRecords.Where(f => f.EquipmentId == equipmentId && f.StartTime <= endDateTime).OrderByDescending(f => f.StartTime).FirstOrDefault();
                //如果3天内没有找到
                if (entity == null)
                {
                    entity = context.EquipmentRecords.Where(f => f.EquipmentId == equipmentId).OrderByDescending(f => f.StartTime).FirstOrDefault();
                }
                //如果最新记录状态没有改变
                if (entity != null && entity.State == state)
                {
                    entity.EndTime = dateTime;
                    entity.Update();
                }
                else
                {
                    //更新最新记录结束时间
                    if (entity != null)
                    {
                        entity.EndTime = dateTime;
                        entity.Update();
                    }
                    //添加设备状态新记录
                    var record = new EquipmentRecordEntity
                    {
                        EquipmentId = equipmentId,
                        State = state,
                        StartTime = dateTime,
                        EndTime = dateTime,
                    };
                    record.Create();
                    context.EquipmentRecords.Add(record);
                }
                context.SaveChanges();

                return new Result();
            }
        }

        /// <summary>
        /// 添加或更新设备状态记录
        /// 1.如果设备最新记录状态没有改变则更新结束时间
        /// 2.如果没有记录则添加记录
        /// </summary>
        /// <returns></returns>
        public Result AddUpdateEquipmentRecordBatch(List<EquipmentRecordUpdateModel> items)
        {
            using (var context = new EFContext())
            {
                foreach (var item in items)
                {
                    //降低查询数据量
                    var endDateTime = item.DateTime.AddDays(-3);
                    var entity = context.EquipmentRecords.Where(f => f.EquipmentId == item.EquipmentId && f.StartTime >= endDateTime).OrderByDescending(f => f.StartTime).FirstOrDefault();
                    //如果3天内没有找到
                    if (entity == null)
                    {
                        entity = context.EquipmentRecords.Where(f => f.EquipmentId == item.EquipmentId).OrderByDescending(f => f.StartTime).FirstOrDefault();
                    }
                    //如果最新记录状态没有改变
                    if (entity != null && entity.State == item.State)
                    {
                        entity.EndTime = item.DateTime;
                        entity.Update();
                    }
                    else
                    {
                        //更新最新记录结束时间
                        if (entity != null)
                        {
                            entity.EndTime = item.DateTime;
                            entity.Update();
                        }
                        //添加设备状态新记录
                        var record = new EquipmentRecordEntity
                        {
                            EquipmentId = item.EquipmentId,
                            State = item.State,
                            StartTime = item.DateTime,
                            EndTime = item.DateTime,
                        };
                        record.Create();
                        context.EquipmentRecords.Add(record);
                    }
                }
                context.SaveChanges();
            }

            return new Result();
        }

        /// <summary>
        /// 进行设备状态记录统计（日统计）
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public Result RunEquipmentRecordDayTotal(DateTime date)
        {
            var begDate = DateTime.Parse(date.ToString("yyyy-MM-dd"));
            var endDate = begDate.AddDays(1).AddSeconds(-1);

            var result = new Result();
            using (var context = new EFContext())
            {
                var query = context.EquipmentRecords.Where(f => (f.StartTime >= begDate && f.StartTime <= endDate)).ToList();
                //过滤跨天的数据部分

                //获取状态统计时间
                var total = query.GroupBy(f => new { f.EquipmentId, f.State })
                     .Select(f => new TotalRecord
                     {
                         EquipmentId = f.Key.EquipmentId,
                         State = f.Key.State,
                         Value = Convert.ToDecimal(f.Sum(ff => (ff.EndTime - ff.StartTime).TotalMinutes)),
                         Date = DateTime.Parse(f.Min(ff => ff.StartTime).ToString("yyyy-MM-dd")),

                     }).ToList();

                if (total.Count == 0)
                {
                    result.Message = "没有汇总统计数据";
                    return result;
                }
                var furnaceQuy = (from q in query
                                  join e in context.EquipmentInfos.Where(f => !f.IsDelete) on q.EquipmentId equals e.Id
                                  where q.State == EquipmentState.Run
                                  select new
                                  {
                                      q.EquipmentId,
                                      e.EquipmentType,
                                      q.StartTime,
                                      q.EndTime
                                  }).ToList();


                //获取配置的设备的阈值
                var homegrownConfig = _configRepository.GetSysConfigDetailNameOrKey("", EquipmentType.Homegrown).Content;
                var importConfig = _configRepository.GetSysConfigDetailNameOrKey("", EquipmentType.Import).Content;
                //var ionbondConfig = _configRepository.GetSysConfigDetailNameOrKey("", EquipmentType.Ionbond).Content;
                var homegrown = 200;
                var import = 300;
                //var ionbond = 200;
                if (homegrownConfig != null && !homegrownConfig.ConfigValue.IsNullOrEmpty())
                {
                    int.TryParse(homegrownConfig.ConfigValue, out homegrown);
                }
                if (importConfig != null && !importConfig.ConfigValue.IsNullOrEmpty())
                {
                    int.TryParse(importConfig.ConfigValue, out import);
                }
                //if (ionbondConfig != null && !ionbondConfig.ConfigValue.IsNullOrEmpty())
                //{
                //    int.TryParse(ionbondConfig.ConfigValue, out ionbond);
                //}


                var dayTotals = context.EquipmentRecordDayTotals.Where(f => f.TotalDay >= begDate && f.TotalDay <= endDate).ToList();
                foreach (var item in total.Select(f => new { f.EquipmentId, f.Date }).Distinct())
                {
                    var value = dayTotals.Where(f => f.EquipmentId == item.EquipmentId && f.TotalDay == item.Date).FirstOrDefault();
                    if (value.IsNullOrEmpty())
                    {
                        value = new EquipmentRecordDayTotalEntity
                        {
                            EquipmentId = item.EquipmentId,
                            TotalDay = item.Date,
                        };
                        value.Create();
                        context.EquipmentRecordDayTotals.Add(value);
                    }
                    else
                    {
                        value.Update();
                    }
                    //运行时间
                    var run = total.Where(f => f.EquipmentId == value.EquipmentId && f.Date == value.TotalDay && f.State == EquipmentState.Run).FirstOrDefault();
                    if (!run.IsNullOrEmpty())
                    {
                        value.TotalRunningTime = run.Value;
                    }
                    //待机时间
                    var stop = total.Where(f => f.EquipmentId == value.EquipmentId && f.Date == value.TotalDay && f.State == EquipmentState.Stop).FirstOrDefault();
                    if (!stop.IsNullOrEmpty())
                    {
                        value.TotalStopTime = stop.Value;
                    }
                    //报警时间
                    var alarm = total.Where(f => f.EquipmentId == value.EquipmentId && f.Date == value.TotalDay && f.State == EquipmentState.Alarm).FirstOrDefault();
                    if (!alarm.IsNullOrEmpty())
                    {
                        value.TotalAlarmTime = alarm.Value;
                    }
                    value.FurnaceNum = 0;
                    //出炉数量
                    var furnaceList = furnaceQuy.Where(f => f.EquipmentId == value.EquipmentId && value.TotalDay.Value.ToString("yyyy-MM-dd") == f.StartTime.ToString("yyyy-MM-dd")).ToList();
                    foreach (var furnace in furnaceList)
                    {
                        //计算开炉次数
                        var minutes = (furnace.EndTime - furnace.StartTime).TotalMinutes;
                        switch (furnace.EquipmentType)
                        {
                            case EquipmentType.Homegrown:
                                if (minutes >= homegrown)
                                {
                                    value.FurnaceNum++;
                                }
                                break;
                            case EquipmentType.Import:
                                if (minutes >= import)
                                {
                                    value.FurnaceNum++;
                                }
                                break;
                                //case EquipmentType.CemeCon:
                                //    if (minutes >= import)
                                //    {
                                //        value.FurnaceNum++;
                                //    }
                                //    break;
                        }
                    }
                }

                context.SaveChanges();

                return result;
            }
        }

        /// <summary>
        /// 进行设备状态记录统计
        /// </summary>
        /// <returns></returns>
        public Result RunEquipmentRecordTotal()
        {
            using (var context = new EFContext())
            {
                var query = context.EquipmentRecordDayTotals.AsQueryable();
                //获取最后更新时间
                var list = context.EquipmentRecordTotals.ToList();
                //var maxDate = list.Max(f => f.UpdateAt);
                ////如果有记录
                //if (maxDate.HasValue)
                //{
                //    query = query.Where(f => f.UpdateAt > maxDate);
                //}
                var values = query.GroupBy(f => f.EquipmentId).Select(f => new EquipmentRecordTotalEntity
                {
                    EquipmentId = f.Key,
                    FurnaceNum = f.Sum(f => f.FurnaceNum),
                    TotalRunningTime = f.Sum(f => f.TotalRunningTime),
                    TotalAlarmTime = f.Sum(f => f.TotalAlarmTime),
                    TotalStopTime = f.Sum(f => f.TotalStopTime),
                }).ToList();
                if (values.Count == 0)
                {
                    return new Result("没有汇总数据");
                }

                if (list.IsNullOrEmpty())
                {
                    foreach (var item in values)
                    {
                        item.Create();
                    }
                    context.EquipmentRecordTotals.AddRange(values);
                }
                else
                {
                    foreach (var item in list)
                    {
                        var value = values.Where(f => f.EquipmentId == item.EquipmentId).FirstOrDefault();
                        if (value.IsNullOrEmpty())
                        {
                            value.Create();
                            context.EquipmentRecordTotals.Add(value);
                        }
                        else
                        {
                            item.FurnaceNum = value.FurnaceNum;
                            item.TotalAlarmTime = value.TotalAlarmTime;
                            item.TotalRunningTime = value.TotalRunningTime;
                            item.TotalStopTime = value.TotalStopTime;
                            item.Update();
                        }
                    }
                }
                context.SaveChanges();

                return new Result();

            }
        }

        class TotalRecord
        {
            public string EquipmentId { get; set; }
            public string State { get; set; }
            public decimal Value { get; set; }
            public DateTime Date { get; set; }
        }

        #endregion

        #region 设备记录统计

        /// <summary>
        /// 获取设备状态记录日统计分页列表
        /// </summary>
        /// <param name="equipmentName">设备名称</param>
        /// <param name="equipmentCode">设备编号</param>
        /// <param name="equipmentType">设备类型</param>
        /// <param name="begTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <param name="page">当前页</param>
        /// <param name="size">页大小</param>
        public Result<PagedList<EquipmentRecordDayTotal>> GetEquipmentRecordDayTotalPageList(string equipmentName, string equipmentCode, string equipmentType, DateTime? begTime, DateTime? endTime, int page, int size)
        {
            using (var context = new EFContext())
            {
                var query = QueryEquipmentRecordDayTotal(equipmentName, equipmentCode, equipmentType, begTime, endTime, context);

                var pageList = query.OrderByDescending(f => f.EquipmentCode).ToPagedList(page, size);

                return new Result<PagedList<EquipmentRecordDayTotal>>(pageList);
            }
        }

        /// <summary>
        /// 获取设备状态记录日统计列表
        /// </summary>
        /// <param name="equipmentName">设备名称</param>
        /// <param name="equipmentCode">设备编号</param>
        /// <param name="equipmentType">设备类型</param>
        /// <param name="begTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        public Result<List<EquipmentRecordDayTotal>> GetEquipmentRecordDayTotalList(string equipmentName, string equipmentCode, string equipmentType, DateTime? begTime, DateTime? endTime)
        {
            using (var context = new EFContext())
            {
                var query = QueryEquipmentRecordDayTotal(equipmentName, equipmentCode, equipmentType, begTime, endTime, context);

                var pageList = query.OrderByDescending(f => f.EquipmentCode).ToList();

                return new Result<List<EquipmentRecordDayTotal>>(pageList);
            }
        }

        private IQueryable<EquipmentRecordDayTotal> QueryEquipmentRecordDayTotal(string equipmentName, string equipmentCode, string equipmentType, DateTime? begTime, DateTime? endTime, EFContext context)
        {
            var query = from recordTotal in context.EquipmentRecordDayTotals
                        join equipment in context.EquipmentInfos.Where(f => !f.IsDelete) on recordTotal.EquipmentId equals equipment.Id
                        select new EquipmentRecordDayTotal
                        {
                            Id = recordTotal.Id,
                            EquipmentName = equipment.EquipmentName,
                            EquipmentCode = equipment.EquipmentCode,
                            EquipmentType = equipment.EquipmentType,
                            FurnaceNum = recordTotal.FurnaceNum,
                            TotalAlarmTime = recordTotal.TotalAlarmTime,
                            TotalStopTime = recordTotal.TotalStopTime,
                            TotalRunningTime = recordTotal.TotalRunningTime,
                            TotalDay = recordTotal.TotalDay,
                        };

            if (!equipmentName.IsNullOrEmpty())
            {
                query = query.Where(f => f.EquipmentName.StartsWith(equipmentName));
            }
            if (!equipmentCode.IsNullOrEmpty())
            {
                query = query.Where(f => f.EquipmentCode.StartsWith(equipmentCode));
            }
            if (!equipmentType.IsNullOrEmpty())
            {
                query = query.Where(f => f.EquipmentType == equipmentType);
            }
            if (begTime.HasValue)
            {
                query = query.Where(f => f.TotalDay >= begTime);
            }
            if (endTime.HasValue)
            {
                query = query.Where(f => f.TotalDay <= endTime);
            }
            // query = query.Where(f => f.TotalDay >= begTime && f.TotalDay <= endTime);

            return query;
        }

        /// <summary>
        /// 获取设备状态记录统计分页列表
        /// </summary>
        /// <param name="equipmentName">设备名称</param>
        /// <param name="equipmentCode">设备编号</param>
        /// <param name="equipmentType">设备类型</param>
        /// <param name="begTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <param name="page">当前页</param>
        /// <param name="size">页大小</param>
        public Result<PagedList<EquipmentRecordTotal>> GetEquipmentRecordTotalPageList(string equipmentName, string equipmentCode, string equipmentType, DateTime? begTime, DateTime? endTime, int page, int size)
        {
            using (var context = new EFContext())
            {
                var sql = QueryEquipmentRecordTotal(equipmentName, equipmentCode, equipmentType, begTime, endTime, context);

                var list = EFSqlHelper.FromSqlQuery<EquipmentRecordTotal>(context, sql).ToList();

                return new Result<PagedList<EquipmentRecordTotal>>(list.ToPagedList(page, size));
            }
        }

        /// <summary>
        /// 获取设备状态记录统计列表
        /// </summary>
        /// <param name="equipmentName">设备名称</param>
        /// <param name="equipmentCode">设备编号</param>
        /// <param name="equipmentType">设备类型</param>
        /// <param name="begTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        public Result<List<EquipmentRecordTotal>> GetEquipmentRecordTotalList(string equipmentName, string equipmentCode, string equipmentType, DateTime? begTime, DateTime? endTime)
        {
            using (var context = new EFContext())
            {
                var sql = QueryEquipmentRecordTotal(equipmentName, equipmentCode, equipmentType, begTime, endTime, context);

                var list = EFSqlHelper.FromSqlQuery<EquipmentRecordTotal>(context, sql).ToList();

                return new Result<List<EquipmentRecordTotal>>(list);
            }
        }

        private string QueryEquipmentRecordTotal(string equipmentName, string equipmentCode, string equipmentType, DateTime? begTime, DateTime? endTime, EFContext context)
        {

            var sql = @$"SELECT
                        equipment_info.id as EquipmentId,
                        equipment_code as EquipmentCode,
                        equipment_name as EquipmentName,
                        SUM(furnace_num) AS FurnaceNum,
	                        SUM( total_running_time ) AS TotalRunningTime,
	                        SUM( total_alarm_time ) AS TotalAlarmTime,
	                        SUM( total_stop_time ) AS TotalStopTime
                        FROM
	                         equipment_record_day_total
                         JOIN equipment_info ON equipment_record_day_total.equipment_id = equipment_info.id 
                        WHERE 1=1 ";
            if (begTime.HasValue)
            {
                sql += $" AND total_day >= '{begTime.Value.ToString("yyyy-MM-dd")}'";
            }
            if (endTime.HasValue)
            {
                sql += $" AND total_day <= '{endTime.Value.AddDays(1).ToString("yyyy-MM-dd")}'";
            }
            if (!equipmentName.IsNullOrEmpty())
            {
                sql += $" AND equipment_info.equipment_name='{equipmentName}'";
            }
            if (!equipmentCode.IsNullOrEmpty())
            {
                sql += $" AND equipment_info.equipment_code='{equipmentCode}'";
            }
            if (!equipmentType.IsNullOrEmpty())
            {
                sql += $" AND equipment_info.equipment_type='{equipmentType}'";
            }
            sql += " GROUP BY equipment_info.id,equipment_info.equipment_code,equipment_info.equipment_name";
            return sql;


        }

        /// <summary>
        /// 根据设备Id获取记录统计
        /// </summary>
        /// <param name="equipmentId">设备Id</param>
        /// <returns></returns>
        public Result<EquipmentRecordTotalEntity> GetEquipmentRecordTotalDetail(string equipmentId)
        {
            using (var context = new EFContext())
            {
                var entity = context.EquipmentRecordTotals.Where(f => f.EquipmentId == equipmentId).FirstOrDefault();
                return new Result<EquipmentRecordTotalEntity>(entity);
            }
        }

        /// <summary>
        /// 获取设备状态记录月统计
        /// </summary>
        /// <returns></returns>
        public Result<List<EquipmentRecordStateMonthTotal>> GetEquipmentRecordStateMonthTotal()
        {
            //获取今年第一天和最后一天
            var endDate = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");
            var begDate = DateTime.Parse(endDate).AddMonths(-12).ToString("yyyy-MM-dd");

            using (var context = new EFContext())
            {
                var sql = @$"SELECT
                        SUM(total_running_time) AS TotalRunningTime,
                        SUM(total_alarm_time) AS TotalAlarmTime,
                        SUM(total_stop_time) AS TotalStopTime,
                        DATE_FORMAT(total_day,'%Y-%m') AS TotalMonth
                    FROM
                        equipment_record_day_total
                    WHERE
                        total_day >= '{begDate}'
                        AND total_day <= '{endDate}'
                    GROUP BY
                    TotalMonth";
                var list = EFSqlHelper.FromSqlQuery<EquipmentRecordStateMonthTotal>(context, sql).ToList();

                return new Result<List<EquipmentRecordStateMonthTotal>>(list);

            }

        }

        /// <summary>
        /// 获取设备记录开炉次数月统计
        /// </summary>
        /// <returns></returns>
        public Result<List<EquipmentRecordFurnaceMonthTotal>> GetEquipmentRecordFurnaceMonthTotal()
        {
            //获取今年第一天和最后一天
            var endDate = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");
            var begDate = DateTime.Parse(endDate).AddMonths(-12).ToString("yyyy-MM-dd");
            using (var context = new EFContext())
            {
                var sql = @$"SELECT
	                    SUM( furnace_num ) AS FurnaceNum,
	                    equipment_info.equipment_type AS EquipmentType,
	                    DATE_FORMAT ( total_day,'%Y-%m' ) AS TotalMonth 
                    FROM
	                    equipment_record_day_total
	                    JOIN equipment_info ON equipment_record_day_total.equipment_id = equipment_info.id 
                    WHERE
	                    total_day >= '{begDate}' 
	                    AND total_day <= '{endDate}' 
                    GROUP BY
	                    TotalMonth,
	                    EquipmentType";
                var list = EFSqlHelper.FromSqlQuery<EquipmentRecordFurnaceMonthTotal>(context, sql).ToList();

                return new Result<List<EquipmentRecordFurnaceMonthTotal>>(list);
            }
        }

        /// <summary>
        /// 获取设备记录OEE月统计
        /// </summary>
        /// <returns></returns>
        public Result<List<EquipmentOEEMonthTotal>> GetEquipmentRecordOEEMonthTotal()
        {
            //获取今年第一天和最后一天
            var endDate = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");
            var begDate = DateTime.Parse(endDate).AddMonths(-12).ToString("yyyy-MM-dd");
            using (var context = new EFContext())
            {
                var sql = $@"SELECT
	                        info.id AS EquipmentId,
	                        info.equipment_type AS EquipmentType,
	                        SUM( total_running_time ) AS TotalRunningTime,
	                        DATE_FORMAT ( total_day,'%Y-%m' ) AS TotalMonth
	
                        FROM
	                        equipment_record_day_total a
	                        JOIN equipment_info info ON a.equipment_id = info.id 
                        WHERE
	                        total_day >= '{begDate}' 
	                        AND total_day <= '{endDate}' 
                        GROUP BY
	                        TotalMonth,
	                        EquipmentId,
	                        EquipmentType";

                var list = EFSqlHelper.FromSqlQuery<EquipmentRecordStateOEEMonthTotal>(context, sql).ToArray();

                //计算OEE
                //获取配置的设备的初尝值
                var homegrownConfig = _configRepository.GetSysConfigDetailNameOrKey("", EquipmentTypeOffset.HomegrownOffset).Content;
                var importConfig = _configRepository.GetSysConfigDetailNameOrKey("", EquipmentTypeOffset.ImportOffset).Content;
                //var ionbondConfig = _configRepository.GetSysConfigDetailNameOrKey("", EquipmentTypeOffset.IonbondOffset).Content;
                var homegrown = 0m;
                var import = 0m;
                //var ionbond = 0m;
                if (homegrownConfig != null && !homegrownConfig.ConfigValue.IsNullOrEmpty())
                {
                    decimal.TryParse(homegrownConfig.ConfigValue, out homegrown);
                }
                if (importConfig != null && !importConfig.ConfigValue.IsNullOrEmpty())
                {
                    decimal.TryParse(importConfig.ConfigValue, out import);
                }
                //if (ionbondConfig != null && !ionbondConfig.ConfigValue.IsNullOrEmpty())
                //{
                //    decimal.TryParse(ionbondConfig.ConfigValue, out ionbond);
                //}

                foreach (var item in list)
                {
                    var days = 0;
                    var minutes = 0;
                    var now = DateTime.Now;
                    //如果在本月
                    if (item.TotalMonth == DateTime.Now.ToString("yyyy-MM"))
                    {
                        //初尝值不包括今天
                        days = now.Day - 1;
                        //获取当月到当前的分钟
                        minutes = days * 60 * 24 + (now.Hour - 1) * 60 + now.Minute;
                    }
                    else
                    {
                        var sptr = item.TotalMonth.Split('-');
                        if (sptr.Length == 2)
                        {
                            days = DateTime.DaysInMonth(int.Parse(sptr[0]), int.Parse(sptr[1]));
                            minutes = days * 60 * 24;
                        }

                    }
                    var value = 0m;
                    switch (item.EquipmentType)
                    {
                        case EquipmentType.Homegrown:
                            value = days * homegrown;
                            break;
                        case EquipmentType.Import:
                            value = days * import;
                            break;
                        //case EquipmentType.CemeCon:
                        //    value = days * cemecon;
                        //    break;
                        default:
                            break;
                    }
                    if (minutes > 0)
                    {
                        item.OEE = (item.TotalRunningTime + value) / minutes;
                    }
                }

                var result = list.GroupBy(f => f.TotalMonth).Select(f => new EquipmentOEEMonthTotal
                {
                    TotalMonth = f.Key,
                    OEE = Math.Round(f.Sum(f => f.OEE) / f.Count(), 4) * 100
                }).ToList();

                return new Result<List<EquipmentOEEMonthTotal>>(result);

            }
        }

        /// <summary>
        /// 获取设备OEE信息
        /// </summary>
        /// <param name="equipmentId">设备Id</param>
        /// <param name="begDate">开始时间</param>
        /// <param name="endDate">结束时间</param>
        /// <returns></returns>
        public Result<EquipmentOEETotal> GetEquipmentOEEMonthTotal(string equipmentId, DateTime begDate, DateTime endDate)
        {
            //获取今年第一天和最后一天
            var beg = begDate.ToString("yyyy-MM-dd");
            var end = endDate.AddDays(1).ToString("yyyy-MM-dd");
            EquipmentOEETotal ret = null;

            using (var context = new EFContext())
            {
                var sql = $@"SELECT
	                        info.id AS EquipmentId,
	                        info.equipment_type AS EquipmentType,
	                        SUM( total_running_time ) AS TotalRunningTime,
	                        SUM( total_alarm_time ) AS TotalAlarmTime,
	                        SUM( total_stop_time ) AS TotalStopTime 
                        FROM
	                        equipment_record_day_total a
	                        JOIN equipment_info info ON a.equipment_id = info.id 
                        WHERE
	                        info.id = '{equipmentId}' 
	                        AND total_day >= '{beg}' 
	                        AND total_day <= '{end}' 
                        GROUP BY
	                        EquipmentId,
	                        EquipmentType";

                var list = EFSqlHelper.FromSqlQuery<EquipmentRecordStateOEEMonthTotal>(context, sql).ToArray();

                if (list.Length > 0)
                {
                    var detail = list[0];

                    //获取配置的设备的初尝值
                    var homegrownConfig = _configRepository.GetSysConfigDetailNameOrKey("", EquipmentTypeOffset.HomegrownOffset).Content;
                    var importConfig = _configRepository.GetSysConfigDetailNameOrKey("", EquipmentTypeOffset.ImportOffset).Content;
                    //var ionbondConfig = _configRepository.GetSysConfigDetailNameOrKey("", EquipmentTypeOffset.IonbondOffset).Content;
                    var homegrown = 0m;
                    var import = 0m;
                    //var ionbond = 0m;
                    if (homegrownConfig != null && !homegrownConfig.ConfigValue.IsNullOrEmpty())
                    {
                        decimal.TryParse(homegrownConfig.ConfigValue, out homegrown);
                    }
                    if (importConfig != null && !importConfig.ConfigValue.IsNullOrEmpty())
                    {
                        decimal.TryParse(importConfig.ConfigValue, out import);
                    }
                    //if (ionbondConfig != null && !ionbondConfig.ConfigValue.IsNullOrEmpty())
                    //{
                    //    decimal.TryParse(ionbondConfig.ConfigValue, out ionbond);
                    //}

                    var now = DateTime.Now;
                    var minutes = 0m;
                    var days = 0m;
                    if (endDate >= now)
                    {
                        days = Convert.ToDecimal((now - begDate).TotalDays);
                    }
                    else
                    {
                        days = Convert.ToDecimal((endDate - begDate).TotalDays);
                    }
                    if (endDate.ToString("yyyy-MM-dd") == DateTime.Now.ToString("yyyy-MM-dd"))
                    {
                        minutes = days * 60 * 24 + (now.Hour - 1) * 60 + now.Minute;
                    }
                    else
                    {
                        minutes = days * 60 * 24;
                    }

                    var value = 0m;
                    switch (detail.EquipmentType)
                    {
                        case EquipmentType.Homegrown:
                            value = days * homegrown;
                            break;
                        case EquipmentType.Import:
                            value = days * import;
                            break;
                        //case EquipmentType.CemeCon:
                        //    value = days * import;
                        //    break;
                        default:
                            break;
                    }
                    if (minutes > 0)
                    {
                        detail.OEE = Math.Round((detail.TotalRunningTime + value) / minutes, 4) * 100;
                    }

                    ret = ModelTools.PubClone<EquipmentRecordStateOEEMonthTotal, EquipmentOEETotal>.Trans(detail);
                }

                return new Result<EquipmentOEETotal>(ret);
            }
        }

        #endregion
    }
}
