using Microsoft.AspNetCore.Mvc;
using OfficeOpenXml;
using ServiceCenter;
using ServiceCenter.Extensions;
using ServiceCenter.SqlSugars;
using SqlSugar;
using System.Net.NetworkInformation;
using System.Text;
using WCS.Core;
using WCS.Entity.Protocol.HUB;
using WCS.Entity.Protocol.SRM;
using WCS.WorkEngineering.WebApi.Models.WCS.Request;
using WCS.WorkEngineering.WebApi.Models.WCS.Response;

//using Microsoft.OpenApi.Writers;

// ReSharper disable PossibleLossOfFraction

namespace WCS.WorkEngineering.WebApi.Controllers
{
    /// <summary>
    ///  设备Ip通讯检测结构
    /// </summary>
    public class DeviceIpTestResults
    {
        public string Ip { get; set; }

        public bool Result { get; set; }
    }

    /// <summary>
    /// WCS相关接口控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class WcsController : ControllerBase
    {
        /// <summary>
        ///  获取设备配置信息接口
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public List<Device> GetDeviceList()
        {
            return Device.All.ToList();
        }

        /// <summary>
        ///  获取设备运行状态
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public PagedInfoResponse<RunInfoViewMode> GetDevRunInfo(DevRunInfoViewMode req)
        {
            var runInfos = new List<RunInfoViewMode>();
            var db = new SqlSugarHelper().Default;
            var plcEx = new SqlSugarHelper().PLCEX;
            var type = "";
            List<List<DateTime>> dateList = new List<List<DateTime>>();
            switch (req.Scope)
            {
                case ScopeType.Day:
                    dateList = GetDayRanges(req.StateTime, req.EndTime);
                    break;

                case ScopeType.Hour:
                    dateList = GetHourRanges(req.StateTime, req.EndTime);
                    break;

                default:
                    throw new Exception("不支持此时间范围统计，目前仅支持天与小时");
            }

            switch (req.Type)
            {
                case DevType.SRM: //堆垛机

                    foreach (var date in dateList)
                    {
                        var minTime = date.MinBy(x => x);
                        var maxTime = date.MaxBy(x => x);
                        type = DevType.SRM.ToString();
                        //获取时段内设备的运行状态
                        var runInfoList = plcEx.Queryable<DevRunInfo>().Where(x => x.Type == type && x.Frame >= minTime && x.Frame < maxTime).ToList().GroupBy(x => x.Code);
                        foreach (var runInfo in runInfoList)
                        {
                            var info = new RunInfoViewMode()
                            {
                                Code = runInfo.Key,
                                Free = runInfo.Where(x =>
                                    x.RunMode == SrmMode.自动.GetDescription() &&
                                    x.RunStatus == SrmRunStatus.空闲.GetDescription()).Sum(x => x.Duration) / 1000 / 60,
                                Alarm = runInfo.Where(x => x.RunMode == SrmMode.维修.GetDescription())
                                    .Sum(x => x.Duration) / 1000 / 60,
                                Manual = runInfo.Where(x => x.RunMode == SrmMode.手动.GetDescription() || x.RunMode == SrmMode.半自动.GetDescription())
                                    .Sum(x => x.Duration) / 1000 / 60,
                                Automatic = runInfo.Where(x => x.RunMode == SrmMode.自动.GetDescription()).Sum(x => x.Duration) / 1000 / 60,
                                Working = runInfo.Where(x => x.RunMode == SrmMode.自动.GetDescription()
                                                             && x.RunStatus != SrmRunStatus.空闲.GetDescription()
                                                             && x.RunStatus != SrmRunStatus.保持维修.GetDescription()).Sum(x => x.Duration) / 1000 / 60,
                                TotalTime = runInfo.Sum(x => x.Duration) / 1000 / 60
                            };

                            #region 开始分析设备动作,不计算停止时间

                            var devActions = new List<DevActionViewMode>();
                            double totalTime = 0; //总耗时
                            double totalCount = 0; //总次数
                            //入库
                            var infos = runInfo.Where(x => x.RunMode == SrmMode.自动.GetDescription()).OrderBy(x => x.Frame).ToList();
                            totalTime = infos.Where(x => x.RunStatus != SrmRunStatus.空闲.GetDescription() && x.RunStatus != SrmRunStatus.保持维修.GetDescription()).Sum(x => x.Duration);

                            #endregion 开始分析设备动作,不计算停止时间

                            #region 计算任务的工位使用数量

                            var stationCounts = new List<StationCount>();
                            type = DevType.SrmTaskSum.ToString();
                            var taskSum = plcEx.Queryable<DevRunInfo>().Where(x => x.Code == runInfo.Key && x.Type == type && x.Frame >= minTime && x.Frame < maxTime)
                                .ToList().Select(x =>
                                {
                                    var item = x;
                                    var taskInfo = item.RunStatus.Split("--");
                                    if (taskInfo.Length < 3) return null;
                                    item.Duration = long.Parse(taskInfo[2]);
                                    return item;
                                }).Where(x => x != null).ToList();

                            //入库
                            stationCounts.Add(new StationCount()
                            {
                                Type = DevActionType.In.GetDescription(),
                                StationNum = taskSum.Count(x => x is { RunMode: "1" }),
                                StationIndex = 1
                            });
                            stationCounts.Add(new StationCount()
                            {
                                Type = DevActionType.In.GetDescription(),
                                StationNum = taskSum.Count(x => x is { RunMode: "2" }),
                                StationIndex = 2
                            });
                            info.StationCount = stationCounts;
                            totalCount = taskSum.Count;
                            devActions.Add(new DevActionViewMode()
                            {
                                Type = DevActionType.In.GetDescription(),
                                ActionAmount = totalCount,
                                ActionTime = totalTime == 0 ? 0 : Math.Round((totalTime / totalCount) / 1000, 2),
                            });
                            info.DevAction = devActions;

                            #endregion 计算任务的工位使用数量

                            info.StartTime = minTime;
                            info.EndTime = maxTime;
                            runInfos.Add(info);
                        }
                    }

                    break;

                case DevType.Truss:
                    //type = DevType.Truss.ToString();
                    //foreach (var date in dateList)
                    //{
                    //    HandleTrussRunInfo(type, db, plcEx, runInfos, date.MinBy(x => x), date.MaxBy(x => x));
                    //}
                    break;
            }

            var res = new PagedInfoResponse<RunInfoViewMode>();
            res.Result = runInfos.OrderBy(x => x.StartTime).ThenBy(x => x.Code).ToList();
            res.TotalNum = runInfos.Count;

            // If you are a commercial business and have
            // purchased commercial licenses use the static property
            // LicenseContext of the ExcelPackage class:
            ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.Commercial;

            // If you use EPPlus in a noncommercial context
            // according to the Polyform Noncommercial license:
            ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
            // 创建一个新的 Excel 文件
            FileInfo excelFile = new FileInfo("D:\\output.xlsx");
            using (ExcelPackage package = new ExcelPackage(excelFile))
            {
                ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1");

                // 写入表头
                int col = 1;
                var title = new List<string>() { "时间", "设备", "入库", "空闲", "手动", "自动", "报警", "工作时间", "总时间", "次数", "耗时", "稼动率", "单抓", "双爪" };
                foreach (var prop in title)
                {
                    worksheet.Cells[1, col].Value = prop;
                    col++;
                }

                // 写入数据
                int row = 2;
                var dateTimeList = res.Result.GroupBy(x => x.StartTime);
                foreach (var time in dateTimeList)
                {
                    var codeLost = time.OrderBy(x => x.Code);

                    foreach (var code in codeLost)
                    {
                        worksheet.Cells[row, 1].Value = code.StartTime;
                        worksheet.Cells[row, 2].Value = code.Code;
                        worksheet.Cells[row, 3].Value = code.StationCount?.Select(x => x.StationIndex * x.StationNum).Sum(x => x);
                        worksheet.Cells[row, 4].Value = code.Free;
                        worksheet.Cells[row, 5].Value = code.Manual;
                        worksheet.Cells[row, 6].Value = code.Automatic;
                        worksheet.Cells[row, 7].Value = code.Alarm;
                        worksheet.Cells[row, 8].Value = code.Working;
                        worksheet.Cells[row, 9].Value = code.TotalTime;
                        worksheet.Cells[row, 10].Value = code.DevAction.FirstOrDefault(x => x.Type == "入库")?.ActionAmount;
                        worksheet.Cells[row, 11].Value = code.DevAction.FirstOrDefault(x => x.Type == "入库")?.ActionTime;
                        worksheet.Cells[row, 12].Value = code.Working / code.TotalTime;
                        worksheet.Cells[row, 13].Value = code.StationCount.First(x => x is { Type: "入库", StationIndex: 1 }).StationNum;
                        worksheet.Cells[row, 14].Value = code.StationCount.First(x => x is { Type: "入库", StationIndex: 2 }).StationNum;
                        //worksheet.Cells[row, 16].Value = enterDepot2;
                        //worksheet.Cells[row, 17].Value = outDepot1;
                        //worksheet.Cells[row, 18].Value = outDepot2;
                        row++;
                    }

                    //foreach (var prop in item.GetType().GetProperties())
                    //{
                    //    worksheet.Cells[row, col].Value = prop.GetValue(item);
                    //    col++;
                    //}
                }

                // 保存 Excel 文件
                package.Save();
            }

            return res;

            //var runInfos = new List<RunInfoViewMode>();
            //var db = new SqlSugarHelper().Default;
            //var plcEx = new SqlSugarHelper().PLCEX;
            //var type = "";
            //switch (req.Type)
            //{
            //    case DevType.SRM:
            //        type = DevType.SRM.ToString();
            //        //获取时段内设备的运行状态
            //        var runInfoList = plcEx.Queryable<DevRunInfo>().Where(x => x.Type == type && x.Frame >= req.StateTime && x.Frame < req.EndTime).ToList().GroupBy(x => x.Code);
            //        foreach (var runInfo in runInfoList)
            //        {
            //            var info = new RunInfoViewMode()
            //            {
            //                Code = runInfo.Key,
            //                //EnterDepot = db.Queryable<WCS_TaskOld>().With(SqlWith.NoLock)
            //                //    .Where(x => x.Status == TaskStatus.Finish && x.Type == TaskType.EnterDepot &&
            //                //                x.Device == runInfo.Key && x.EndTime >= req.StateTime &&
            //                //                x.EndTime < req.EndTime)
            //                //    .SplitTable(x => x.Take(2))
            //                //    .Count(),
            //                //OutDepot = db.Queryable<WCS_TaskOld>().With(SqlWith.NoLock)
            //                //    .Where(x => x.Status == TaskStatus.Finish && x.Type == TaskType.OutDepot &&
            //                //                x.Device == runInfo.Key && x.EndTime >= req.StateTime &&
            //                //                x.EndTime < req.EndTime)
            //                //    .SplitTable(x => x.Take(2))
            //                //    .Count(),
            //                //MoveDepot = db.Queryable<WCS_TaskOld>().With(SqlWith.NoLock)
            //                //    .Where(x => x.Status == TaskStatus.Finish && x.Type == TaskType.TransferDepot &&
            //                //                x.Device == runInfo.Key && x.EndTime >= req.StateTime &&
            //                //                x.EndTime < req.EndTime)
            //                //    .SplitTable(x => x.Take(2))
            //                //    .Count(),
            //                Free = runInfo.Where(x =>
            //                    x.RunMode == SrmMode.自动.GetDescription() &&
            //                    x.RunStatus == SrmRunStatus.空闲.GetDescription()).Sum(x => x.Duration) / 1000 / 60,
            //                //Alarm = runInfo.Where(x => x.RunMode == SrmMode.维修.GetDescription())
            //                //    .Sum(x => x.Duration) / 1000 / 60,
            //                Manual = runInfo.Where(x => x.RunMode == SrmMode.手动.GetDescription() || x.RunMode == SrmMode.半自动.GetDescription())
            //                    .Sum(x => x.Duration) / 1000 / 60,
            //                Automatic = runInfo.Where(x => x.RunMode == SrmMode.自动.GetDescription()
            //                                               && x.RunStatus != SrmRunStatus.空闲.GetDescription())
            //                    .Sum(x => x.Duration) / 1000 / 60,
            //            };

            //            #region 开始分析设备动作,不计算停止时间

            //            var devActions = new List<DevActionViewMode>();
            //            double totalTime = 0; //总耗时
            //            double totalCount = 0; //总次数
            //            //入库
            //            var infos = runInfo.Where(x => x.RunMode == SrmMode.自动.GetDescription() && x.RunStatus != SrmRunStatus.空闲.GetDescription()).OrderBy(x => x.Frame).ToList();
            //            totalTime = infos.Sum(x => x.Duration);
            //            totalCount = infos.Count(x => x.RunStatus == SrmRunStatus.放货收叉.GetDescription());
            //            devActions.Add(new DevActionViewMode()
            //            {
            //                //Type = DevActionType.In.GetDescription(),
            //                ActionAmount = totalCount,
            //                ActionTime = totalTime == 0 ? 0 : Math.Round(totalTime / totalCount, 2),
            //            });
            //            ////出库
            //            //infos = runInfo.Where(x => x.RunMode == RobotMode.Automatic.GetDescription()).ToList();
            //            //totalTime = infos.Where(x => x.RunStatus == RobotRunStatus.OutBoundCrawling.GetDescription() || x.RunStatus == RobotRunStatus.OutStorage.GetDescription()).Sum(x => x.Duration);
            //            //totalCount = infos.Count(x => x.RunStatus == RobotRunStatus.OutBoundCrawling.GetDescription());
            //            //devActions.Add(new DevActionViewMode()
            //            //{
            //            //    Type = DevActionType.Out.GetDescription(),
            //            //    ActionAmount = totalCount,
            //            //    ActionTime = totalTime == 0 ? 0 : Math.Round(totalTime / totalCount, 2),
            //            //});
            //            info.DevAction = devActions;

            //            #endregion 开始分析设备动作,不计算停止时间

            //            //#region 计算任务的工位使用数量

            //            //var stationCounts = new List<StationCount>();
            //            //type = DevType.RobotTaskSum.ToString();
            //            //var taskSum = plcEx.Queryable<DevRunInfo>().Where(x => x.Code == runInfo.Key && x.Type == type && x.Frame >= req.StateTime && x.Frame < req.EndTime)
            //            //    .ToList().Select(x =>
            //            //    {
            //            //        var item = x;
            //            //        item.Duration = long.Parse(item.RunStatus.Split("--")[2]);
            //            //        return item;
            //            //    }).ToList();

            //            ////入库
            //            //stationCounts.Add(new StationCount()
            //            //{
            //            //    Type = DevActionType.In.GetDescription(),
            //            //    StationNum = taskSum.Count(x => x is { Duration: 3, RunMode: "1" }),
            //            //    StationIndex = 1
            //            //});
            //            //stationCounts.Add(new StationCount()
            //            //{
            //            //    Type = DevActionType.In.GetDescription(),
            //            //    StationNum = taskSum.Count(x => x is { Duration: 3, RunMode: "2" }),
            //            //    StationIndex = 2
            //            //});
            //            ////出库
            //            //stationCounts.Add(new StationCount()
            //            //{
            //            //    Type = DevActionType.Out.GetDescription(),
            //            //    StationNum = taskSum.Count(x => x is { Duration: 4, RunMode: "1" }),
            //            //    StationIndex = 1
            //            //});
            //            //stationCounts.Add(new StationCount()
            //            //{
            //            //    Type = DevActionType.Out.GetDescription(),
            //            //    StationNum = taskSum.Count(x => x is { Duration: 4, RunMode: "2" }),
            //            //    StationIndex = 2
            //            //});
            //            //info.StationCount = stationCounts;

            //            //#endregion 计算任务的工位使用数量

            //            runInfos.Add(info);
            //        }
            //        break;

            //    case DevType.Robot: //机械臂
            //        type = DevType.Robot.ToString();
            //        //获取时段内设备的运行状态
            //        var robotInfoList = plcEx.Queryable<DevRunInfo>().Where(x => x.Type == type && x.Frame >= req.StateTime && x.Frame < req.EndTime).ToList().GroupBy(x => x.Code);
            //        foreach (var runInfo in robotInfoList)
            //        {
            //            var curPoints = new List<string>();
            //            if (runInfo.Key == "Robot1")
            //            {
            //                curPoints = new List<string>() { "8090", "8092" };
            //            }
            //            else if (runInfo.Key == "Robot2")
            //            {
            //                curPoints = new List<string>() { "8096", "8098" };
            //            }

            //            var info = new RunInfoViewMode()
            //            {
            //                Code = runInfo.Key,
            //                EnterDepot = db.Queryable<WCS_TaskDtl>().With(SqlWith.NoLock)
            //                    .Where(x => x.Desc == "码垛抓取完成" && x.AddTime >= req.StateTime && x.AddTime < req.EndTime && curPoints.Contains(x.CurPoint))
            //                    .SplitTable(x => x.Take(2))
            //                    .Count(),
            //                //OutDepot = db.Queryable<WCS_TaskOld>().With(SqlWith.NoLock)
            //                //    .Where(x => x.Status == TaskStatus.Finish && x.Type == TaskType.OutDepot &&
            //                //                x.Device == runInfo.Key && x.EndTime >= req.StateTime &&
            //                //                x.EndTime < req.EndTime)
            //                //    .SplitTable(x => x.Take(2))
            //                //    .Count(),
            //                Free = runInfo.Where(x =>
            //                    x.RunMode == RobotMode.自动.GetDescription() &&
            //                    x.RunStatus == RobotRunStatus.空闲.GetDescription()).Sum(x => x.Duration) / 1000 / 60,
            //                Alarm = runInfo.Where(x => x.RunMode == RobotMode.故障.GetDescription())
            //                    .Sum(x => x.Duration) / 1000 / 60,
            //                Manual = runInfo.Where(x => x.RunMode == RobotMode.手动.GetDescription())
            //                    .Sum(x => x.Duration) / 1000 / 60,
            //                Automatic = runInfo.Where(x => x.RunMode == RobotMode.自动.GetDescription()).Sum(x => x.Duration) / 1000 / 60,
            //                Working = runInfo.Where(x => x.RunMode == RobotMode.自动.GetDescription() && (x.RunStatus == RobotRunStatus.抓取中.GetDescription() || x.RunStatus == RobotRunStatus.放置中.GetDescription()))
            //                    .Sum(x => x.Duration) / 1000 / 60,
            //                TotalTime = runInfo.Sum(x => x.Duration) / 1000 / 60
            //            };

            //            #region 开始分析设备动作,不计算停止时间

            //            var devActions = new List<DevActionViewMode>();
            //            double totalTime = 0; //总耗时
            //            double totalCount = 0; //总次数
            //            //入库
            //            var infos = runInfo.Where(x => x.RunMode == RobotMode.自动.GetDescription()).OrderBy(x => x.Frame).ToList();
            //            totalTime = infos.Where(x => x.RunStatus == RobotRunStatus.抓取中.GetDescription() || x.RunStatus == RobotRunStatus.放置中.GetDescription()).Sum(x => x.Duration);
            //            totalCount = infos.Count(x => x.RunStatus == RobotRunStatus.抓取中.GetDescription());
            //            devActions.Add(new DevActionViewMode()
            //            {
            //                Type = DevActionType.In.GetDescription(),
            //                ActionAmount = totalCount,
            //                ActionTime = totalTime == 0 ? 0 : Math.Round(totalTime / totalCount, 2),
            //            });
            //            info.DevAction = devActions;

            //            #endregion 开始分析设备动作,不计算停止时间

            //            runInfos.Add(info);
            //        }

            //        break;

            //    case DevType.Truss:
            //        //type = DevType.Truss.ToString();
            //        ////获取时段内设备的运行状态
            //        //var trussInfoList = plcEx.Queryable<DevRunInfo>().Where(x => x.Type == type && x.Frame >= req.StateTime && x.Frame < req.EndTime).ToList().GroupBy(x => x.Code);
            //        //foreach (var runInfo in trussInfoList)
            //        //{
            //        //    var info = new RunInfo()
            //        //    {
            //        //        Code = runInfo.Key,
            //        //        EnterDepot = db.Queryable<WCS_TaskOld>().With(SqlWith.NoLock)
            //        //            .Where(x => x.Status == TaskStatus.Finish && x.Type == TaskType.SetPlate &&
            //        //                        x.Device == runInfo.Key && x.EndTime >= req.StateTime &&
            //        //                        x.EndTime < req.EndTime)
            //        //            .SplitTable(x => x.Take(2))
            //        //            .Count(),
            //        //        Free = runInfo.Where(x => x.RunMode == TrussStatus.Idle.GetDescription()).Sum(x => x.Duration) / 1000 / 60,
            //        //        Alarm = runInfo.Where(x => x.RunMode == TrussStatus.Alarm.GetDescription()).Sum(x => x.Duration) / 1000 / 60,
            //        //        Manual = runInfo.Where(x => x.RunMode == TrussStatus.Manual.GetDescription() || x.RunMode == TrussStatus.KeepInRepair.GetDescription()).Sum(x => x.Duration) / 1000 / 60,
            //        //        Automatic = runInfo.Where(x => x.RunMode == TrussStatus.Execute.GetDescription()).Sum(x => x.Duration) / 1000 / 60,
            //        //    };

            //        //    #region 开始分析设备动作,不计算停止时间

            //        //    var devActions = new List<DevActionViewMode>();
            //        //    double totalTime = 0; //总耗时
            //        //    double totalCount = 0; //总次数
            //        //    //入库
            //        //    var infos = runInfo.Where(x => x.RunMode == TrussStatus.Execute.GetDescription()).ToList();
            //        //    totalTime = infos.Where(x => x.RunMode == TrussStatus.Execute.GetDescription()).Sum(x => x.Duration);
            //        //    totalCount = infos.Count(x => x.RunMode == TrussStatus.Execute.GetDescription());
            //        //    devActions.Add(new DevActionViewMode()
            //        //    {
            //        //        Type = DevActionType.In.GetDescription(),
            //        //        ActionAmount = totalCount,
            //        //        ActionTime = totalTime == 0 ? 0 : Math.Round(totalTime / totalCount, 2),
            //        //    });

            //        //    info.DevAction = devActions;

            //        //    #endregion 开始分析设备动作,不计算停止时间

            //        //    #region 计算任务的工位使用数量

            //        //    var stationCounts = new List<StationCount>();
            //        //    type = DevType.TrussTaskSum.ToString();
            //        //    var taskSum = plcEx.Queryable<DevRunInfo>().Where(x => x.Code == runInfo.Key && x.Type == type && x.Frame >= req.StateTime && x.Frame < req.EndTime)
            //        //        .ToList();

            //        //    //入库
            //        //    stationCounts.Add(new StationCount()
            //        //    {
            //        //        Type = DevActionType.In.GetDescription(),
            //        //        StationNum = taskSum.Count(x => x is { RunMode: "1" }),
            //        //        StationIndex = 1
            //        //    });
            //        //    stationCounts.Add(new StationCount()
            //        //    {
            //        //        Type = DevActionType.In.GetDescription(),
            //        //        StationNum = taskSum.Count(x => x is { RunMode: "2" }),
            //        //        StationIndex = 2
            //        //    });
            //        //    stationCounts.Add(new StationCount()
            //        //    {
            //        //        Type = DevActionType.In.GetDescription(),
            //        //        StationNum = taskSum.Count(x => x is { RunMode: "3" }),
            //        //        StationIndex = 3
            //        //    });
            //        //    stationCounts.Add(new StationCount()
            //        //    {
            //        //        Type = DevActionType.In.GetDescription(),
            //        //        StationNum = taskSum.Count(x => x is { RunMode: "4" }),
            //        //        StationIndex = 4
            //        //    });
            //        //    stationCounts.Add(new StationCount()
            //        //    {
            //        //        Type = DevActionType.In.GetDescription(),
            //        //        StationNum = taskSum.Count(x => x is { RunMode: "5" }),
            //        //        StationIndex = 5
            //        //    });
            //        //    stationCounts.Add(new StationCount()
            //        //    {
            //        //        Type = DevActionType.In.GetDescription(),
            //        //        StationNum = taskSum.Count(x => x is { RunMode: "6" }),
            //        //        StationIndex = 6
            //        //    });
            //        //    stationCounts.Add(new StationCount()
            //        //    {
            //        //        Type = DevActionType.In.GetDescription(),
            //        //        StationNum = taskSum.Count(x => x is { RunMode: "7" }),
            //        //        StationIndex = 7
            //        //    });
            //        //    stationCounts.Add(new StationCount()
            //        //    {
            //        //        Type = DevActionType.In.GetDescription(),
            //        //        StationNum = taskSum.Count(x => x is { RunMode: "8" }),
            //        //        StationIndex = 8
            //        //    });
            //        //    stationCounts.Add(new StationCount()
            //        //    {
            //        //        Type = DevActionType.In.GetDescription(),
            //        //        StationNum = taskSum.Count(x => x is { RunMode: "9" }),
            //        //        StationIndex = 9
            //        //    });
            //        //    stationCounts.Add(new StationCount()
            //        //    {
            //        //        Type = DevActionType.In.GetDescription(),
            //        //        StationNum = taskSum.Count(x => x is { RunMode: "10" }),
            //        //        StationIndex = 10
            //        //    });

            //        //    info.StationCount = stationCounts;

            //        //    #endregion 计算任务的工位使用数量

            //        //    runInfos.Add(info);
            //        //}
            //        break;
            //}
            //var res = new PagedInfoResponse<RunInfoViewMode>();
            //res.Result = runInfos;
            //res.TotalNum = runInfos.Count;
            //return res;
        }

        #region 设备IP相关

        /// <summary>
        /// 检查Ip是否正常联通
        /// </summary>
        /// <param name="strIpOrDName">输入参数,表示IP地址或域名</param>
        /// <returns></returns>
        [HttpGet]
        public static bool PingIpOrDomainName(string strIpOrDName)
        {
            try

            {
                var objPingSender = new Ping();

                var objPinOptions = new PingOptions
                {
                    DontFragment = true
                };

                const string data = "";

                var buffer = Encoding.UTF8.GetBytes(data);

                const int intTimeout = 120;

                var objPinReply = objPingSender.Send(strIpOrDName, intTimeout, buffer, objPinOptions);

                var strInfo = objPinReply.Status.ToString();

                return strInfo == "Success";
            }
            catch (Exception)

            {
                return false;
            }
        }

        /// <summary>
        ///  获取设备IP检测结果
        /// </summary>
        /// <returns>设备IP检测结果</returns>
        [HttpGet]
        public List<DeviceIpTestResults> DeviceIpTest()
        {
            if (!ServiceHub.DeviceIPList.Any()) throw new Exception("未配置任何Ip");
            var deviceIpTestResults = new List<DeviceIpTestResults>();
            ServiceHub.DeviceIPList.ForEach(ip =>
            {
                deviceIpTestResults.Add(new DeviceIpTestResults
                {
                    Ip = ip,
                    Result = PingIpOrDomainName(ip)
                });
            });

            return deviceIpTestResults;
        }

        /// <summary>
        ///  获取设备Ip集合
        /// </summary>
        /// <returns>设备Ip集合</returns>
        [HttpGet]
        public List<string> GetDeviceIpList()
        {
            if (!ServiceHub.DeviceIPList.Any()) throw new Exception("未配置任何Ip");
            return ServiceHub.DeviceIPList;
        }

        #endregion 设备IP相关

        /// <summary>
        ///  获取小时范围
        /// </summary>
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <returns></returns>
        private List<List<DateTime>> GetHourRanges(DateTime startTime, DateTime endTime)
        {
            List<List<DateTime>> hourRanges = new List<List<DateTime>>(); // 存放每个小时的开始时间和结束时间对

            // 循环遍历每个小时
            DateTime currentHour = startTime;
            while (currentHour <= endTime)
            {
                DateTime hourStart = currentHour; // 当前小时的开始时间
                DateTime hourEnd = currentHour.AddHours(1).AddSeconds(-1); // 当前小时的结束时间
                hourRanges.Add(new[] { hourStart, hourEnd }.ToList()); // 将当前小时的开始时间和结束时间添加到列表中
                currentHour = currentHour.AddHours(1); // 移动到下一个小时
            }
            return hourRanges;
        }

        /// <summary>
        ///  获取小时范围
        /// </summary>
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <returns></returns>
        private List<List<DateTime>> GetDayRanges(DateTime startTime, DateTime endTime)
        {
            List<List<DateTime>> dayRanges = new List<List<DateTime>>(); // 存放每个小时的开始时间和结束时间对

            // 循环遍历每个小时
            DateTime currentDate = startTime;
            while (currentDate <= endTime)
            {
                DateTime dayStart = currentDate.Date; // 当天的开始时间（凌晨）
                DateTime dayEnd = currentDate.Date.AddDays(1).AddSeconds(-1); // 当天的结束时间（当天的23:59:59）
                dayRanges.Add(new[] { dayStart, dayEnd }.ToList()); // 将当天的开始时间和结束时间添加到列表中
                currentDate = currentDate.AddDays(1); // 移动到下一天
            }
            return dayRanges;
        }
    }

    /// <summary>
    ///  带分页的返回体
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class PagedInfoResponse<T>
    {
        /// <summary>
        /// 每页行数
        /// </summary>
        public int PageSize { get; set; } = 10;

        /// <summary>
        /// 当前页
        /// </summary>
        public int PageIndex { get; set; } = 1;

        /// <summary>
        /// 总记录数
        /// </summary>
        public int TotalNum { get; set; }

        /// <summary>
        /// 总页数
        /// </summary>
        public int TotalPage
        {
            get
            {
                if (TotalNum > 0)
                {
                    return TotalNum % PageSize == 0 ? TotalNum / PageSize : TotalNum / PageSize + 1;
                }
                else
                {
                    return 0;
                }
            }
            set { }
        }

        public List<T> Result { get; set; }
        public Dictionary<string, object> Extra { get; set; } = new Dictionary<string, object>();

        public PagedInfoResponse()
        {
        }
    }
}