ams
cjs
2025-05-28 6db5849413c86ac0f75ec90a6eca2889372774ad
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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
using Hanhe.iWCS.Common;
using Hanhe.iWCS.MData;
using Hanhe.iWCS.Model;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using static Hanhe.iWCS.TaizhouGEMTwoProtocol.ApiHelper;
using static Hanhe.iWCS.TaizhouGEMTwoProtocol.MESHelper;
 
namespace Hanhe.iWCS.TaizhouGEMTwoProtocol
{
    public class ERPService
    {
        /*
         * 变更优化操作:
         * 
         * 注释内容:
         *      PLCControl.SecondWeightInCache6 方法
         * 
         * **/
 
 
        static WebApiHelper api = new WebApiHelper();
 
        public const string ERPSwitch01 = "1";// ERP变更流程开关
        public static List<string> SendERPTaskType = Settings.SendERPTaskType.Split(',').ToList();//回报任务类型
        public static List<string> LoginInfo = Settings.LoginInfo.Split(',').ToList();// ERP登录接口传输信息
 
        /// <summary>
        /// ERP物料下发接口
        /// </summary>
        /// <param name="itemTable"></param>
        /// <returns></returns>
        public static SimpleResult Item(ERPItemTable itemTable)
        {
            SimpleResult result = new SimpleResult { success = false};
 
            // 查询中间表是否存在数据,如果存在,则进行更新;如果不存在,则获取当前【物料序号】,并进行累加插入数据
            var query = Query.EQ("item_code", itemTable.item_code);
            var erpItemInfo = MongoDBSingleton.Instance.FindOne<ERPItemTable>(query, "ERPItemTable");
            if (erpItemInfo != null)
            {
                var update = Update.Set("item_name", itemTable.item_name).Set("item_spec", itemTable.item_spec)
                    .Set("item_uom", itemTable.item_uom).Set("dateTime", DateTime.Now);
                MongoDBSingleton.Instance.Update<ERPItemTable>(query, update, "ERPItemTable", MongoDB.Driver.UpdateFlags.None);
                result.success = true;
            }
            else
            {
                int itemNo = 1;
                // 获取最大序号的数据
                var maxErpItemInfoList = MongoDBSingleton.Instance.FindAll<ERPItemTable>("ERPItemTable");
                if (maxErpItemInfoList.Count > 0)
                {
                    var maxErpItemInfo = maxErpItemInfoList.OrderByDescending(it => it.item_no).First();
                    if (maxErpItemInfo != null) itemNo = maxErpItemInfo.item_no + 1;
                }
                MongoDBSingleton.Instance.Insert<ERPItemTable>(new ERPItemTable
                {
                    item_no = itemNo,
                    item_code = itemTable.item_code,
                    item_name = itemTable.item_name,
                    item_spec = itemTable.item_spec,
                    item_uom = itemTable.item_uom,
                    dateTime = DateTime.Now
                }, "ERPItemTable");
                result.success = true;
            }
            return result;
        }
 
        /// <summary>
        /// ERP员工信息下发接口
        /// </summary>
        /// <param name="itemTable"></param>
        /// <returns></returns>
        public static SimpleResult Employee(ERPEmployeeTable itemTable)
        {
            SimpleResult result = new SimpleResult { success = false };
 
            // 查询中间表是否存在数据,如果存在,则进行更新;如果不存在,则获取当前【物料序号】,并进行累加插入数据
            var query = Query.EQ("employee_id", itemTable.employee_id);
            var erpItemInfo = MongoDBSingleton.Instance.FindOne<ERPEmployeeTable>(query, "ERPEmployeeTable");
            if (erpItemInfo != null)
            {
                var update = Update.Set("employee_name", itemTable.employee_name).Set("dateTime", DateTime.Now);
                MongoDBSingleton.Instance.Update<ERPEmployeeTable>(query, update, "ERPEmployeeTable", MongoDB.Driver.UpdateFlags.None);
                result.success = true;
            }
            else
            {
                int itemNo = 1;
                // 获取最大序号的数据
                var maxErpItemInfoList = MongoDBSingleton.Instance.FindAll<ERPEmployeeTable>("ERPEmployeeTable");
                if (maxErpItemInfoList.Count > 0)
                {
                    var maxErpItemInfo = maxErpItemInfoList.OrderByDescending(it => it.item_no).First();
                    if (maxErpItemInfo != null) itemNo = maxErpItemInfo.item_no + 1;
                }
                MongoDBSingleton.Instance.Insert<ERPEmployeeTable>(new ERPEmployeeTable
                {
                    item_no = itemNo,
                    employee_id = itemTable.employee_id,
                    employee_name = itemTable.employee_name,
                    dateTime = DateTime.Now
                }, "ERPEmployeeTable");
                result.success = true;
            }
            return result;
        }
 
        /// <summary>
        /// ERP物料中间表
        /// </summary>
        public class ERPItemTable
        {
            public ObjectId _id { get; set; }
            /// <summary>
            /// 物料序号(唯一)
            /// </summary>
            public int item_no { get; set; }
            /// <summary>
            /// 物料编码(唯一)
            /// </summary>
            public string item_code { get; set; }
            /// <summary>
            /// 物料名称
            /// </summary>
            public string item_name { get; set; }
            /// <summary>
            /// 规格型号
            /// </summary>
            public string item_spec { get; set; }
            /// <summary>
            /// 单位
            /// </summary>
            public string item_uom { get; set; }
            /// <summary>
            /// 操作时间
            /// </summary>
            public DateTime dateTime { get; set; }
        }
 
        /// <summary>
        /// ERP员工信息中间表
        /// </summary>
        public class ERPEmployeeTable
        {
            public ObjectId _id { get; set; }
            /// <summary>
            /// 物料序号(唯一)
            /// </summary>
            public int item_no { get; set; }
            /// <summary>
            /// 物料编码
            /// </summary>
            public string item_code { get; set; }
            /// <summary>
            /// 物料名称
            /// </summary>
            public string item_name { get; set; }
            /// <summary>
            /// 员工工号
            /// </summary>
            public string employee_id { get; set; }
            /// <summary>
            /// 员工名称
            /// </summary>
            public string employee_name { get; set; }
            /// <summary>
            /// 操作时间
            /// </summary>
            public DateTime dateTime { get; set; }
        }
 
        public static void SendERPTaskInfo(TN_I_TASK_MST mst)
        {
            var sendERPTaskInfo = MongoDBSingleton.Instance.FindOne<SendErpTaskInfoTable>(Query.EQ("taskNo", mst.CN_S_TASK_NO), "SendErpTaskInfoTable");
            if (sendERPTaskInfo == null)
            {
                //string timeStamp = "";
                //if (mst.transportInfo.Count > 0) timeStamp = mst.transportInfo.First().itemPCode;
                MongoDBSingleton.Instance.Insert<SendErpTaskInfoTable>(new SendErpTaskInfoTable
                {
                    taskNo = mst.CN_S_TASK_NO,
                    timeStamp = mst.Ext2,// mst.CN_S_BATCH_NO
                    dateTime = DateTime.Now.AddHours(8)
                }, "SendErpTaskInfoTable");
            }
            else CMMLog.Error($"SendERPTaskInfo Error:当前任务号数据已存在,不允许插入 SendErpTaskInfoTable 记录表。任务号:{mst.CN_S_TASK_NO}");
        }
 
        public class SendErpTaskInfoTable
        {
            public ObjectId _id { get; set; }
            /// <summary>
            /// 任务号(唯一)
            /// </summary>
            public string taskNo { get; set; }
            /// <summary>
            /// 时间戳-对应任务数据 CN_S_BATCH_NO 字段值
            /// </summary>
            public string timeStamp { get; set; }
            public DateTime dateTime { get; set; }
        }
 
        /// <summary>
        /// 入库任务完成回报ERP信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static void SendERPTaskCompleteFunc()
        {
            var sendERPTaskInfoList = MongoDBSingleton.Instance.FindAll<SendErpTaskInfoTable>();
            if (sendERPTaskInfoList.Count > 0)
            {
                // 先根据任务批次号字段获取时间戳中间表-TimeCuoInfoCom 数据,并进行后续调用,处理成功删除时间戳中间表-TimeCuoInfoCom 数据
                sendERPTaskInfoList.ForEach(a =>
                {
                    bool result = ERPApiFuncTwo(a.timeStamp);
                    if (result)
                    {
                        MongoDBSingleton.Instance.Remove<SendErpTaskInfoTable>(Query.EQ("_id", a._id), "SendErpTaskInfoTable", RemoveFlags.None);
                        MongoDBSingleton.Instance.Remove<TimeCuoInfoCom>(Query.EQ("timeStamp", int.Parse(a.timeStamp)), "TimeCuoInfoCom", RemoveFlags.None);
                    }
                });
            }
        }
 
        /// <summary>
        /// ERP交互方法:打包下线任务创建前 调用 批号主档 接口
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static bool ERPApiFunc(string timeStamp)
        {
            bool result = false;
            try
            {
                var model = MongoDBSingleton.Instance.FindOne<TimeCuoInfoCom>(Query.EQ("timeStamp", int.Parse(timeStamp)), "TimeCuoInfoCom");
                if (model != null)
                {
                    string userToken = ERPGetLogin();
                    if (!string.IsNullOrEmpty(userToken))
                    {
                        // 打包下线任务创建前 调用 批号主档 接口
                        result = ERPBatchInfo(userToken, model);
                    }
                    else CMMLog.Error($"ERPApiFunc Error:未获取到userToken.");
                }
                else CMMLog.Error($"ERPApiFunc Error:当前任务未获取到对应的时间戳数据。时间戳:{timeStamp},时间戳表:TimeCuoInfoCom");
            }
            catch(Exception ex)
            {
                CMMLog.Error($"ERPApiFun Error:{ex.Message}");
            }
            
 
            
            return result;
        }
 
        /// <summary>
        /// ERP交互方法:任务完成调用 条码主档 接口
        /// </summary>
        /// <param name="timeStamp"></param>
        /// <returns></returns>
        public static bool ERPApiFuncTwo(string timeStamp)
        {
            bool result = false;
            try
            {
                var model = MongoDBSingleton.Instance.FindOne<TimeCuoInfoCom>(Query.EQ("timeStamp", int.Parse(timeStamp)), "TimeCuoInfoCom");
                if (model != null)
                {
                    string userToken = ERPGetLogin();
                    if (!string.IsNullOrEmpty(userToken))
                    {
                        // 任务完成调用 条码主档 接口
                        result = ERPBarCodeInfo(userToken, model);
                    }
                    else CMMLog.Error($"ERPApiFuncTwo Error:未获取到userToken.");
                }
                else CMMLog.Error($"ERPApiFuncTwo Error:当前任务未获取到对应的时间戳数据。时间戳:{timeStamp},时间戳表:TimeCuoInfoCom");
            }
            catch (Exception ex)
            {
                CMMLog.Error($"ERPApiFuncTwo Error:{ex.Message}");
            }
 
            return result;
        }
 
        public static string CooKie = "";
        /// <summary>
        /// ERP登录接口
        /// </summary>
        public static string ERPGetLogin()
        {
            // 获取配置文件数据
            string userToken = "";
            try
            {
                string res = JsonConvert.SerializeObject(new
                {
                    parameters = new ArrayList { LoginInfo[0], LoginInfo[1], LoginInfo[2], int.Parse(LoginInfo[3]) }
                });
                string feedback = "";
                string url = Settings.GetThirdUrlList().Where(a => a.UrlNo == "1" && a.enable == 1).FirstOrDefault().Url;
                CMMLog.Info($"ERPGetLogin Res:{res},url:{url}");
                feedback = api.WebPost(url, res,"","GetCooKie");
                CMMLog.Info($"ERPGetLogin Req:{feedback}");
                if (!string.IsNullOrEmpty(feedback))
                {
                    var response = JsonConvert.DeserializeObject<ERPGetLoginResModel>(feedback);
                    if (response.IsSuccessByAPI && !string.IsNullOrEmpty(CooKie)) userToken = CooKie;
                    else CMMLog.Info($"ERPGetLogin:调用接口失败,获取Cookie失败。");
                }
            }
            catch (Exception ex)
            {
                CMMLog.Error($"WMSPost WmsInTask Error:{ex.Message}");
            }
            CMMLog.Info($"ERPGetLogin userToken:{userToken}");
            return userToken;
        }
        public class ERPGetLoginResModel
        {
            public string Message { get; set; }
            public string MessageCode { get; set; }
            public int LoginResultType { get; set; }
            public ERPGetLoginResContextModel Context { get; set; }
            public class ERPGetLoginResContextModel
            {
                public string UserToken { get; set; }
            }
 
            /// <summary>
            /// 接口调用状态 成功-true 失败-false
            /// </summary>
            public bool IsSuccessByAPI { get; set; }
        }
 
        /// <summary>
        /// 发送ERP批号主档数据
        /// </summary>
        /// <returns></returns>
        public static bool ERPBatchInfo(string userToken, TimeCuoInfoCom model)
        {
            bool result = false;
 
            try
            {
                ERPBatchInfoModel sendInfo = new ERPBatchInfoModel();
                sendInfo.Model.FCreateOrgId.FNumber = model.createOrganization;
                sendInfo.Model.FMaterialID.FNumber = model.materialCode;
                sendInfo.Model.FNumber = model.batchNumber;
                sendInfo.Model.FProduceDeptID.FNumber = model.workshopCode;
                sendInfo.Model.FInStockDate = model.BusinessDate;
 
                string res = JsonConvert.SerializeObject(new
                {
                    parameters = new ArrayList { "BD_BatchMainFile", JsonConvert.SerializeObject(sendInfo) }
                });
                string feedback = "";
                string url = Settings.GetThirdUrlList().Where(a => a.UrlNo == "3" && a.enable == 1).FirstOrDefault().Url;
                CMMLog.Info($"ERPBatchInfo Res:{res},Cookie:{userToken},url:{url}");
                feedback = api.WebPost(url, res, userToken);
                CMMLog.Info($"ERPBatchInfo Req:{feedback}");
                if (!string.IsNullOrEmpty(feedback))
                {
                    var response = JsonConvert.DeserializeObject<ERPResModel>(feedback);
                    result = response.Result.ResponseStatus.IsSuccess;
                }
            }
            catch (Exception ex)
            {
                CMMLog.Error($"ERPBatchInfo WmsInTask Error:{ex.Message}");
            }
 
 
            return result;
        }
        public class ERPBatchInfoModel
        {
            public string Creator { get; set; } = "";
            public Array NeedUpDateFields { get; set; } = new Array[0];
            public Array NeedReturnFields { get; set; } = new Array[0];
            public string IsDeleteEntry { get; set; } = "true";
            public string SubSystemId { get; set; } = "";
            public string IsVerifyBaseDataField { get; set; } = "false";
            public string IsEntryBatchFill { get; set; } = "true";
            public string ValidateFlag { get; set; } = "true";
            public string NumberSearch { get; set; } = "true";
            public string InterationFlags { get; set; } = "";
            public string IsAutoSubmitAndAudit { get; set; } = "false";
            public ModelModel Model { get; set; } = new ModelModel();
            public class ModelModel
            {
                public int FLOTID { get; set; } = 0;
 
                public FCreateOrgIdModel FCreateOrgId { get; set; } = new FCreateOrgIdModel();
                public class FCreateOrgIdModel
                {
                    /// <summary>
                        /// 创建组织
                        /// </summary>
                    public string FNumber { get; set; }
                }
                public FMaterialIDModel FMaterialID { get; set; } = new FMaterialIDModel();
                public class FMaterialIDModel
                {
                    /// <summary>
                        /// 物料编码
                        /// </summary>
                    public string FNumber { get; set; }
                }
                /// <summary>
                /// 批号
                /// </summary>
                public string FNumber { get; set; }
                public FProduceDeptIDModel FProduceDeptID { get; set; } = new FProduceDeptIDModel();
                public class FProduceDeptIDModel
                {
                    /// <summary>
                        /// 车间编码
                        /// </summary>
                    public string FNumber { get; set; }
                }
                /// <summary>
                    /// 业务日期
                    /// </summary>
                public string FInStockDate { get; set; }
            }
        }
 
        /// <summary>
        /// 发送ERP条码主档数据
        /// </summary>
        /// <returns></returns>
        public static bool ERPBarCodeInfo(string userToken, TimeCuoInfoCom model)
        {
            bool result = false;
 
            try
            {
                ERPBarCodeInfoModel sendInfo = new ERPBarCodeInfoModel();
 
                sendInfo.Model.FBarCode = model.barcode;
                sendInfo.Model.FBarCodeRule.FNumber = model.codeRules;
                sendInfo.Model.FMaterialID.FNumber = model.materialCode;
                sendInfo.Model.F_JY_CZZ.FStaffNumber = model.employeeId.ToString();
                sendInfo.Model.FCreateOrgId.FNumber = model.createOrganization;
                sendInfo.Model.FLot.FNumber = model.batchNumber;
                sendInfo.Model.FUnitId.FNumber = model.measurementUnit;
                sendInfo.Model.FQty = model.count;
                sendInfo.Model.FStockId.FNumber = model.WarehouseCode;
                sendInfo.Model.FDeptId.FNumber = model.workshopCode;
                sendInfo.Model.FBillDate = model.BusinessDate;
 
                string res = JsonConvert.SerializeObject(new
                {
                    parameters = new ArrayList { "BD_BarCodeMainFile", JsonConvert.SerializeObject(sendInfo) }
                });
                string feedback = "";
                string url = Settings.GetThirdUrlList().Where(a => a.UrlNo == "2" && a.enable == 1).FirstOrDefault().Url;
                CMMLog.Info($"ERPBarCodeInfo Res:{res},Cookie:{userToken},url:{url}");
                feedback = api.WebPost(url, res, userToken);
                CMMLog.Info($"ERPBarCodeInfo Req:{feedback}");
                if (!string.IsNullOrEmpty(feedback))
                {
                    var response = JsonConvert.DeserializeObject<ERPResModel>(feedback);
                    result = response.Result.ResponseStatus.IsSuccess;
                }
            }
            catch (Exception ex)
            {
                CMMLog.Error($"ERPBarCodeInfo Error:{ex.Message}");
            }
 
 
            return result;
        }
        public class ERPBarCodeInfoModel
        {
            public string Creator { get; set; } = "";
            public Array NeedUpDateFields { get; set; } = new Array[0];
            public Array NeedReturnFields { get; set; } = new Array[0];
            public string IsDeleteEntry { get; set; } = "true";
            public string SubSystemId { get; set; } = "";
            public string IsVerifyBaseDataField { get; set; } = "false";
            public string IsEntryBatchFill { get; set; } = "true";
            public string ValidateFlag { get; set; } = "true";
            public string NumberSearch { get; set; } = "true";
            public string InterationFlags { get; set; } = "";
            public string IsAutoSubmitAndAudit { get; set; } = "false";
            public ModelModel Model { get; set; } = new ModelModel();
            public class ModelModel
            {
                public int FID { get; set; } = 0;
                /// <summary>
                    /// 条形码
                    /// </summary>
                public string FBarCode { get; set; }
                public FBarCodeRuleModel FBarCodeRule { get; set; } = new FBarCodeRuleModel();
                public class FBarCodeRuleModel
                {
                    /// <summary>
                    /// 条码规则
                    /// </summary>
                    public string FNumber { get; set; }
                }
                public FMaterialIDModel FMaterialID { get; set; } = new FMaterialIDModel();
                public class FMaterialIDModel
                {
                    /// <summary>
                        /// 物料编码
                        /// </summary>
                    public string FNumber { get; set; }
                }
                public F_JY_CZZModel F_JY_CZZ { get; set; } = new F_JY_CZZModel();
                public class F_JY_CZZModel
                {
                    /// <summary>
                    /// 员工编号  原先:FNumber  目前:FStaffNumber
                    /// </summary>
                    public string FStaffNumber { get; set; }
                }
                public FCreateOrgIdModel FCreateOrgId { get; set; } = new FCreateOrgIdModel();
                public class FCreateOrgIdModel
                {
                    /// <summary>
                        /// 创建组织
                        /// </summary>
                    public string FNumber { get; set; }
                }
                public FLotModel FLot { get; set; } = new FLotModel();
                public class FLotModel
                {
                    /// <summary>
                    /// 批号
                    /// </summary>
                    public string FNumber { get; set; }
                }
                public FUnitIdModel FUnitId { get; set; } = new FUnitIdModel();
                public class FUnitIdModel
                {
                    /// <summary>
                    /// 计量单位
                    /// </summary>
                    public string FNumber { get; set; }
                }
                /// <summary>
                /// 数量
                /// </summary>
                public int FQty { get; set; }
                public FStockIdModel FStockId { get; set; } = new FStockIdModel();
                public class FStockIdModel
                {
                    /// <summary>
                    /// 仓库编码
                    /// </summary>
                    public string FNumber { get; set; }
                }
                public FDeptIdModel FDeptId { get; set; } = new FDeptIdModel();
                public class FDeptIdModel
                {
                    /// <summary>
                    /// 车间编码
                    /// </summary>
                    public string FNumber { get; set; }
                }
                /// <summary>
                /// 业务日期
                /// </summary>
                public string FBillDate { get; set; }
            }
        }
 
        public class ERPResModel
        {
            public ResultModel Result { get; set; }
 
            public class ResultModel
            {
                public ResponseStatusModel ResponseStatus { get; set; }
 
                public class ResponseStatusModel
                {
                    public bool IsSuccess { get; set; }
                    public int MsgCode { get; set; }
                }
            }
        }
 
 
        /// <summary>
        /// 写入包装机物料信息
        /// </summary>
        /// <param name="plcInfo"></param>
        public static void WriteItemInfo(Settings.PlcInfo plcInfo)
        {
            CMMLog.Debug($"WriteItemInfo:Start!");
 
            try
            {
                //读取【翻页】通道数据
                var result = OITcpHelper.RegisterReadOutPut(new OITcpHelper.RegisterReadOutPutModel
                {
                    dataNum = 1,
                    addr = plcInfo.FyReadAddr,
                    host = plcInfo.ip,
                    port = plcInfo.port
                });
                CMMLog.Debug($"WriteItemInfo:读取【翻页】通道数据为:{JsonConvert.SerializeObject(result)}!");
                if (true) // result != null && result.errCode == 0
                {
                    // 示例:读出值为1 获取1~5编号的物料数据;读出值为2 获取6~10编号的物料数据 规则 result.result[0] * 5 - 4 起始编号
                    //int startItemNo = 1;
                    int startItemNo = result.result[0] * 5 - 4;
                    CMMLog.Debug($"WriteItemInfo:翻页数据为:{startItemNo}!");
                    var reLocationTask = MongoDBSingleton.Instance.Find<ERPItemTable>(Query.And(Query.In("item_no", new List<MongoDB.Bson.BsonValue>() { startItemNo, startItemNo + 1, startItemNo + 2, startItemNo + 3, startItemNo + 4 })), "ERPItemTable").ToList();
                    int reLocationTaskNum = reLocationTask != null ? reLocationTask.Count : 0;
                    CMMLog.Debug($"WriteItemInfo:查询出ERP物料表数据数量为:{reLocationTaskNum}!备注:只有数量为5才会写入数据");
                    if (reLocationTaskNum == 5)
                    {
                        int no = 0;
                        reLocationTask.ForEach(a =>
                        {
                            int writeAddr = plcInfo.FyWriteAddr + no * 100;
                            no++;
                            // 解析物料数据并写入 有效数据通道 70,共100(产品批次号-20 产品型号-10 物料编码-20 物料名称-15 计量单位-5 剩余30无用通道)
                            int[] num = new int[100];
                            // 内存地址 0~19 协议地址 1~20  批次号 人工输入,不需要程序写入
                            for (int i = 0; i <= 19; i++) num[i] = 0;
                            // 内存地址 20~29 协议地址 21~30 产品型号
                            // HandleItemInfo(a.item_spec, 20, 29, num);
                            HandleItemInfoChina(a.item_spec, 20, 29, num);
                            CMMLog.Debug($"WriteItemInfo:物料信息处理-2。处理数据:{a.item_spec},处理后数据:{JsonConvert.SerializeObject(num)}");
                            // 内存地址 30~49 协议地址 31~50 物料编码
                            HandleItemInfo(a.item_code, 30, 49, num);
                            CMMLog.Debug($"WriteItemInfo:物料信息处理-2。处理数据:{a.item_code},处理后数据:{JsonConvert.SerializeObject(num)}");
                            // 内存地址 50~64 协议地址 51~65 物料名称
                            // HandleItemInfo(a.item_name, 50, 64, num);
                            HandleItemInfoChina(a.item_name, 50, 64, num);// 中文处理
                            CMMLog.Debug($"WriteItemInfo:物料信息处理-2。处理数据:{a.item_name},处理后数据:{JsonConvert.SerializeObject(num)}");
                            // 内存地址 65~69 协议地址 66~70 计量单位
                            HandleItemInfo(a.item_uom, 65, 69, num);
                            CMMLog.Debug($"WriteItemInfo:物料信息处理-2。处理数据:{a.item_uom},处理后数据:{JsonConvert.SerializeObject(num)}");
                            // 内存地址 70~79 协议地址 71~100 空余地址
                            for (int i = 70; i <= 99; i++) num[i] = 0;
 
                            CMMLog.Debug($"WriteItemInfo:发送物料信息。序号:{a.item_no},ip:{plcInfo.ip},port:{plcInfo.port},写入起始地址:{writeAddr},写入数据:{JsonConvert.SerializeObject(num)}");
 
                            var wirteall01 = OITcpHelper.RegisterWriteOutPutMulti(new OITcpHelper.RegisterWriteOutPutModelMulti
                            {
                                addr = writeAddr,
                                host = plcInfo.ip,
                                port = plcInfo.port,
                                data = num
                            });
                            int writeResult = wirteall01 != null ? wirteall01.errCode : 1;
                            CMMLog.Debug($"WriteItemInfo:发送物料信息。序号:{a.item_no},写入结果:{writeResult}。ip:{plcInfo.ip},port:{plcInfo.port},写入起始地址:{writeAddr},写入数据:{JsonConvert.SerializeObject(num)}");
                        });
                    }
                }
                else CMMLog.Debug($"WriteItemInfo:未读取【翻页】通道数据!");
            }
            catch(Exception ex)
            {
                CMMLog.Debug($"WriteItemInfo Error:{ex.Message}");
            }
 
            CMMLog.Debug($"WriteItemInfo:End!");
        }
 
        public static void HandleItemInfo(string itemInfo,int startIndex, int endIndex , int[] num)
        {
            string data = itemInfo;// 要写入的处理后数据
            string dataHeader = "";// 数据头处理
            int dataCutCont = 0;// 数据截取开关
            if (itemInfo.Length % 2 != 0)
            {
                data = "0" + itemInfo;
                dataHeader = "" + itemInfo.Substring(0, 1);
            }
            int maxLength = startIndex - 1 + (data.Length / 2);// data.Length / 2 至少为 1
            for (int i = startIndex; i <= maxLength; i++)
            {
                num[i] = int.Parse(PLCControl.AsciiToTen(data.Substring(dataCutCont, 2)));
                dataCutCont = dataCutCont + 2;
            }
            if (!string.IsNullOrEmpty(dataHeader)) num[startIndex] = int.Parse(PLCControl.AsciiToTen(dataHeader));
            for (int i = maxLength + 1; i <= endIndex; i++) num[i] = 0;//将当前处理完数据的其他无数据的通道全部置为 0
            CMMLog.Debug($"WriteItemInfo:物料信息处理-1。处理数据:{itemInfo},处理后数据:{JsonConvert.SerializeObject(num)}");
        }
 
        public static void HandleItemInfoChina(string itemInfo, int startIndex, int endIndex, int[] num)
        {
            string data = itemInfo;// 要写入的处理后数据
            int dataCutCont = 0;// 数据截取开关
            int maxLength = startIndex - 1 + data.Length;// data.Length / 2 至少为 1
            for (int i = startIndex; i <= maxLength; i++)
            {
                num[i] = Test.ConvertToAscii(char.Parse(data.Substring(dataCutCont, 1)));
                dataCutCont = dataCutCont + 1;
            }
            for (int i = maxLength + 1; i <= endIndex; i++) num[i] = 0;//将当前处理完数据的其他无数据的通道全部置为 0
            CMMLog.Debug($"WriteItemInfo:物料信息处理-1。处理数据:{itemInfo},处理后数据:{JsonConvert.SerializeObject(num)}");
        }
 
        /// <summary>
        /// 获取员工编码
        /// </summary>
        /// <returns></returns>
        public static string GetEmployeeId(int readAddr,string ip,int port)
        {
            string employeeId = "";
            var employeeIdAction = OITcpHelper.RegisterReadOutPut(new OITcpHelper.RegisterReadOutPutModel
            {
                addr = readAddr,
                host = ip,
                port = port,
                dataNum = 2
            });
            employeeId = Convert.ToInt32(PLCControl.Completion(employeeIdAction.result[0]) + PLCControl.Completion(employeeIdAction.result[1]), 2).ToString();
 
            return employeeId;
        }
 
 
        public static string packageCont = "1";// 包装机复称UI变更功能开关  1-开启 0-关闭
 
        /// <summary>
        /// 插入包装机信息表
        /// </summary>
        public static void packageInfo(string machineNo, string trayCode, string lotNo, string oneTrayWeight)
        {
            if (packageCont == "1")
            {
                try
                {
                    MongoDBSingleton.Instance.Insert<packageInfoModel>(new packageInfoModel
                    {
                        machineNo = machineNo,
                        trayCode = trayCode,
                        batchNo = lotNo,
                        time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                        weight = oneTrayWeight,
                        CreateTime = DateTime.Now.AddHours(8)
                    }, "packageInfoModel");
                }
                catch (Exception ex)
                {
                    CMMLog.Error($"packageInfo Error:{ex.Message}");
                }
            }
 
        }
 
        public static void updatePackageInfo(string machince, string trayCode, int[] result)
        {
            if (packageCont == "1")
            {
                try
                {
                    var queryList = MongoDBSingleton.Instance.Find<packageInfoModel>(Query.And(Query.EQ("machineNo", machince), Query.EQ("trayCode", trayCode), Query.EQ("weight2", "")), "packageInfoModel");
                    if (queryList.Count > 0)
                    {
                        packageInfoModel query = queryList.OrderByDescending(a => a.time).First();
                        if (query != null)
                        {
                            CMMLog.Debug($"updatePackageInfo:{query.machineNo},trayCode:{query.trayCode},weight:{query.weight}");
                            //读取复称平台的重量 result[17]) + PLCControl.Completion(result[18]
                            double x = (double)Convert.ToInt32(PLCControl.Completion(result[19]) + PLCControl.Completion(result[20]), 2) / 100;
                            string weight = x.ToString();
                            CMMLog.Debug($"updatePackageInfo:原始复称重量数据:{result[19]},{result[20]};转换后复称重量数据:{weight}");
 
                            //重量差值
                            //string weightDifference = (double.Parse(query.weight) - x).ToString();
                            string weightDifference = Math.Round((double.Parse(query.weight) - x), 2).ToString();
                            //CMMLog.Info($"weightDifference2:{weightDifference2}");
 
                            //将复称平台重量写入中间表
                            MongoDBSingleton.Instance.Update<packageInfoModel>(Query.And(Query.EQ("machineNo", machince), Query.EQ("time", query.time), Query.EQ("trayCode", query.trayCode), Query.EQ("weight2", "")), Update.Set("weight2", weight).Set("weightDifference", weightDifference), UpdateFlags.None);
 
                        }
                        else CMMLog.Debug($"数据查询失败");
                    }
                    else CMMLog.Debug($"updatePackageInfo:packageInfoModel未找到数据,machineNo:{machince},trayCode:{trayCode}");
                }
                catch (Exception ex)
                {
                    CMMLog.Error($"updatePackageInfo Error:{ex.Message}");
                }
            }
        }
 
        public static void deletePackageInfo()
        {
            if (packageCont == "1")
            {
                try
                {
                    var request = MongoDBSingleton.Instance.FindAll<packageInfoModel>();
                    if (request.Count > 0)
                    {
                        request.ForEach(a =>
                        {
                            if (DateTime.Now.Subtract(a.CreateTime).TotalDays > 7)
                            {
                                MongoDBSingleton.Instance.Remove<packageInfoModel>(Query.EQ("_id", a._id), "packageInfoModel", RemoveFlags.None);
                            }
                        });
                    }
                }
                catch (Exception ex)
                {
                    CMMLog.Error($"deletePackageInfo Error:{ex.Message}");
                }
 
            }
        }
 
        internal static void insertMidTable()
        {
            var db = new SqlHelper<object>().GetInstance(false);
            bool resul = false;
 
            //CMMLog.Info($"查询【T_JY_MATERIALSync】表,查询条件:a.FWorkShopNumber == BM000161 && a.FUseOrgNumber == 02");
            var materInfo = db.Queryable<T_JY_MATERIALSync>().Where(a => a.FWorkShopNumber == "BM000161" && a.FUseOrgNumber == "02").ToList();
            if (materInfo.Count > 0)
            {
                //CMMLog.Info($"查询【T_JY_MATERIALSync】的数量为:{materInfo.Count}");
                var itemList = MongoDBSingleton.Instance.FindAll<ERPItemTable>();
                if (itemList.Count != materInfo.Count)
                {
                    MongoDBSingleton.Instance.RemoveAll<ERPItemTable>("ERPItemTable");
                }
 
                foreach (var a in materInfo)
                {
                    var itemInfo = MongoDBSingleton.Instance.FindOne<ERPItemTable>(Query.EQ("item_code", a.FNumber), "ERPItemTable");
                    if (itemInfo == null)
                    {
                        CMMLog.Info($"中间表【ERPItemTable】未查询到数据,物料编码:{a.FNumber}");
                        int itemNo = 1;
                        // 获取最大序号的数据
                        var maxErpItemInfoList = MongoDBSingleton.Instance.FindAll<ERPItemTable>("ERPItemTable");
                        if (maxErpItemInfoList.Count > 0)
                        {
                            var maxErpItemInfo = maxErpItemInfoList.OrderByDescending(it => it.item_no).First();
                            if (maxErpItemInfo != null) itemNo = maxErpItemInfo.item_no + 1;
                        }
 
                        CMMLog.Info($"获取插入序号:{itemNo}");
                        MongoDBSingleton.Instance.Insert<ERPItemTable>(new ERPItemTable
                        {
                            item_no = itemNo,
                            item_code = a.FNumber,
                            item_name = a.FName,
                            item_spec = a.FSpecification,
                            item_uom = a.FStoreUnit,
                            dateTime = DateTime.Now
                        }, "ERPItemTable");
                        resul = true;
                    }
                    else
                    {
                        //查询数据是否相同
                        if (itemInfo.item_name != a.FName || itemInfo.item_spec != a.FSpecification || itemInfo.item_uom != a.FStoreUnit)
                        {
                            var query = Query.EQ("item_code", a.FName);
                            var update = Update.Set("item_name", a.FName).Set("item_spec", a.FSpecification)
                            .Set("item_uom", a.FStoreUnit).Set("dateTime", DateTime.Now);
                            MongoDBSingleton.Instance.Update<ERPItemTable>(query, update, "ERPItemTable", MongoDB.Driver.UpdateFlags.None);
                            resul = true;
                        }
                    }
                }
            }
 
            var empInfo = db.Queryable<T_JY_EMPINFOSync>().ToList();
            if (empInfo.Count > 0)
            {
                var empList = MongoDBSingleton.Instance.FindAll<ERPEmployeeTable>();
                if (empList.Count != empInfo.Count)
                {
                    MongoDBSingleton.Instance.RemoveAll<ERPEmployeeTable>("ERPEmployeeTable");
                }
                foreach (var a in empInfo)
                {
                    var erpEmpInfo = MongoDBSingleton.Instance.FindOne<ERPEmployeeTable>(Query.EQ("item_code", a.FNumber), "ERPEmployeeTable");
                    if (erpEmpInfo == null)
                    {
                        CMMLog.Info($"中间表【ERPEmployeeTable】未查询到数据,物料编码:{a.FNumber}");
                        int itemNo = 1;
                        // 获取最大序号的数据
                        var maxErpEmpInfoList = MongoDBSingleton.Instance.FindAll<ERPEmployeeTable>("ERPEmployeeTable");
                        if (maxErpEmpInfoList.Count > 0)
                        {
                            var maxErpEmpInfo = maxErpEmpInfoList.OrderByDescending(it => it.item_no).First();
                            if (maxErpEmpInfo != null) itemNo = maxErpEmpInfo.item_no + 1;
                        }
 
                        CMMLog.Info($"获取插入序号:{itemNo}");
                        MongoDBSingleton.Instance.Insert<ERPEmployeeTable>(new ERPEmployeeTable
                        {
                            item_no = itemNo,
                            item_code = a.FNumber,
                            item_name = a.FName,
                            employee_id = a.FStaffNumber,
                            dateTime = DateTime.Now
                        }, "ERPEmployeeTable");
 
                        resul = true;
                    }
                    else
                    {
                        if (erpEmpInfo.employee_id != a.FStaffNumber)
                        {
                            var query = Query.EQ("item_code", a.FNumber);
                            var update = Update.Set("item_name", a.FName).Set("employee_id", a.FStaffNumber)
                            .Set("dateTime", DateTime.Now);
                            MongoDBSingleton.Instance.Update<ERPEmployeeTable>(query, update, "ERPEmployeeTable", MongoDB.Driver.UpdateFlags.None);
 
                            resul = true;
                        }
                    }
                }
            }
            if (resul)
            {
                if (!ERPService.WriteEmpAndItemInfoTwo())
                {
                    //清空表数据
                    MongoDBSingleton.Instance.RemoveAll<ERPItemTable>("ERPItemTable");
                    MongoDBSingleton.Instance.RemoveAll<ERPEmployeeTable>("ERPEmployeeTable");
                }
            }
        }
 
        internal static bool WriteEmpAndItemInfoTwo()
        {
            try
            {
                TcpClient client = new TcpClient("10.50.65.30", 3001);
 
                CMMLog.Info("WriteEmpAndItemInfoTwo 已连接到服务器");
                NetworkStream stream = client.GetStream();
                List<byte> paddedData = new List<byte>();
                var encode = Encoding.GetEncoding("GB2312");
                int i = 0;
                while (i < 150)
                {
                    if (i < 100)
                    {
                        //员工编号
                        var erpInfo = MongoDBSingleton.Instance.FindOne<ERPEmployeeTable>(Query.EQ("item_no", i + 1), "ERPEmployeeTable");
                        if (erpInfo != null && !string.IsNullOrEmpty(erpInfo.employee_id))
                        {
                            // 内存地址 0~4 协议地址 1~5 计量单位
                            byte[] data1 = encode.GetBytes(erpInfo.employee_id);
                            byte[] paddedData1 = new byte[10];
 
                            Array.Copy(data1, 0, paddedData1, 0, Math.Min(data1.Length, 10));
 
                            // 将数组转换为列表
                            paddedData.AddRange(paddedData1);
                        }
                        else
                        {
                            paddedData.AddRange(new byte[10]);
                        }
                    }
                    else
                    {
                        int itemNo = i - 99;
                        //物料信息
                        var itemInfo = MongoDBSingleton.Instance.FindOne<ERPItemTable>(Query.EQ("item_no", itemNo), "ERPItemTable");
                        if (itemInfo != null)
                        {
                            // 将数组转换为列表
                            paddedData.AddRange(getBuff(itemInfo.item_spec, 20, 2));
 
                            paddedData.AddRange(getBuff(itemInfo.item_code, 40, 1));
 
                            paddedData.AddRange(getBuff(itemInfo.item_name, 30, 3));
 
                            paddedData.AddRange(getBuff(itemInfo.item_uom, 10, 1));
 
                        }
                        else
                        {
                            paddedData.AddRange(new byte[100]);
                        }
                    }
                    i++;
                }
 
                byte[] combinedArray = paddedData.ToArray();
 
                stream.Write(combinedArray, 0, combinedArray.Length);
                CMMLog.Info("WriteEmpAndItemInfoTwo:" + JsonConvert.SerializeObject(combinedArray));
                //CMMLog.Info($"WriteEmpAndItemInfoTwo {combinedArray.Length}");
 
                //CMMLog.Info($"Received: {encode.GetString(combinedArray, 0, 6000)}");
                return true;
            }
            catch (Exception ex)
            {
                CMMLog.Info("WriteEmpAndItemInfoTwo err:" + ex.Message);
                return false;
                //WriteEmpAndItemInfoTwo();
            }
        }
 
        private static byte[] getBuff(string value, int bit, int result)
        {
            byte[] data1 = Encoding.GetEncoding("GB2312").GetBytes(value);
            if (result == 2) data1 = Encoding.UTF8.GetBytes(value);
            if (result == 3) data1 = Encoding.BigEndianUnicode.GetBytes(value);
            byte[] paddedData1 = new byte[bit];
            Array.Copy(data1, 0, paddedData1, 0, Math.Min(data1.Length, bit)); // 将数据复制到6000字节的缓冲区中
            return paddedData1;
        }
 
        public class packageInfoModel
        {
            public ObjectId _id { get; set; }
            /// <summary>
            /// 包装机号
            /// </summary>
            public string machineNo { get; set; } = "";
            /// <summary>
            /// 托盘号
            /// </summary>
            public string trayCode { get; set; } = "";
            /// <summary>
            /// 批次号
            /// </summary>
            public string batchNo { get; set; } = "";
            /// <summary>
            /// 下料时间
            /// </summary>
            public string time { get; set; } = "";
            /// <summary>
            /// 重量
            /// </summary>
            public string weight { get; set; } = "";
            /// <summary>
            /// 复称重量
            /// </summary>
            public string weight2 { get; set; } = "";
            /// <summary>
            /// 重量差值
            /// </summary>
            public string weightDifference { get; set; } = "";
            /// <summary>
            /// 创建时间
            /// </summary>
            public DateTime CreateTime { get; set; }
        }
 
    }
}