Exemplo n.º 1
0
        public object GetSet([FromQuery] bool init = false, int wId = 1, int qId = 0, int page = 0)
        {
            var workshop = WorkshopHelper.Instance.Get <Workshop>(wId);

            if (init)
            {
                var data = MonitoringKanBanSetHelper.GetDetail(wId).ToList();
                data.Insert(0, new MonitoringKanBanSet
                {
                    Id     = 0,
                    Name   = "所有设备",
                    Type   = KanBanEnum.设备详情看板,
                    Order  = -1,
                    IsShow = true
                });
                var item = MonitoringKanBanSetHelper.Instance.Configs.ToDictionary(c => (int)c.Key, c =>
                {
                    foreach (var v in c.Value)
                    {
                        v.FieldList = v.FieldList.Select((x, i) => MonitoringKanBanSetHelper.ConvertFieldConfig(x, i, v.Display != KanBanItemDisplayEnum.Chart)).ToList();
                    }
                    return(c.Value);
                });
                foreach (var d in data)
                {
                    if (d.Type != KanBanEnum.生产相关看板)
                    {
                        continue;
                    }

                    var t = new List <KanBanItemSet>();
                    foreach (var list in d.ItemList)
                    {
                        var configs = MonitoringKanBanSetHelper.Instance.Configs[d.Type];
                        var config  = configs.FirstOrDefault(x => x.Item == list.Item);
                        if (config == null)
                        {
                            continue;
                        }
                        if ((list.FieldList == null || !list.FieldList.Any()) && MonitoringKanBanSetHelper.Instance.Configs.ContainsKey(d.Type))
                        {
                            list.FieldList = (config.FieldList.Select((x, i) => MonitoringKanBanSetHelper.ConvertFieldSet(x, i, config.Display != KanBanItemDisplayEnum.Chart)).ToList());
                        }
                        else if (list.FieldList.Count != config.FieldList.Count && config.FieldList.Any(x => list.FieldList.All(y => y.Field != x.Field)))
                        {
                            var fieldList = new List <KanBanTableFieldSet>();
                            for (var i = 0; i < config.FieldList.Count; i++)
                            {
                                var order  = i + 1;
                                var field  = config.FieldList[i];
                                var sField = list.FieldList.FirstOrDefault(x => x.Field == field.Field);
                                if (sField != null)
                                {
                                    //sField.Order = order;
                                    fieldList.Add(sField);
                                }
                                else
                                {
                                    fieldList.Add(MonitoringKanBanSetHelper.ConvertFieldSet(field, order,
                                                                                            config.Display != KanBanItemDisplayEnum.Chart));
                                }
                            }
                            list.FieldList = fieldList;
                        }
                        t.Add(list);
                    }

                    d.Items = t.ToJSON();
                }

                return(new
                {
                    errno = 0,
                    errmsg = "成功",
                    menu = EnumHelper.EnumToList <KanBanEnum>().Select(x => new { Id = x.EnumValue, Type = x.EnumName }),
                    item,
                    shift = EnumHelper.EnumToList <KanBanShiftsEnum>(true).Select(x => new { Id = x.EnumValue, Type = x.EnumName }),
                    //data
                    data = data.Select(x =>
                    {
                        var t = ClassExtension.CopyTo <MonitoringKanBanSet, MonitoringKanBanSetWeb>(x);
                        t.DeviceIdList = x.DeviceIdList;
                        t.VariableList = x.VariableList;
                        t.ItemList = x.ItemList.Select(y =>
                        {
                            var ty = ClassExtension.CopyTo <KanBanItemSet, KanBanItemSetWeb>(y);
                            ty.FieldList = y.FieldList;
                            ty.ConfigList = y.ConfigList;
                            return ty;
                        }).ToList();
                        return t;
                    })
                });
            }

            var set = qId != 0 ? MonitoringKanBanSetHelper.Instance.Get <MonitoringKanBanSet>(qId) : new MonitoringKanBanSet
            {
                Type = KanBanEnum.设备详情看板
            };

            if (set != null)
            {
                MonitoringKanBan kanBan;
                var key = new Tuple <int, int>(set.Id, set.WorkshopId);
                switch (set.Type)
                {
                case KanBanEnum.设备详情看板:
                    kanBan = HKanBanHelper.MonitoringKanBanDic.ContainsKey(key)
                            ? HKanBanHelper.MonitoringKanBanDic[key]
                            : new MonitoringKanBan();
                    return(new
                    {
                        errno = 0,
                        errmsg = "成功",
                        type = set.Type,
                        time = kanBan?.Time ?? DateTime.Now,
                        data = kanBan
                    });

                case KanBanEnum.设备状态看板:
                    #region 设备状态看板
                {
                    var ret = new MonitoringKanBan();
                    page = page < 0 ? 0 : page;
                    var idList = set.DeviceIdList;
                    var deviceLibraryDetails = ServerConfig.ApiDb.Query <DeviceDetail>(
                        "SELECT a.*, b.ModelName, b.CategoryId, b.CategoryName, c.FirmwareName, d.ApplicationName, e.HardwareName, f.SiteName, f.Region, " +
                        "g.ScriptName, IFNULL(h.`Name`, '')  AdministratorName, i.`Class`, j.FlowCardId, j.FlowCard, j.LastFlowCardId, j.LastFlowCard, j.StartTime FROM device_library a " +
                        $"JOIN device_model_all b ON a.ModelId = b.Id " +
                        "JOIN firmware c ON a.FirmwareId = c.Id " +
                        "JOIN application d ON a.ApplicationId = d.Id " +
                        "JOIN hardware e ON a.HardwareId = e.Id " +
                        "JOIN site f ON a.SiteId = f.Id " +
                        "JOIN script_version g ON a.ScriptId = g.Id " +
                        "LEFT JOIN (SELECT * FROM(SELECT * FROM maintainer ORDER BY MarkedDelete)a GROUP BY a.Account) h ON a.Administrator = h.Account " +
                        "JOIN device_class i ON a.ClassId = i.Id " +
                        "JOIN `npc_proxy_link` j ON a.Id = j.DeviceId " +
                        $"WHERE a.`MarkedDelete` = 0" +
                        $"{(idList.Any() ? " AND a.Id IN @idList" : "")}" +
                        $" ORDER BY a.Id;", new { idList }).ToDictionary(x => x.Id);

                    var faultDevices = ServerConfig.ApiDb.Query <dynamic>(
                        $"SELECT * FROM (SELECT a.* FROM `fault_device_repair` a " +
                        $"JOIN `device` b ON a.DeviceId = b.Id " +
                        $"WHERE a.`State` != @state" +
                        $"{(idList.Any() ? " AND a.DeviceId IN @idList" : "")}" +
                        $" AND a.MarkedDelete = 0 ORDER BY a.DeviceId, a.State DESC ) a GROUP BY DeviceCode;",
                        new { state = RepairStateEnum.Complete, idList });
                    foreach (var faultDevice in faultDevices)
                    {
                        var device = deviceLibraryDetails.Values.FirstOrDefault(x => x.Id == faultDevice.DeviceId);
                        if (device != null)
                        {
                            device.RepairState = faultDevice.State;
                        }
                    }

                    var url = ServerConfig.GateUrl + UrlMappings.Urls[UrlMappings.deviceListGate];
                    //向GateProxyLink请求数据
                    var resp = !idList.Any() ? HttpServer.Get(url) :
                               HttpServer.Get(url, new Dictionary <string, string>
                        {
                            { "ids", idList.Join() }
                        });
                    DeviceResult dataResult = null;
                    if (resp != "fail")
                    {
                        try
                        {
                            dataResult = JsonConvert.DeserializeObject <DeviceResult>(resp);
                            if (dataResult.errno == Error.Success)
                            {
                                foreach (var deviceInfo in dataResult.datas)
                                {
                                    var deviceId = deviceInfo.DeviceId;
                                    if (deviceLibraryDetails.ContainsKey(deviceId))
                                    {
                                        deviceLibraryDetails[deviceId].State       = deviceInfo.State;
                                        deviceLibraryDetails[deviceId].DeviceState = deviceInfo.DeviceState;
                                        if (deviceLibraryDetails[deviceId].DeviceState == DeviceState.Waiting &&
                                            deviceLibraryDetails[deviceId].StartTime != default(DateTime) &&
                                            deviceLibraryDetails[deviceId].TotalTime <= HKanBanHelper.IdleSecond)
                                        {
                                            deviceLibraryDetails[deviceId].DeviceState = DeviceState.Readying;
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            Log.Error($"{UrlMappings.Urls[UrlMappings.deviceListGate]},信息:{e}");
                        }
                    }

                    //var data = deviceLibraryDetails.Values.All(x => int.TryParse(x.Code, out _))
                    //    ? deviceLibraryDetails.Values.OrderByDescending(x => x.DeviceState).ThenByDescending(x => x.DeviceStateStr).ThenBy(x => int.Parse(x.Code))
                    //    : deviceLibraryDetails.Values.OrderByDescending(x => x.DeviceState).ThenByDescending(x => x.DeviceStateStr).ThenBy(x => x.Code);

                    var allDevices = deviceLibraryDetails.Values.OrderBy(x => int.TryParse(x.Code, out var a) ? a : 9999999).ThenBy(x => x.Code).ToList();

                    var sum   = allDevices.Count;
                    var gz    = allDevices.Count(x => x.RepairState != -1);
                    var other = allDevices.Where(x => x.RepairState == -1);
                    var zc    = other.Count(x => x.DeviceState == DeviceState.Processing)
                                + other.Count(x => x.DeviceState == DeviceState.Restart)
                                + other.Count(x => x.DeviceState == DeviceState.UpgradeFirmware)
                                + other.Count(x => x.DeviceState == DeviceState.UpgradeScript)
                                + other.Count(x => x.DeviceState == DeviceState.Readying)
                                + other.Count(x => x.DeviceState == DeviceState.Waiting);
                    var jg  = other.Count(x => x.DeviceState == DeviceState.Processing);
                    var zb  = other.Count(x => x.DeviceState == DeviceState.Readying);
                    var xz  = other.Count(x => x.DeviceState == DeviceState.Waiting);
                    var wlj = sum - zc;
                    var tp  = (int)Math.Ceiling((decimal)sum / (set.Length <= 0 ? 30 : set.Length));
                    if (page >= tp)
                    {
                        page = 0;
                    }
                    var devices              = allDevices.Skip(set.Length * page).Take(set.Length);
                    var scriptIds            = devices.Select(y => y.ScriptId);
                    var dataNameDictionaries = scriptIds.Any() ? DataNameDictionaryHelper.GetDataNameDictionaryDetails(scriptIds) : new List <DataNameDictionaryDetail>();
                    ret.Id = qId;

                    foreach (var device in devices)
                    {
                        var t  = ClassExtension.ParentCopyToChild <DeviceDetail, MonitoringSetData>(device);
                        var vs = set.VariableList.OrderBy(x => x.Order);

                        DeviceData deviceData = null;
                        if (dataResult != null &&
                            dataResult.datas.Any(d => d.Id == device.Id) &&
                            dataResult.datas.First(d => d.Id == device.Id).DeviceData != null)
                        {
                            deviceData = dataResult.datas.First(d => d.Id == device.Id).DeviceData;
                        }

                        //if (device.RepairState != -1 && device.State != SocketState.Connected)
                        //{
                        //    deviceLibraryDetails[deviceId].in
                        //}
                        //else
                        //{
                        //    FlowCard fc = null;
                        //    if (int.TryParse(device.FlowCard, out var id))
                        //    {
                        //        fc = flowCards.FirstOrDefault(x => x.Id == id);
                        //    }
                        //    deviceLibraryDetails[deviceId].FlowCard = fc?.Card ?? "";
                        //}

                        foreach (var x in vs)
                        {
                            var dn = dataNameDictionaries.FirstOrDefault(d =>
                                                                         d.VariableTypeId == x.VariableTypeId && d.PointerAddress == x.PointerAddress);

                            ////设备状态
                            //var stateDId = 1;
                            ////总加工次数
                            //var processCountDId = 63;
                            ////总加工时间
                            //var processTimeDId = 64;
                            ////当前加工流程卡号
                            //var currentFlowCardDId = 6;
                            ////累积运行总时间
                            //var runTimeDId = 5;

                            if (dn == null)
                            {
                                continue;
                            }

                            var r = new MonitoringSetSingleDataDetail
                            {
                                Order     = x.Order,
                                SubOrder  = x.SubOrder,
                                Delimiter = x.Delimiter,
                                Sid       = x.ScriptId,
                                Type      = x.VariableTypeId,
                                Add       = x.PointerAddress,
                                VName     = x.VariableName.IsNullOrEmpty() ? dn.VariableName ?? "" : x.VariableName,
                            };

                            if (dn.VariableTypeId == 1 && dn.VariableNameId == AnalysisHelper.stateDId)
                            {
                                r.V = device.DeviceStateStr;
                            }
                            else if (deviceData != null)
                            {
                                List <int> bl = null;
                                switch (x.VariableTypeId)
                                {
                                case 1: bl = deviceData.vals; break;

                                case 2: bl = deviceData.ins; break;

                                case 3: bl = deviceData.outs; break;

                                default: break;
                                }

                                if (bl != null)
                                {
                                    if (bl.Count > x.PointerAddress - 1)
                                    {
                                        var chu = Math.Pow(10, dn.Precision);
                                        var v   = (decimal)(bl.ElementAt(x.PointerAddress - 1) / chu);
                                        if (dn.VariableTypeId == 1 && (dn.VariableNameId == AnalysisHelper.flowCardDId || dn.VariableNameId == AnalysisHelper.nextFlowCardDId))
                                        {
                                            //var flowCard = FlowCardHelper.Instance.Get<FlowCard>((int)v);
                                            //r.V = flowCard?.Card ?? "";
                                            r.V = device.LastFlowCard;
                                        }
                                        else if (dn.VariableTypeId == 1 && dn.VariableNameId == AnalysisHelper.currentProductDId)
                                        {
                                            //var production = ProductionHelper.Instance.Get<Production>((int)v);
                                            //r.V = production?.ProductionName ?? "";

                                            var production = ProductionHelper.GetProduction(device.LastFlowCardId);
                                            r.V = production?.Name ?? "";
                                        }
                                        else
                                        {
                                            r.V = v.ToString();
                                        }
                                    }
                                }
                            }
                            t.Data.Add(r);
                        }
                        ret.MSetData.Add(t);
                    }
                    var monitoringProcesses = new List <MonitoringProcess>();
                    //monitoringProcesses.AddRange(AnalysisHelper.GetMonitoringProcesses(idList));
                    //if (!monitoringProcesses.Any())
                    //{
                    //    monitoringProcesses.AddRange(ServerConfig.ApiDb.Query<MonitoringProcess>(
                    //        "SELECT b.*, c.CategoryId, c.CategoryName, a.`Code`, a.`ScriptId` FROM `device` a " +
                    //        "JOIN `npc_proxy_link` b ON a.Id = b.DeviceId " +
                    //        "JOIN (SELECT a.*, b.CategoryName FROM `device_model` a " +
                    //        "JOIN `device_category` b ON a.CategoryId = b.Id) c ON a.ModelId = c.Id WHERE a.Id in @idList AND a.MarkedDelete = 0;", new { idList }));
                    //}
                    monitoringProcesses.AddRange(AnalysisHelper.GetMonitoringProcesses(wId, idList));
                    if (!monitoringProcesses.Any())
                    {
                        monitoringProcesses.AddRange(ServerConfig.ApiDb.Query <MonitoringProcess>(
                                                         "SELECT b.*, c.CategoryId, c.CategoryName, a.`Code`, a.`ScriptId` FROM `device` a " +
                                                         "JOIN `npc_proxy_link` b ON a.Id = b.DeviceId " +
                                                         "JOIN device_model_all c ON a.ModelId = c.Id WHERE a.Id in @idList AND a.MarkedDelete = 0;"));
                    }
                    var timeRate    = new List <decimal>();
                    var processTime = monitoringProcesses.Sum(x => x.ProcessTime);
                    var runTime     = monitoringProcesses.Sum(x => x.RunTime);
                    var rate        = runTime > 0 ? (processTime * 100m / (runTime)).ToRound() : 0;
                    timeRate.Add(rate);
                    timeRate.AddRange(workshop.StatisticTimeList.Select((_, i) =>
                        {
                            var p = monitoringProcesses.Where(x => x.ExtraData.Parts.Count > i).Sum(y => y.ExtraData.Parts.FirstOrDefault(x => x.Shift == i)?.ProcessTime ?? 0);
                            var r = monitoringProcesses.Where(x => x.ExtraData.Parts.Count > i).Sum(y => y.ExtraData.Parts.FirstOrDefault(x => x.Shift == i)?.RunTime ?? 0);
                            return(r > 0 ? (p * 100m / (r)).ToRound() : 0);
                        }));

                    //var now = DateTime.Now;
                    //var currentWorkTime = DateTimeExtend.GetDayWorkTimeRanges(workshop.Shifts, workshop.StatisticTimeList, now);
                    //var workTime = DateTimeExtend.GetDayWorkDay(workshop.ShiftTimeList, now);
                    //var reports = FlowCardReportGetHelper.GetReport(wId, workTime.Item1, workTime.Item2, 18).ToList();
                    var qualifiedRate = new List <decimal>();
                    //var qualified = reports.Sum(x => x.HeGe);
                    //var total = reports.Sum(x => x.Total);
                    var qualified = monitoringProcesses.Sum(y => y.DayQualified);
                    var total     = monitoringProcesses.Sum(x => x.DayTotal);
                    rate = total > 0 ? (qualified * 100m / (total)).ToRound() : 0;
                    qualifiedRate.Add(rate);
                    qualifiedRate.AddRange(workshop.StatisticTimeList.Select((range, i) =>
                        {
                            //var p = reports.Where(x => x.Time.InSameRange(range)).Sum(y => y.HeGe);
                            //var r = reports.Where(x => x.Time.InSameRange(range)).Sum(y => y.Total);
                            var p = monitoringProcesses.Where(x => x.ExtraData.Parts.Count > i).Sum(y => y.ExtraData.Parts.FirstOrDefault(x => x.Shift == i)?.DayQualified ?? 0);
                            var r = monitoringProcesses.Where(x => x.ExtraData.Parts.Count > i).Sum(y => y.ExtraData.Parts.FirstOrDefault(x => x.Shift == i)?.DayTotal ?? 0);
                            return(r > 0 ? (p * 100m / (r)).ToRound() : 0);
                        }));

                    return(new
                        {
                            errno = 0,
                            errmsg = "成功",
                            type = set.Type,
                            time = DateTime.Now,
                            jg,
                            zc,
                            zb,
                            xz,
                            gz,
                            wlj,
                            sum,
                            timeRate,
                            qualifiedRate,
                            row = set.Row,
                            col = set.Col,
                            cCol = set.ContentCol,
                            cName = set.ColNameList,
                            len = set.Length,
                            cp = page,
                            tp,
                            data = ret.MSetData
                        });
                }

                    #endregion
                case KanBanEnum.生产相关看板:
                    #region 生产相关看板
                    kanBan = HKanBanHelper.MonitoringKanBanDic.ContainsKey(key)
                            ? HKanBanHelper.MonitoringKanBanDic[key]
                            : new MonitoringKanBan();
                    return(new
                    {
                        errno = 0,
                        errmsg = "成功",
                        type = set.Type,
                        time = kanBan?.Time ?? DateTime.Now,
                        items = set.ItemList.Select(y =>
                        {
                            var ty = ClassExtension.CopyTo <KanBanItemSet, KanBanItemSetWeb>(y);
                            ty.FieldList = y.FieldList;
                            return ty;
                        }).ToList(),
                        colSet = set.ColSet,
                        data = kanBan?.ItemData ?? new Dictionary <string, List <dynamic> >()
                    });

                    #endregion
                }
            }

            return(new
            {
                errno = 0,
                type = 0,
                errmsg = "成功",
                time = DateTime.Now,
            });
        }