1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;
 
namespace EquipmentCollectionForm
{
    public partial class EquipmentCollectionForm_KB : Form
    {
        private json objJsonResult = new json();
        DataTable dt = new DataTable();
        public DBHelper oCN = new DBHelper();
        public string TimeDate = "";
        public EquipmentCollectionForm_KB()
        {
            InitializeComponent();
        }
 
        private void btnWB_Click(object sender, EventArgs e)
        {
            MessageBox.Show("数据读取中...", "操作提示");
        }
        
        //定时获取数据
        private async void timer_Tick(object sender, EventArgs e)
        {
          
            string Url = DBHelper.GetConfigKey(AppDomain.CurrentDomain.BaseDirectory + "Config/SQLAPI.config", "sUrl");
            string urls = Url + EquipmentType_KB.One;
            // 准备要发送的表单数据
            var formData = new FormUrlEncodedContent(new[]
            {
                    new KeyValuePair<string, string>("userName", "admin"),
                    new KeyValuePair<string, string>("password", "Youngsunabc123..")
                    // 添加更多键值对,根据您的需要
                });
            JsonResult_KB jsonResult = await getUrl(urls, formData);
            string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:00");
 
            SaveInjectionMoldingMachine(jsonResult.data.token, Url, time);
 
        }
 
       
 
        //设备采集数据 保存
        public async void SaveInjectionMoldingMachine(string token, string Url, string time)
        {
           
            if (TimeDate == "")
            {
                TimeDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); ;
            }           
 
            //获取所有设备数据
            JsonEquipmentData_KB jsonResult = await FindDeviceList(Url, token);
            if (jsonResult.code != "0")
            {
                MessageBox.Show("设备列表报错:" + jsonResult.message);
            }
            else
            {
 
                string nos = "";
                //获取设备编码
                for (int i = 0; i < jsonResult.data.Count; i++)
                {
                    nos += jsonResult.data[i].no + ",";                   
                }
                nos = nos.Substring(0, nos.Length - 1);
                //获取参数 获取每个设备对应的所有参数   20250723 凯贝没有工艺参数采集  20250814采集铆压机的工艺参数
                JsonEquipmentData_KB jsonEquipment = await FindAllDevicePropsDetailByTimeRange(Url, token, nos, TimeDate, time);
 
                //JsonEquipmentData_KB jsonEquipment= null;
 
                var JsonData_KB = "{\"data\":[";
 
                if (jsonEquipment == null)
                {
                    CustomWriteLog("jsonEquipment对象为空", DateTime.Now.ToString("yyyy-MM-dd"));
                }
                //20250723注释
                if (jsonEquipment.data == null)
                {
                    CustomWriteLog("jsonEquipment.data属性为空", DateTime.Now.ToString("yyyy-MM-dd"));
                }
                else
                {
                    CustomWriteLog("开始循环工艺参数总数为:'" + jsonEquipment.data.Count + "'", DateTime.Now.ToString("yyyy-MM-dd"));
 
                    //通过每个设备进行循环赋值
                    for (int i = 0; i < jsonEquipment.data.Count; i++)
                    {
                        //循环 螺母压装设备对应的所有工艺参数
                        for (int j = 0; j < jsonEquipment.data[i].props.Count; j++)
                        {
                            //循环 每个参数对应的所有数据
                            for (int k = 0; k < jsonEquipment.data[i].props[j].datas.Count; k++)
                            {
                                JsonData_KB += "{\"HDate\":\"" + jsonEquipment.data[i].props[j].datas[k].createTime + "\",\"HTechParamName\":\"" + jsonEquipment.data[i].props[j].propName + "\",\"HResult\":\"" + jsonEquipment.data[i].props[j].datas[k].value + "\",\"HCount\":1,\"HSourceCode\":\"" + jsonEquipment.data[i].deviceNo + "\"},";
                                
                            }
                        }                      
                    }
                }
 
                //获取设备时间段产量    因为没有工艺参数采集 所以需要单独拉出来采集数量
                for (int i = 0; i < jsonResult.data.Count; i++)
                {                   
                    JsonEquipmentData_KB data = await FindProdByNosAndTime(Url, token, jsonResult.data[i].no, TimeDate, time);
                    for (int j = 0; j < data.data.Count; j++)
                    {
                        JsonData_KB += "{\"HDate\":\"" + time + "\",\"HTechParamName\":\"生产数量\",\"HResult\":\"OK\",\"HCount\":" + data.data[j].prod + ",\"HSourceCode\":\"" + jsonResult.data[i].no + "\"},";
                    }
                }
 
                CustomWriteLog("02", DateTime.Now.ToString("yyyy-MM-dd"));
 
                //获取设备运行状态
                var EquipmentStaus = await FindDeviceStatusByNos(Url, token, nos);
                if (EquipmentStaus == null)
                {
                    CustomWriteLog("EquipmentStaus对象为空", DateTime.Now.ToString("yyyy-MM-dd"));
                }
                if (EquipmentStaus.data == null)
                {
                    CustomWriteLog("EquipmentStaus.data属性为空", DateTime.Now.ToString("yyyy-MM-dd"));
                }
                else
                {
                    for (int i = 0; i < EquipmentStaus.data.Count; i++)
                    {
                        //设备运行 开关停机时间
                        if (EquipmentStaus.data[i].no.Contains("KB01ZD") || EquipmentStaus.data[i].no.Contains("KBCY") || EquipmentStaus.data[i].no.Contains("KBMY"))
                        {
                            string HBegDate = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
                            string HEndDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:00");
 
                            if (DateTime.Parse(HEndDate).AddMinutes(1).ToString("yyyy-MM-dd") != DateTime.Parse(HEndDate).ToString("yyyy-MM-dd"))
                            {
                                HEndDate = DateTime.Parse(HEndDate).AddMinutes(1).ToString("yyyy-MM-dd HH:mm:00");
                            }
 
                            JsonResult_KB HEqDate = await FindDeviceStatusTimeByNo(Url, token, EquipmentStaus.data[i].no, HBegDate, HEndDate);
 
                            // 记录开机时长
                            CustomWriteLog("设备开机时长: 开机时长" + ((float)(HEqDate.data.onlineTime / 60 / 60)).ToString("0.00") + "  " + EquipmentStaus.data[i].no + "",
                                            DateTime.Now.ToString("yyyy-MM-dd"));
 
                            // 记录关机时长
                            CustomWriteLog("设备关机时长: 关机时长" + ((float)(HEqDate.data.offlineTime / 60 / 60)).ToString("0.00") + "  " + EquipmentStaus.data[i].no + "",
                                            DateTime.Now.ToString("yyyy-MM-dd"));
 
                            // 记录停机时长
                            CustomWriteLog("设备停机时长: 停机时长" + ((float)(HEqDate.data.standbyTime / 60 / 60)).ToString("0.00") + "  " + EquipmentStaus.data[i].no + "",
                                            DateTime.Now.ToString("yyyy-MM-dd"));
 
                            // 记录运行时长
                            CustomWriteLog("设备运行时长: 运行时长" + ((float)(HEqDate.data.runTime / 60 / 60)).ToString("0.00") + "  " + EquipmentStaus.data[i].no + "",
                                            DateTime.Now.ToString("yyyy-MM-dd"));
 
                            JsonData_KB += "{\"HDate\":\"" + HEndDate + "\",\"HTechParamName\":\"开机时长\",\"HResult\":\"" + ((float)(HEqDate.data.onlineTime / 60 / 60)).ToString("0.00") + "\",\"HCount\":1,\"HSourceCode\":\"" + EquipmentStaus.data[i].no + "\"},";
                            JsonData_KB += "{\"HDate\":\"" + HEndDate + "\",\"HTechParamName\":\"关机时长\",\"HResult\":\"" + ((float)(HEqDate.data.offlineTime / 60 / 60)).ToString("0.00") + "\",\"HCount\":1,\"HSourceCode\":\"" + EquipmentStaus.data[i].no + "\"},";
                            JsonData_KB += "{\"HDate\":\"" + HEndDate + "\",\"HTechParamName\":\"停机时长\",\"HResult\":\"" + ((float)(HEqDate.data.standbyTime / 60 / 60)).ToString("0.00") + "\",\"HCount\":1,\"HSourceCode\":\"" + EquipmentStaus.data[i].no + "\"},";
                            JsonData_KB += "{\"HDate\":\"" + HEndDate + "\",\"HTechParamName\":\"运行时长\",\"HResult\":\"" + ((float)(HEqDate.data.runTime / 60 / 60)).ToString("0.00") + "\",\"HCount\":1,\"HSourceCode\":\"" + EquipmentStaus.data[i].no + "\"},";
                        }
 
 
                        string staus = "";
                        switch (EquipmentStaus.data[i].status)
                        {
                            //-1:未知,1:离线,2:待机,3:正常运行,4:告警
                            case "-1":
                                staus = "未知";
                                break;
                            case "1":
                                staus = "离线";
                                break;
                            case "2":
                                staus = "待机";
                                break;
                            case "3":
                                staus = "正常运行";
                                break;
                            case "4":
                                staus = "告警";
                                break;
                        }
                        if (jsonEquipment == null || jsonEquipment.data == null)
                        {
                            // 当 jsonEquipment 或 jsonEquipment.data 为 null 时,统一走这里
                            JsonData_KB += "{\"HDate\":\"" + time + "\",\"HTechParamName\":\"开关机状态\",\"HResult\":\"" + staus + "\",\"HCount\":0,\"HSourceCode\":\"" + EquipmentStaus.data[i].no + "\"},";
                            CustomWriteLog("2.1", DateTime.Now.ToString("yyyy-MM-dd"));
 
                        }
                        else if (jsonEquipment.data.Count > 0)
                        {
                            JsonData_KB += "{\"HDate\":\"" + time + "\",\"HTechParamName\":\"开关机状态\",\"HResult\":\"" + staus + "\",\"HCount\":1,\"HSourceCode\":\"" + EquipmentStaus.data[i].no + "\"},";
                            CustomWriteLog("2.2", DateTime.Now.ToString("yyyy-MM-dd"));
 
                        }
                        else
                        {
                            JsonData_KB += "{\"HDate\":\"" + time + "\",\"HTechParamName\":\"开关机状态\",\"HResult\":\"" + staus + "\",\"HCount\":0,\"HSourceCode\":\"" + EquipmentStaus.data[i].no + "\"},";
                            CustomWriteLog("2.3", DateTime.Now.ToString("yyyy-MM-dd"));
 
                        }
 
                    }
                }
 
                CustomWriteLog("03", DateTime.Now.ToString("yyyy-MM-dd"));
 
                //查询当前开工的设备 获取对应的物料信息
                DataSet datable = oCN.RunProcReturn(@"select m.HNumber,eq.HEquipFileNo from Sc_ICMOBillStatus_Tmp a
                                            inner join Gy_EquipFileBillMain eq on a.HSourceID = eq.HSourceID
                                            inner join Gy_Material m on a.HMaterID = m.HItemID
                                            where a.HICMOStatus = '1' ", "Sc_ICMOBillStatus_Tmp");
 
                if (datable.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < datable.Tables[0].Rows.Count; i++)
                    {
                        string HSourceCode = datable.Tables[0].Rows[i]["HEquipFileNo"].ToString();
                        string HNumber = datable.Tables[0].Rows[i]["HNumber"].ToString();
 
                        JsonData_KB += "{\"HDate\":\"" + DateTime.Now.ToString() + "\",\"HTechParamName\":\"物料代码\",\"HResult\":\"" + HNumber + "\",\"HCount\":1,\"HSourceCode\":\"" + HSourceCode + "\"},";
                    }
                }
 
                CustomWriteLog("04", DateTime.Now.ToString("yyyy-MM-dd"));
 
                JsonData_KB = JsonData_KB.Substring(0, JsonData_KB.Length - 1);
                JsonData_KB += "]}";
 
                CustomWriteLog("结束所有", DateTime.Now.ToString("yyyy-MM-dd"));
 
                //保存数据
                DataSave(JsonData_KB);
                if (TimeDate != "")
                {
                    TimeDate = time;
                }
            }
        }
 
        //数据保存
        public void DataSave(string JsonData_KB)
        {
            JsonEquipmentData_KB data = JsonConvert.DeserializeObject<JsonEquipmentData_KB>(JsonData_KB);
 
            for (int i = 0; i < data.data.Count; i++)
            {
                oCN.RunProc(@"insert into Sb_EquipMentCollectionTechParam_Temp(HDate,HSourceCode,HTechParamID,HTechParamName,HCount
                ,HCreateTime,HResult,HProcNumber,HFlag)
                values(getdate(),'" + data.data[i].HSourceCode + "',0,'" + data.data[i].HTechParamName + "'," + data.data[i].HCount
                + ",'" + data.data[i].HDate + "','" + data.data[i].HResult + "','" + data.data[i].HProcNumber + "',0)");
                
            }          
        }
 
        //定时生成产量汇报单
        private async void Time_CLHB_Tick(object sender, EventArgs e)
        {
 
            string Url = DBHelper.GetConfigKey(AppDomain.CurrentDomain.BaseDirectory + "Config/SQLAPI.config", "sUrl");
            string urls = Url + EquipmentType_KB.One;
            //准备要发送的表单数据
            var formData = new FormUrlEncodedContent(new[]
           {
                     new KeyValuePair<string, string>("userName", "admin"),
                     new KeyValuePair<string, string>("password", "Youngsunabc123..")
                      //添加更多键值对,根据您的需要
               });
            JsonResult_KB jsonResult = await getUrl(urls, formData);
            string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string token = jsonResult.data.token;
 
            //获取所有的设备数据
            JsonEquipmentData_KB jsonEquipment = await FindDeviceList(Url, token);
 
            if (jsonEquipment.code != "0")
            {
                MessageBox.Show("设备列表报错:" + jsonEquipment.message);
            }
            else
            {
                string nos = "";
                //获取去设备编码
                for (int i = 0; i < jsonEquipment.data.Count; i++)
                {
                    nos += "''" + jsonEquipment.data[i].no + "'',";
                }
                nos = nos.Substring(0, nos.Length - 1);
 
                CustomWriteLog("产量汇报单,设备编码:'" + nos + "'", DateTime.Now.ToString("yyyy-MM-dd"));
 
                //查询开工的设备信息 以及 查询当天设备对应的开工时间 和完工时间
                DataSet ds = oCN.RunProcReturn("exec h_p_Sc_TimeICMOReporList '" + nos + "'", "h_p_Sc_TimeICMOReporList");
 
                if (ds.Tables[0].Rows.Count > 0)
                {
                    //根据当天只开工没有完工对应的产量数据 生成产量汇报单
                    DataTable dt = ds.Tables[0];
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        nos = dt.Rows[i]["设备编码"].ToString();
                        string HICMInterID = dt.Rows[i]["HInterID"].ToString();
                        string HBegDate = DateTime.Parse(dt.Rows[i]["日期"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
                        string HEndDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        jsonEquipment = await FindProdByNosAndTime(Url, token, nos, HBegDate, HEndDate);
                        if (decimal.Parse(jsonEquipment.data[0].prod) > 0)
                        {
                            //生成产量汇报单
                            oCN.RunProc("exec h_p_Sc_AddTimeICMORepor " + HICMInterID + "," + jsonEquipment.data[0].prod + ",'" + HEndDate + "'");
                            CustomWriteLog("生成产量汇报单1:'exec h_p_Sc_AddTimeICMORepor " + HICMInterID + "," + jsonEquipment.data[0].prod + ",'" + HEndDate + "''", DateTime.Now.ToString("yyyy-MM-dd"));
                        }
                    }
                }
                if (ds.Tables[1].Rows.Count > 0)
                {
                    //根据当天开工并且完工对应的产量数据 生成产量汇报单
                     DataTable dt = ds.Tables[1];
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        nos = dt.Rows[i]["设备编码"].ToString();
                        string HICMInterID = dt.Rows[i]["HInterID"].ToString();
                        string HBegDate = DateTime.Parse(dt.Rows[i]["开始日期"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
                        string HEndDate = DateTime.Parse(dt.Rows[i]["结束日期"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
                        jsonEquipment = await FindProdByNosAndTime(Url, token, nos, HBegDate, HEndDate);
                        if (decimal.Parse(jsonEquipment.data[0].prod) > 0)
                        {
                            //生成产量汇报单
                            oCN.RunProc("exec h_p_Sc_AddTimeICMORepor " + HICMInterID + "," + jsonEquipment.data[0].prod + ",'" + HEndDate + "'");
                            CustomWriteLog("生成产量汇报单2:'exec h_p_Sc_AddTimeICMORepor " + HICMInterID + "," + jsonEquipment.data[0].prod + ",'" + HEndDate + "''", DateTime.Now.ToString("yyyy-MM-dd"));
                        }
                    }
                }
            }
 
        }
 
        private void EquipmentCollectionForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("确定要关闭吗?", "确认", MessageBoxButtons.YesNo) == DialogResult.No)
            {
                e.Cancel = true;
            }
        }
 
        #region  接口
 
        //获取登录的token
        public async Task<JsonResult_KB> getUrl(string url, FormUrlEncodedContent formData)
        {
            // 创建 HttpClient 实例
            using (var client = new HttpClient())
            {
                // 发送 POST 请求,并等待响应
                HttpResponseMessage response = await client.PostAsync(url, formData);
 
                Dictionary<object, object> dic = new Dictionary<object, object>();
                JsonResult_KB jsonResult = new JsonResult_KB();
                // 检查响应是否成功
                if (response.IsSuccessStatusCode)
                {
                    // 处理成功响应的逻辑
                    string responseBody = await response.Content.ReadAsStringAsync();
                    jsonResult = JsonConvert.DeserializeObject<JsonResult_KB>(responseBody);
                }
                else
                {
                    // 处理失败响应的逻辑
                    MessageBox.Show("请求失败,状态码:" + response.StatusCode);
                }
                return jsonResult;
            }
        }
 
        // 获取设备列表
        public async Task<JsonEquipmentData_KB> EquipmentList(string url, StringContent postData, string Type)
        {
 
            // 创建 HttpClient 实例
            using (HttpClient client = new HttpClient())
            {
                JsonEquipmentData_KB jsonResult = new JsonEquipmentData_KB();
                try
                {
                    HttpResponseMessage response;
                    if (Type == "POST")
                    {  // 发起 POST 请求
                        response = await client.PostAsync(url, postData);
                    }
                    else
                    {
                        // 发起 get 请求
                        response = await client.GetAsync(url);
                    }
 
 
                    // 确保请求成功
                    if (response.IsSuccessStatusCode)
                    {
                        // 读取响应内容
                        string responseBody = await response.Content.ReadAsStringAsync();
                        jsonResult = JsonConvert.DeserializeObject<JsonEquipmentData_KB>(responseBody);
                    }
                    else
                    {
                        MessageBox.Show($"请求失败:{response.StatusCode} - {url} - 当前时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss}");
                    }
 
                }
                catch (Exception ex)
                {
                    MessageBox.Show("请求报错:" + ex.Message);
                }
                return jsonResult;
            }
        }
 
        public async Task<JsonResult_KB> EquipResultList(string url, StringContent postData, string Type)
        {
 
            // 创建 HttpClient 实例
            using (HttpClient client = new HttpClient())
            {
                JsonResult_KB jsonResult = new JsonResult_KB();
                try
                {
                    HttpResponseMessage response;
                    if (Type == "POST")
                    {  // 发起 POST 请求
                        response = await client.PostAsync(url, postData);
                    }
                    else
                    {
                        // 发起 get 请求
                        response = await client.GetAsync(url);
                    }
 
 
                    // 确保请求成功
                    if (response.IsSuccessStatusCode)
                    {
                        // 读取响应内容
                        string responseBody = await response.Content.ReadAsStringAsync();
                        jsonResult = JsonConvert.DeserializeObject<JsonResult_KB>(responseBody);
                    }
                    else
                    {
                        MessageBox.Show($"请求失败,: {response.StatusCode}");
                    }
 
                }
                catch (Exception ex)
                {
                    MessageBox.Show("请求报错:" + ex.Message);
                }
                return jsonResult;
            }
        }
 
 
        //获取tockID
        public async Task<JsonResult_KB> FindAccessToken(string url)
        {
            string urls = url + EquipmentType_KB.One;
            // 准备要发送的表单数据
            var formData = new FormUrlEncodedContent(new[]
            {
                    new KeyValuePair<string, string>("userName", "admin"),
                    new KeyValuePair<string, string>("password", "admin")
                    // 添加更多键值对,根据您的需要
                });
            JsonResult_KB jsonResult = await getUrl(urls, formData);
            return jsonResult;
        }
 
        //获取设备列表
        public async Task<JsonEquipmentData_KB> FindDeviceList(string url, string token)
        {
            //设备列表接口
            string urls = url + EquipmentType_KB.Two;
            CustomWriteLog("设备列表接口:'" + urls + "'", DateTime.Now.ToString("yyyy-MM-dd"));
            // 准备要发送的表单数据
            var postData = new StringContent("{\"token\":\"" + token + "\"}", System.Text.Encoding.UTF8, "application/json");
            JsonEquipmentData_KB jsonResult = await EquipmentList(urls, postData, "POST");
            return jsonResult;
        }
 
        //获取良品、不良品明细、工艺参数
        public async Task<JsonEquipmentData_KB> FindAllDevicePropsDetailByTimeRange(string url, string token, string nos, string HBegin, string HEnd)
        {
            string basePropIds = DBHelper.GetConfigKey(AppDomain.CurrentDomain.BaseDirectory + "Config/SQLAPI.config", "basePropIds");
            basePropIds = "[" + basePropIds + "]";
            nos = nos.Replace(",", "\",\"");
            //20250723  发现有的客户数采没有采集工艺参数 如果传入对应的 设备编号 会导致 请求失败  传入参数ID 也可以获取到对应的设备  这样不会 请求失败
            //string stringJson = "{\"token\":\"" + token + "\",\"deviceNos\":[\"" + nos + "\"],\"startTime\":\"" + HBegin + "\",\"endTime\":\"" + HEnd + "\",\"basePropIds\":" + basePropIds + "}";
            string stringJson = "{\"token\":\"" + token + "\",\"startTime\":\"" + HBegin + "\",\"endTime\":\"" + HEnd + "\",\"basePropIds\":" + basePropIds + "}";
            //设备列表接口
            string urls = url + EquipmentType_KB.Nine;
            CustomWriteLog("工艺参数接口:'" + urls + "' 参数值: '" + stringJson + "'", DateTime.Now.ToString("yyyy-MM-dd"));
            // 准备要发送的表单数据
            var postData = new StringContent(stringJson, System.Text.Encoding.UTF8, "application/json");
            JsonEquipmentData_KB jsonEquipment = await EquipmentList(urls, postData, "POST");
            return jsonEquipment;
        }
 
        //获取不良数,合数数,可疑数 总数
        public async Task<JsonEquipmentData_KB> FindDevicePropCalc(string url, string token, string nos, string HBegin, string HEnd)
        {
            string stringJson = "{\"token\":\"" + token + "\",\"deviceNo\":\"" + nos + "\",\"propIds\":[606,173,469,470],\"beginTime\":\"" + HBegin + "\",\"endTime\":\"" + HEnd + "\"}";
            var postData = new StringContent(stringJson, System.Text.Encoding.UTF8, "application/json");
            string urls = url + EquipmentType_KB.Seven;
            CustomWriteLog("获取不良数,合数数,可疑数 总数:'" + urls + "' 参数值: '" + stringJson + "'", DateTime.Now.ToString("yyyy-MM-dd"));
            JsonEquipmentData_KB jsonResult = await EquipmentList(urls, postData, "POST");
            return jsonResult;
        }
 
 
        //获取设备运行状态
        public async Task<JsonEquipmentData_KB> FindDeviceStatusByNos(string url, string token, string nos)
        {
            nos = nos.Replace(",", "\",\"");
            nos = "\"" + nos + "\"";
            string stringJson = "{\"token\":\"" + token + "\",\"nos\":[" + nos + "]}";
            var postData = new StringContent(stringJson, System.Text.Encoding.UTF8, "application/json");
            string urls = url + EquipmentType_KB.Three;
            CustomWriteLog("设备运行状态:'" + urls + "' 参数值: '" + stringJson + "'", DateTime.Now.ToString("yyyy-MM-dd"));
            JsonEquipmentData_KB jsonResult = await EquipmentList(urls, postData, "POST");
            return jsonResult;
        }
 
        //获取设备时间段产量
        public async Task<JsonEquipmentData_KB> FindProdByNosAndTime(string url, string token, string nos, string HBegin, string HEnd)
        {
            nos = nos.Replace(",", "\",\"");
            nos = "\"" + nos + "\"";
            string stringJson = "{\"token\":\"" + token + "\",\"nos\":[" + nos + "],\"startTime\":\"" + HBegin + "\",\"endTime\":\"" + HEnd + "\"}";
            var postData = new StringContent(stringJson, System.Text.Encoding.UTF8, "application/json");
            string urls = url + EquipmentType_KB.Four;
            CustomWriteLog("设备时间段产量:'" + urls + "' 参数值: '" + stringJson + "'", DateTime.Now.ToString("yyyy-MM-dd"));
            JsonEquipmentData_KB jsonResult = await EquipmentList(urls, postData, "POST");
            return jsonResult;
        }
 
        //获取设备运行时间 开机 停机 待机  关机
        public async Task<JsonResult_KB> FindDeviceStatusTimeByNo(string url, string token, string nos, string HBegin, string HEnd)
        {
            nos = nos.Replace(",", "\",\"");
            nos = "\"" + nos + "\"";
            string stringJson = "{\"token\":\"" + token + "\",\"no\":" + nos + ",\"startTime\":\"" + HBegin + "\",\"endTime\":\"" + HEnd + "\"}";
            var postData = new StringContent(stringJson, System.Text.Encoding.UTF8, "application/json");
            string urls = url + EquipmentType_KB.Five;
            // 记录开机时长
            CustomWriteLog("设备运行时间接口:'" + urls + "' 参数值: '" + stringJson + "'", DateTime.Now.ToString("yyyy-MM-dd"));
            JsonResult_KB jsonResult = await EquipResultList(urls, postData, "POST");
            return jsonResult;
        }
 
        //获取注塑机的 开机
        public async Task<JsonResult_KB> FindDeviceStatusTimeByNosAndOperationMode(string url, string token, string nos, string HBegin, string HEnd)
        {
            nos = nos.Replace(",", "\",\"");
            nos = "\"" + nos + "\"";
            string stringJson = "{\"token\":\"" + token + "\",\"no\":" + nos + ",\"startTime\":\"" + HBegin + "\",\"endTime\":\"" + HEnd + "\"}";
            var postData = new StringContent(stringJson, System.Text.Encoding.UTF8, "application/json");
            string urls = url + EquipmentType_KB.Ten;
            CustomWriteLog("注塑机的 开机接口:'" + urls + "' 参数值: '" + stringJson + "'", DateTime.Now.ToString("yyyy-MM-dd"));
            JsonResult_KB jsonResult = await EquipResultList(urls, postData, "POST");
            return jsonResult;
        }
        #endregion
 
        private static readonly object lockObj = new object();
        //写日志
        public static void CustomWriteLog(object obj, string FileName, string filePath = "Vlog", bool isAppend = true)
        {
            try
            {
                lock (lockObj)
                {
                    filePath = $@"{filePath}\{FileName}.txt";
 
                    filePath = AppDomain.CurrentDomain.BaseDirectory + filePath;
 
                    if (!System.IO.Directory.Exists(Path.GetDirectoryName(filePath)))
                    {
                        System.IO.Directory.CreateDirectory(Path.GetDirectoryName(filePath));
                    }
 
                    bool fileExists = System.IO.File.Exists(filePath);
                    //不存在 则创建该文件
                    if (!fileExists)
                    {
                        System.IO.File.Create(filePath).Close();
                    }
 
                    using (StreamWriter writer = new StreamWriter(filePath, isAppend))
                    {
                        //存在的时候才写一行
                        if (fileExists && isAppend)
                        {
                            writer.WriteLine();
                        }
 
                        var content = obj is string ? obj : JsonConvert.SerializeObject(obj);
                        writer.WriteLine($"{DateTime.Now} {content}");
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
    }
 
 
    public class JsonResult_KB
    {
        public string code { get; set; }
        public string message { get; set; }
        public string expirationTime { get; set; }
        public string token { get; set; }
        public JsonData_KB data { get; set; }
    }
 
    public class JsonEquipmentData_KB
    {
        public string code { get; set; }
        public string message { get; set; }
        public string expirationTime { get; set; }
        public string token { get; set; }
        public string deviceNo { get; set; }
        public string deviceName { get; set; }
        public string deviceStatus { get; set; }
        public List<JsonData_KB> data { get; set; }
    }
 
    public class JsonData_KB
    {
        public double onlineTime { get; set; }
        public double offlineTime { get; set; }
        public double standbyTime { get; set; }
        public double runTime { get; set; }
        public string expirationTime { get; set; }
        public string token { get; set; }
        public string deviceNo { get; set; }
        public List<propsData_KB> props { get; set; }
        public string area { get; set; }
        public string no { get; set; }
        public string name { get; set; }
        public string status { get; set; }
        public string prod { get; set; }
        public string propName { get; set; }
        public string basePropId { get; set; }
        public string value { get; set; }
        public string time { get; set; }
        public int propId { get; set; }
        public double count { get; set; }
        public double min { get; set; }
        public double max { get; set; }
        public double avg { get; set; }
        public double sum { get; set; }
        public string createTime { get; set; }
        public string happenTime { get; set; }
        public string HDate { get; set; }
        public string HTechParamName { get; set; }
        public string HResult { get; set; }
        public string HCount { get; set; }
        public string HSourceCode { get; set; }
        public string HProcNumber { get; set; }
    }
 
    public class propsData_KB
    {
        public string propName { get; set; }
        public List<JsonData_KB> datas { get; set; }
        public string basePropId { get; set; }
    }
 
    public class valueData_KB
    {
        public string beat { get; set; }
        public string type { get; set; }
    }
 
    //设备接口
    public static class EquipmentType_KB
    {
        //设备 获取令牌
        public static string One = "/api/third/findAccessToken";
        //设备列表
        public static string Two = "/api/third/findDeviceList";
        //设备状态
        public static string Three = "/api/third/findDeviceStatusByNos";
        //设备产量
        public static string Four = "/api/third/findProdByNosAndTime";
        //设备时长
        public static string Five = "/api/third/findDeviceStatusTimeByNo";
        //属性列表
        public static string Six = "/api/third/findPropertyListByNos";
        //产量,不良数,合格数,可疑数 总数
        public static string Seven = "/api/third/findDevicePropCalc";
        //一段时间内设备状态的获取
        public static string Eight = "/api/third/dayDeviceStatusTimeline";
        //良品 不良品 明细 注塑机数据
        public static string Nine = "/api/third/findAllDevicePropsDetailByTimeRange";
        //注塑机开机时长 根据 操作模式采集
        public static string Ten = "/api/third/findDeviceStatusTimeByNosAndOperationMode";
        //public static string Eleven = "Monday";
        //public static string Twelve = "Monday";
    }
 
    public class Info_KB
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }
 
}