buli
2023-07-05 af7b716a60d889acea95560abba0e46eee008b8f
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
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
public without sharing class AssetHandler extends Oly_TriggerHandler {
  public static Map<String, List<Rental_Apply_Equipment_Set_Detail__c>> queueRaesdMap;
  private Map<Id, Asset> newMap;
  private Map<Id, Asset> oldMap;
  private List<Asset> newList;
  private List<Asset> oldList;
  private static final Map<String, Schema.RecordTypeInfo> DEVELOPERNAMEMAP = Schema.SObjectType.Asset.getRecordTypeInfosByDeveloperName(); // 20230306 ljh add
  @TestVisible
  private static Set<String> testTargetDepts;
  @TestVisible
  private static Id Account_Asset_Id;
  public static Boolean disabled = false;
 
  public AssetHandler() {
    this.newMap = (Map<Id, Asset>) Trigger.newMap;
    this.oldMap = (Map<Id, Asset>) Trigger.oldMap;
    this.newList = (List<Asset>) Trigger.new;
    this.oldList = (List<Asset>) Trigger.old;
 
    Integer i = 0;
  }
 
  protected override void beforeInsert() {
    beforeSetValue();
    //动态更新 Asset的 AccountId的 Logic
    beforeSetAccountId();
 
    //第一次不加变更的时候不知道第一次是多少
    updateChangeQuantityReason();
 
    workflowCode();
  }
  protected override void beforeUpdate() {
    if (!disabled) {
      beforeSetValue();
      //动态更新 Asset的 AccountId的 Logic
      beforeSetAccountId();
 
      updateChangeQuantityReason();
 
      // 20230309 gzw 优化 注释代码
 
      // 虚拟维修保修合同保修开始结束日期更新
      // updateMaintenance_Contract_Asset();
 
      // 20230309 gzw 优化 注释代码
 
      updateRentalCount();
 
      workflowCode();
    }
  }
 
  protected override void afterInsert() {
    //有新的Asset的时候 暂定分配
    queueRedistribution();
  }
 
  protected override void afterUpdate() {
    if (!disabled) {
      mainAssetUpdateed_OneToOneRecord();
      // 已经改进 Must_Input_ChangeQuantityReason 的 valida before可以完成 ChangeQuantityReason__c = ''
      ////入力規則によってbeforeクリアできません,
      cleanChangeQuantityReason();
      // 清理字段「待废弃数(丢失/盘亏)修改理由」
      cleanGiveupReturnReason();
      //当主体参照的Asset的Last断开的时候重新寻找暂定分配
      queueRedistribution();
      // before では数式項目がnullの場合があります
      formulaToTextCheck();
      // check一对一link表
      checkOneToOneLink();
      // 虚拟维修保修合同保修开始结束日期更新
      updateMaintenance_Contract_Asset();
    }
  }
 
  //20230309 sx 保有设备workflow代码化 start
  private void workflowCode() {
    /*List<Id> accIds = new List<Id>();
        List<Id> productIds = new List<Id>(); 
        List<Id> hospitalIds = new List<Id>();
        for(Asset nObj : newList) {
            accIds.add(nObj.Account.Id);
            productIds.add(nObj.Product2.Id);
            hospitalIds.add(nObj.Hospital__c);
        }
        
        //查找客户List
        Map<Id, Account> accMap = new Map<Id, Account>([SELECT Id, Name, Management_Code__c from Account where Id in :accIds]);
        Map<Id, Product2> productMap = new Map<Id, Product2>([SELECT Id, Name, RecordTypeId, RecordType.Name, Serial_Lot_No__c ,ProductCode  from Product2 where Id in :productIds]);
        Map<Id, Account> hosMap = new Map<Id, Account>([SELECT Id, Name, RecordType.Name  from Account where id in :hospitalIds]);
 
        Map<Id, Account> acc_assMap = new Map<Id, Account>();
        Map<Id, Product2> pro_proMap = new Map<Id, Product2>();
        Map<Id, Account> hos_assMap = new Map<Id, Account>();
        for(Asset nObj : newList){
            if(accMap.containsKey(nObj.Account.Id)) {
                acc_assMap.put(nObj.Id, accMap.get(nObj.Account.Id));
            }
            if(productMap.containsKey(nObj.Product2.Id)) {
                pro_proMap.put(nObj.Id, productMap.get(nObj.Product2.Id));
            }
            if(hosMap.containsKey(nObj.Hospital__c)) {
                hos_assMap.put(nObj.Id, hosMap.get(nObj.Id));
            }
        }*/
    Date today = Date.today();
 
    for (Asset nObj : newList) {
      //保有设备HPID文本化
      nObj.Asset_Year_Txt__c = nObj.Asset_Year__c;
      nObj.HP_ID_Text__c = nObj.HP_Id__c;
      nObj.Gurantee_End_day1__c = nObj.Gurantee_End_day__c;
 
      //覆盖设备的可选对象文本化
      if (
        Trigger.isInsert ||
        (Trigger.isUpdate &&
        nObj.Posting_Date__c != oldMap.get(nObj.Id).Posting_Date__c)
      ) {
        if (
          String.isBlank(nObj.IF_Coverage_Target_Asset__c) ||
          '0'.equals(nObj.IF_Coverage_Target_Asset__c)
        ) {
          nObj.IF_Coverage_Target_Asset__c =
            nObj.IF_Coverage_Target_Asset_FF__c + '';
        }
 
        if (
          nObj.IF_Coverage_Target_Asset_FF__c == 3 &&
          nObj.FY23_Asset_Age__c == null
        ) {
          nObj.FY23_Asset_Age__c = 0;
        }
      }
 
      //市场对应录入时间自动录入
      if (
        (Trigger.isInsert && nObj.Market_Product_Category__c != null) ||
        (Trigger.isUpdate &&
        nObj.Market_Product_Category__c !=
        oldMap.get(nObj.Id).Market_Product_Category__c &&
        nObj.Market_Product_Category__c != null)
      ) {
        nObj.Marketing_Input_Date__c = today;
      }
 
      /*//待报废变更为使用中
            if(nObj.RecordType.Name == '备品' 
                && nObj.Manage_type__c == '个体管理' 
                && nObj.Quantity > 0 && nObj.Status == '待报废' 
                && ( (nObj.Abandoned_RealThing__c == null && nObj.Abandoned_Inventory__c == null) || (nObj.Abandoned_RealThing__c + nObj.Abandoned_Inventory__c) == 0) 
                && acc_assMap.get(nObj.Id).Management_Code__c != System.Label.Account_Asset_FJZ) {
                nObj.Status = '使用中';
                nObj.Tobe_Discarded_Date__c = null;
            }*/
 
      /*//AssetMarkUpdate
            if(Trigger.isUpdate && nObj.IF_Information_From__c == false && nObj.AssetMark__c == null) {
                if(pro_proMap.containsKey(nObj.Id)){
                    if(pro_proMap.get(nObj.Id).RecordType.Name == '竞品-主机' ) {
                        nObj.AssetMark__c = '竞品主机';
                    }else if(pro_proMap.get(nObj.Id).RecordType.Name == '竞品-耗材') {
                        nObj.AssetMark__c = '竞品耗材';
                    }else if(pro_proMap.get(nObj.Id).Serial_Lot_No__c == 'S/N tracing') {
                        nObj.AssetMark__c = '主机';
                    }
                }
                else {
                    nObj.AssetMark__c = '耗材';
                }
            }*/
 
      /*//AssetName=ProductName
            if(nObj.Name.equals('*') || (nObj.Product2.Id != null && nObj.Product2 != oldMap.get(nObj.Id).Product2)) {
                nObj.Name = pro_proMap.get(nObj.Id).Name;  
            }*/
 
      //AssetTextCopy
      if (
        Trigger.isInsert ||
        (Trigger.isUpdate && nObj.Product2 != oldMap.get(nObj.Id).Product2)
      ) {
        nObj.BSSCategory_Text__c = nObj.BSSCategory__c;
        nObj.Brand_Name_Text__c = nObj.Brand_Name__c;
        nObj.Category2_Text__c = nObj.Category2__c;
        nObj.Category3_Text__c = nObj.Category3__c;
        nObj.Category4_Text__c = nObj.Category4__c;
        nObj.Category5_Text__c = nObj.Category5__c;
      }
 
      //CIC安装状态确认日
      if (
        nObj.CIC_call_back_check__c && nObj.CIC_call_back_confirm_day__c == null
      ) {
        nObj.CIC_call_back_confirm_day__c = today;
      }
 
      //Equipment_Last_confirmed_day
      if (
        (Trigger.isInsert &&
        (nObj.Status != null ||
        nObj.Installation_Site__c != null ||
        nObj.Final_Examination_Date__c != null ||
        nObj.Hospital_Manage_Number__c != null)) ||
        (Trigger.isUpdate &&
        (nObj.Status != oldMap.get(nObj.Id).Status ||
        nObj.Installation_Site__c != oldMap.get(nObj.Id).Installation_Site__c ||
        nObj.Final_Examination_Date__c !=
        oldMap.get(nObj.Id).Final_Examination_Date__c ||
        nObj.Hospital_Manage_Number__c !=
        oldMap.get(nObj.Id).Hospital_Manage_Number__c))
      ) {
        nObj.Equipment_Last_checking_day__c = today;
      }
 
      /*//Product_Code+Serial_No
            if(Trigger.isUpdate && nObj.IsCompetitorProduct == false && nObj.Manage_type__c != '数量管理' && nObj.AssetMark__c != '耗材' && nObj.Loaner_accsessary__c != true && nObj.unknow_serial_NO_product__c != false) {
                if(nObj.Product2.Id == null) {
                    nObj.Product_Serial_No__c = nObj.Id;
                }else {
                    nObj.Product_Serial_No__c = pro_proMap.get(nObj.Id).ProductCode + ' ' + nObj.SerialNumber;
                    if(nObj.Delete_Flag__c){
                        nObj.Product_Serial_No__c += ':' + acc_assMap.get(nObj.Id).Management_Code__c;
                    }
                }
            }*/
 
      //Product_Code+Serial_No Clear
      if (
        (Trigger.isInsert && nObj.IsCompetitorProduct) ||
        (Trigger.isUpdate &&
        nObj.IsCompetitorProduct &&
        !oldMap.get(nObj.Id).IsCompetitorProduct)
      ) {
        nObj.Product_Serial_No__c = '';
      }
 
      /*//Product_Code+Serial_No+Salesdepartment
            if(Trigger.isUpdate && nObj.IsCompetitorProduct == false && nObj.Manage_type__c == '数量管理' && nObj.AssetMark__c == '耗材' && nObj.Loaner_accsessary__c == true && nObj.unknow_serial_NO_product__c == false) {
                if(nObj.Product2.Id == null) {
                    nObj.Product_Serial_No__c = nObj.Id;
                }else {
                    nObj.Product_Serial_No__c = pro_proMap.get(nObj.Id).ProductCode + ' ' + nObj.SerialNumber + ':' + nObj.Salesdepartment__c.subString(0,nObj.Salesdepartment__c.indexOf(':'));
                    if(nObj.Delete_Flag__c){
                        nObj.Product_Serial_No__c += ':' + acc_assMap.get(nObj.Id).Management_Code__c;
                    }
                }
            }*/
 
      /*//Product_Code+Serial_No UnkownSerial
            if(Trigger.isUpdate && nObj.unknow_serial_NO_product__c == true) {
                nObj.SerialNumber = nObj.serial_past__c;
                if(nObj.Product2.Id == null) {
                    nObj.Product_Serial_No__c = nObj.Id;
                }else {
                    nObj.Product_Serial_No__c = pro_proMap.get(nObj.Id).ProductCode + ':' + nObj.serial_past__c;
                    if(nObj.Delete_Flag__c){
                        nObj.Product_Serial_No__c += ':' + acc_assMap.get(nObj.Id).Management_Code__c;
                    }
                }
            }*/
 
      //更新备品资产管理负责本部选项
      if (
        (Trigger.isInsert && nObj.Internal_demo_incharge_demo__c != null) ||
        (Trigger.isUpdate &&
        nObj.Internal_demo_incharge_demo__c !=
        oldMap.get(nObj.Id).Internal_demo_incharge_demo__c)
      ) {
        nObj.Internal_demo_incharge_demo_text__c = nObj.Internal_demo_incharge_demo__c;
      }
 
      /*//自动更新资产所属(医院资产)
            if(Trigger.isUpdate && nObj.RecordType.Name == '医院保有设备' && hos_assMap.containskey(nObj.Id) && hos_assMap.get(nObj.Id).RecordType.Name == '病院' && acc_assMap.get(nObj.Id).Id == '00110000015Bx0h' ) {
                nObj.Asset_Owner__c = '医院资产';
            }*/
 
      /*//自动更新资产所属(奥林巴斯)
            if(nObj.RecordType.Name == '医院保有设备' || (acc_assMap.containskey(nObj.Id) && acc_assMap.get(nObj.Id).Id == '00110000015Bx0h')) {
                nObj.Asset_Owner__c = '奥林巴斯';
            }*/
 
      /*//自动更新资产所属(经销商资产)
            if(nObj.RecordType.Name == '医院保有设备' && (acc_assMap.containskey(nObj.Id) && hos_assMap.get(nObj.Id).RecordType.Name == '販売店')) {
                nObj.Asset_Owner__c = '经销商资产';
            }*/
 
      //手动创建的耗材信息修改
      if (
        nObj.RecordTypeId == '01210000000kOPM' &&
        nObj.Information_From__c == '手动输入' &&
        nObj.AssetMark__c == '耗材'
      ) {
        nObj.Guarantee_period_for_products__c = nObj.Posting_Date__c;
        nObj.InstallDate = nObj.Posting_Date__c;
      }
 
      //出货日自动赋值
      if (Trigger.isInsert && nObj.Information_From__c == '手动输入') {
        nObj.Posting_Date__c = Date.newInstance(1900, 1, 1);
      }
 
      //新逻辑保修期限对应
      if (nObj.New_logic_data__c) {
        nObj.Guarantee_period_for_products__c = nObj.Guarantee_period_formula__c;
      }
 
      //成本中心更新编码Update
      if (
        (Trigger.isInsert && nObj.Internal_cost_center_cd__c != null) ||
        (Trigger.isUpdate &&
        nObj.Internal_cost_center_cd__c !=
        oldMap.get(nObj.Id).Internal_cost_center_cd__c)
      ) {
        nObj.Internal_demo_incharge_demo_text__c = nObj.Internal_cost_center_formula__c;
      }
 
      //成本中心更新选项Update
      if (
        (Trigger.isInsert && nObj.Internal_cost_center__c != null) ||
        (Trigger.isUpdate &&
        nObj.Internal_cost_center__c !=
        oldMap.get(nObj.Id).Internal_cost_center__c)
      ) {
        nObj.Internal_cost_center_text__c = nObj.Internal_cost_center__c;
      }
 
      //待报废日登录
      if (
        Trigger.isUpdate &&
        nObj.Fixture_Status__c != oldMap.get(nObj.Id).Fixture_Status__c &&
        nObj.Fixture_Status__c != '废弃' &&
        (nObj.Abandoned_RealThing__c > 0 ||
        nObj.Abandoned_Inventory__c > 0) &&
        nObj.Manage_type__c == '个体管理'
      ) {
        nObj.Status = '待报废';
        nObj.Tobe_Discarded_Date__c = today;
      }
 
      //退货转备品DEL置FALSE
      if (
        Trigger.isUpdate &&
        ((nObj.RecordType != oldMap.get(nObj.Id).RecordType &&
        nObj.RecordTypeId == '01210000000kOPR') ||
        (nObj.AccountId != oldMap.get(nObj.Id).AccountId &&
        nObj.AccountId == '0011000000VAiwz')) &&
        nObj.Delete_Flag__c
      ) {
        nObj.Delete_Flag__c = false;
      }
 
      //追溯设备耗材Mark更新
      if (
        '追溯系统'.equals(nObj.Information_From__c) &&
        String.isBlank(nObj.AssetMark__c)
      ) {
        nObj.AssetMark__c = '耗材';
      }
 
      //納入商品状態変更(使用中)
      if (
        (Trigger.isInsert && nObj.Status == '使用中') ||
        (Trigger.isUpdate &&
        nObj.Status != oldMap.get(nObj.Id).Status &&
        nObj.Status == '使用中')
      ) {
        nObj.Status_Busy_Date__c = today;
      }
 
      //納入商品状態変更(廃棄)
      if (
        (Trigger.isInsert && nObj.Status == '廃棄') ||
        (Trigger.isUpdate &&
        nObj.Status != oldMap.get(nObj.Id).Status &&
        nObj.Status == '廃棄')
      ) {
        nObj.Discarded_Date__c = today;
        nObj.Quantity = 0;
        nObj.Abandoned_Inventory__c = null;
        nObj.Abandoned_RealThing__c = null;
        nObj.ChangeQuantityReason__c = '废弃';
      }
 
      //納入商品状態変更(不明)
      if (
        (Trigger.isInsert && nObj.Status == '不明') ||
        (Trigger.isUpdate &&
        nObj.Status != oldMap.get(nObj.Id).Status &&
        nObj.Status == '不明')
      ) {
        nObj.Indistinctness_Date__c = today;
      }
 
      //納入商品状態変更(未使用)
      if (
        (Trigger.isInsert && nObj.Status == '未使用') ||
        (Trigger.isUpdate &&
        nObj.Status != oldMap.get(nObj.Id).Status &&
        nObj.Status == '未使用')
      ) {
        nObj.Unused_Date__c = today;
      }
 
      /*//納品確認書の診療科コード_セット
            if(!(nObj.Product2.Id != null && nObj.IsCompetitorProduct == false && nObj.InstallDate != null) && nObj.Install_Account_Code__c == null) {
                nObj.Install_Account_Code__c = acc_assMap.get(nObj.Id).Management_Code__c;
                nObj.Install_Account_Name__c = acc_assMap.get(nObj.Id).Name;
                nObj.Install_Hospital_Name__c = hos_assMap.get(nObj.Id).Name;
                nObj.Install_Hospital_code__c = hos_assMap.get(nObj.Id).Management_Code__c;
            }*/
 
      //病院管理番号変更日
      if (
        (Trigger.isInsert && nObj.Hospital_Manage_Number__c != null) ||
        (Trigger.isUpdate &&
        nObj.Hospital_Manage_Number__c !=
        oldMap.get(nObj.Id).Hospital_Manage_Number__c)
      ) {
        nObj.Hospital_Manage_Number_Change_Date__c = today;
      }
 
      //更新-2次前点检日
      if (
        Trigger.isUpdate &&
        nObj.Final_Examination_Date__c !=
        oldMap.get(nObj.Id).Final_Examination_Date__c
      ) {
        nObj.X2_second_past_inspection__c = oldMap.get(nObj.Id)
          .Final_Examination_Date__c;
      }
 
      // 文本化 多年保修期至
      nObj.Extend_Gurantee_DateTo_Text__c = nObj.Extend_Gurantee_DateTo__c;
 
      // 保修天数工作流
      if (
        Trigger.isInsert ||
        (Trigger.isUpdate &&
        (nObj.Guarantee_period_for_products__c !=
        oldMap.get(nObj.Id).Guarantee_period_for_products__c ||
        nObj.InstallDate__c != oldMap.get(nObj.Id).InstallDate__c ||
        nObj.ChangeWarrantyStartDate__c !=
        oldMap.get(nObj.Id).ChangeWarrantyStartDate__c))
      ) {
        nObj.GuaranteePeriod__c = nObj.guarantee_period__c;
      }
 
      // 有安装日,更新状态到[使用中]
      if (
        (Trigger.isInsert && nObj.InstallDate != null) ||
        (Trigger.isUpdate &&
        nObj.InstallDate != null &&
        nObj.InstallDate != oldMap.get(nObj.Id).InstallDate)
      ) {
        nObj.Status_Busy_Date__c = today;
        nObj.Status = '使用中';
      }
 
      // 备品再退货转DEL置TRUE
      if (
        nObj.AccountId == '00110000015Bx0h' &&
        nObj.RecordTypeId == '01210000000kOPM' &&
        !nObj.Delete_Flag__c
      ) {
        nObj.Delete_Flag__c = true;
      }
 
      // 设定备品所属公司(上海)FromVBA
      if (
        (Trigger.isInsert && nObj.CompanyCodeOfEquipment_txt__c == '5112') ||
        (Trigger.isUpdate &&
        nObj.CompanyCodeOfEquipment_txt__c !=
        oldMap.get(nObj.Id).CompanyCodeOfEquipment_txt__c &&
        nObj.CompanyCodeOfEquipment_txt__c == '5112')
      ) {
        nObj.CompanyOfEquipment__c = '上海';
      }
 
      // 设定备品所属公司(沈阳)FromVBA
      if (
        (Trigger.isInsert && nObj.CompanyCodeOfEquipment_txt__c == '5114') ||
        (Trigger.isUpdate &&
        nObj.CompanyCodeOfEquipment_txt__c !=
        oldMap.get(nObj.Id).CompanyCodeOfEquipment_txt__c &&
        nObj.CompanyCodeOfEquipment_txt__c == '5114')
      ) {
        nObj.CompanyOfEquipment__c = '沈阳';
      }
 
      // 设定备品所属公司(北京)FromVBA
      if (
        (Trigger.isInsert && nObj.CompanyCodeOfEquipment_txt__c == '5111') ||
        (Trigger.isUpdate &&
        nObj.CompanyCodeOfEquipment_txt__c !=
        oldMap.get(nObj.Id).CompanyCodeOfEquipment_txt__c &&
        nObj.CompanyCodeOfEquipment_txt__c == '5111')
      ) {
        nObj.CompanyOfEquipment__c = '北京';
      }
 
      // 设定备品所属公司(广州)FromVBA
      if (
        (Trigger.isInsert && nObj.CompanyCodeOfEquipment_txt__c == '5113') ||
        (Trigger.isUpdate &&
        nObj.CompanyCodeOfEquipment_txt__c !=
        oldMap.get(nObj.Id).CompanyCodeOfEquipment_txt__c &&
        nObj.CompanyCodeOfEquipment_txt__c == '5113')
      ) {
        nObj.CompanyOfEquipment__c = '广州';
      }
    }
  }
  //20230309 sx 保有设备workflow代码化 end
 
  // 借出明细更新借出_分配_数(Sys)和已借出数(Sys)
  private void updateRentalCount() {
    Set<Id> idSet = new Set<Id>();
    for (Id assId : this.newMap.keySet()) {
      if (
        this.newMap.get(assId).AssetManageConfirm__c &&
        this.newMap.get(assId).Account_Management_Code__c !=
        System.Label.Account_Asset_FJZ
      ) {
        idSet.add(assId);
        this.newMap.get(assId).Out_of_wh_Sys__c = 0;
        this.newMap.get(assId).Rental_Count_Sys__c = 0;
      }
    }
    if (!idSet.isEmpty()) {
      // 备品性能优化改修 20230312 by lc Start
      List<AggregateResult> raesdTempList2 = [
        SELECT COUNT(Id) num, Asset__c
        FROM Rental_Apply_Equipment_Set_Detail__c
        //备品发货报错对应 20230413 by lc Start
        //WHERE Detail_Finish__c = false
        WHERE
          Detail_Not_Finish_Text__c = TRUE
          //备品发货报错对应 20230413 by lc End
          AND Asset__c IN :idSet
          AND Shippment_loaner_time2__c != NULL
        GROUP BY Asset__c
      ];
      if (raesdTempList2 != null && raesdTempList2.size() > 0) {
        for (AggregateResult ar : raesdTempList2) {
          String assetId = String.valueOf(ar.get('Asset__c'));
          Integer tempNum = Integer.valueOf(ar.get('num'));
          this.newMap.get(assetId).Rental_Count_Sys__c += tempNum;
        }
      }
 
      List<AggregateResult> raesdTempList1 = [
        SELECT COUNT(Id) num, Asset__c
        FROM Rental_Apply_Equipment_Set_Detail__c
        //备品发货报错对应 20230413 by lc Start
        //WHERE Detail_Finish__c = false
        WHERE
          Detail_Not_Finish_Text__c = TRUE
          //备品发货报错对应 20230413 by lc End
          AND Asset__c IN :idSet
        GROUP BY Asset__c
      ];
      if (raesdTempList1 != null && raesdTempList1.size() > 0) {
        for (AggregateResult ar : raesdTempList1) {
          String assetId = String.valueOf(ar.get('Asset__c'));
          Integer tempNum = Integer.valueOf(ar.get('num'));
          this.newMap.get(assetId).Out_of_wh_Sys__c += tempNum;
          idSet.remove(assetId);
        }
      }
 
      /*for (Rental_Apply_Equipment_Set_Detail__c raesd : [
                SELECT Id, Shippment_loaner_time2__c, Asset__c
                FROM Rental_Apply_Equipment_Set_Detail__c
                WHERE Detail_Finish__c = false
                AND Asset__c IN :idSet
            ]) {
                this.newMap.get(raesd.Asset__c).Out_of_wh_Sys__c += 1;
                if(raesd.Shippment_loaner_time2__c != null) {
                    this.newMap.get(raesd.Asset__c).Rental_Count_Sys__c += 1;
                }
                idSet.remove(raesd.Asset__c);
            }*/
      // 备品性能优化改修 20230312 by lc End
 
      if (!idSet.isEmpty()) {
        // 没有字段可以完全准确地区分备品设备与耗材设备,只好把备品里没出现过的设备当成耗材来查
        for (Consum_Apply_Equipment_Set_Detail__c caesd : [
          SELECT Id, Shippment_loaner_time2__c, Asset__c
          FROM Consum_Apply_Equipment_Set_Detail__c
          WHERE Detail_Finish__c = FALSE AND Asset__c IN :idSet
        ]) {
          this.newMap.get(caesd.Asset__c).Out_of_wh_Sys__c += 1;
          if (caesd.Shippment_loaner_time2__c != null) {
            this.newMap.get(caesd.Asset__c).Rental_Count_Sys__c += 1;
          }
        }
      }
    }
  }
  //多年保修 start
  private void updateMaintenance_Contract_Asset() {
    StaticParameter.EscapeMaintenanceContractAfterUpdateTrigger = true;
    Set<id> AssetIDSet = new Set<id>();
    for (Asset tempAsset : newList) {
      // 20230306 ljh update start
      Id Shipment = DEVELOPERNAMEMAP.get('Shipment').getRecordTypeId();
      // if(String.isNotBlank(tempAsset.warrantyType__c)){
      if (
        String.isNotBlank(tempAsset.warrantyType__c) &&
        Shipment != tempAsset.RecordTypeId
      ) {
        // 20230306 ljh update end
        AssetIDSet.add(tempAsset.id);
      }
    }
    if (AssetIDSet.size() > 0) {
      list<Maintenance_Contract_Asset__c> MCAList = [
        SELECT
          id,
          startDateGurantee__c,
          startDateGurantee_Text__c,
          endDateGurantee__c,
          endDateGurantee_Text__c,
          Return_Flag__c,
          ChangeAcc_flag__c,
          Maintenance_Price_Amount__c,
          Maintenance_Price_Amount_text__c,
          GuaranteePrice_Amount__c,
          GuaranteePrice_Amount_text__c
        FROM Maintenance_Contract_Asset__c
        WHERE
          Asset__c IN :AssetIDSet
          AND Maintenance_Contract__r.RecordType.DeveloperName = 'VM_Contract'
      ];
      if (MCAList.size() > 0) {
        list<Maintenance_Contract_Asset__c> UpdateMcaList = new List<Maintenance_Contract_Asset__c>();
        for (Maintenance_Contract_Asset__c tempMCA : MCAList) {
          if (
            tempMCA.startDateGurantee__c != tempMCA.startDateGurantee_Text__c ||
            tempMCA.endDateGurantee__c != tempMCA.endDateGurantee_Text__c ||
            tempMCA.Maintenance_Price_Amount__c !=
            tempMCA.Maintenance_Price_Amount_Text__c ||
            tempMCA.GuaranteePrice_Amount__c !=
            tempMCA.GuaranteePrice_Amount_text__c
          ) {
            UpdateMcaList.add(tempMCA);
          }
        }
        Oly_TriggerHandler.bypass('SetContractEstimatePriceHandler');
        update UpdateMcaList;
        Oly_TriggerHandler.clearBypass('SetContractEstimatePriceHandler');
      }
    }
  }
  //多年保修 end
 
  private void beforeSetValue() {
    for (Asset nObj : newList) {
      // 有线下数据, 所以不需要下面的logic
      //if (nObj.Quantity == null) {
      //    nObj.Quantity = 1;
      //}
      if (Trigger.isInsert) {
        nObj.Last_Reserve_RAES_Detail__c = null;
        nObj.Last_Reserve_TAES_Detail__c = null;
        nObj.Pre_Reserve_RAES_Detail__c = null;
        nObj.Pre_Reserve_TAES_Detail__c = null;
        nObj.Fixture_OneToOne_Link__c = null;
      }
 
      if (Trigger.isUpdate) {
        Asset oObj = oldMap.get(nObj.Id);
        if (
          oObj.Last_Reserve_RAES_Detail__c != null &&
          nObj.Last_Reserve_RAES_Detail__c == null &&
          oObj.Last_Reserve_RAES_Detail_Flag__c == true
        ) {
          nObj.Pre_Reserve_RAES_Detail__c = oObj.Last_Reserve_RAES_Detail__c;
        }
        if (
          oObj.Last_Reserve_TAES_Detail__c != null &&
          nObj.Last_Reserve_TAES_Detail__c == null
        ) {
          // TODO 由于__r超20,字段建不出来
          // && oObj.Last_Reserve_TAES_Detail_Flag__c == true
          nObj.Pre_Reserve_TAES_Detail__c = oObj.Last_Reserve_TAES_Detail__c;
        }
      }
 
      // 必ず最後で置く
      nObj.Fixture_Status2_text__c = nObj.Fixture_Status2__c;
      nObj.Fixture_Status3_text__c = nObj.Fixture_Status3__c;
      nObj.BTreeIndexKey__c =
        nObj.Asset_Owner__c +
        ':' +
        nObj.Asset_loaner_category__c +
        ':' +
        String.valueOf(nobj.Freeze_sign_Abandoned_Flag__c) +
        ':' +
        String.valueOf(nObj.Delete_Flag__c) +
        ':' +
        String.valueOf(nObj.AssetManageConfirm__c);
 
      if (
        nObj.Status ==
        FixtureUtil.assetStatusMap.get(
          FixtureUtil.AssetStatus.Dai_Fei_Qi.ordinal()
        )
      ) {
        nObj.Freeze_sign__c = false;
      }
      // gzw CHAN-CCR6MW  【委托】【保有设备】保有设备发货日逻辑 start
      if (Trigger.isInsert && nObj.Posting_Date__c == null) {
        nObj.Posting_Date__c = Date.newInstance(1900, 1, 1);
      }
      // gzw CHAN-CCR6MW  【委托】【保有设备】保有设备发货日逻辑 end
    }
  }
 
  // かならず before
  private void updateChangeQuantityReason() {
    for (Asset nObj : newList) {
      Asset oObj;
      String oQuantity = '';
      String oAbandoned_Inventory = '';
      if (Trigger.isUpdate) {
        oObj = oldMap.get(nObj.Id);
        oQuantity = oObj.Quantity == null ? '' : String.valueOf(oObj.Quantity);
        oAbandoned_Inventory = oObj.Abandoned_Inventory__c == null
          ? ''
          : String.valueOf(oObj.Abandoned_Inventory__c);
      }
      String nQuantity = nObj.Quantity == null
        ? ''
        : String.valueOf(nObj.Quantity);
      String nAbandoned_Inventory = nObj.Abandoned_Inventory__c == null
        ? ''
        : String.valueOf(nObj.Abandoned_Inventory__c);
      if (
        (oQuantity != nQuantity &&
        String.isNotBlank(nObj.ChangeQuantityReason__c)) || Trigger.isInsert
      ) {
        String rs = nObj.ChangeQuantityReason__c;
        nObj.ChangeQuantityHistory__c = String.format(
          System.Label.ChangeQuantityHistory,
          new List<String>{ oQuantity, nQuantity, rs }
        );
        // before里面入立规则过不了改到
        // 已经改进 Must_Input_ChangeQuantityReason 的 valida before可以完成 ChangeQuantityReason__c = ''
        // nObj.ChangeQuantityReason__c = '';
      }
 
      if (oAbandoned_Inventory != nAbandoned_Inventory || Trigger.isInsert) {
        String rs = nObj.Giveup_Return__c;
        nObj.ChangeAbandoned_InventoryHistory__c = String.format(
          System.Label.ChangeAbandoned_InventoryHistory,
          new List<String>{ oAbandoned_Inventory, nAbandoned_Inventory, rs }
        );
      }
    }
  }
 
  //// かならず afterUpdate
  private void cleanChangeQuantityReason() {
    // TODO 更新自己table 原则需要Static的Class变量(因为会有复数的Method去更新自己的)
    List<Asset> assList = new List<Asset>();
    for (Asset nObj : newList) {
      if (String.isBlank(nObj.ChangeQuantityReason__c) == false) {
        assList.add(new Asset(Id = nObj.Id, ChangeQuantityReason__c = ''));
      }
    }
    if (!assList.isEmpty()) {
      update assList;
    }
  }
 
  // afterUpdate
  // 清理字段「待废弃数(丢失/盘亏)修改理由」
  private void cleanGiveupReturnReason() {
    List<Asset> assList = new List<Asset>();
    for (Asset nObj : newList) {
      if (String.isBlank(nObj.Giveup_Return__c) == false) {
        assList.add(new Asset(Id = nObj.Id, Giveup_Return__c = ''));
      }
    }
    if (!assList.isEmpty()) {
      update assList;
    }
  }
 
  // かならず after, oObj.Id と nObj.Id を使うため
  // Last_Reserve_RAES_Detail__c (个体管理) のlink 変わった場合、
  // Fixture_OneToOne_Link__c より Asset に積み上げしている数字も連動になる、Fixture_OneToOne_Link__c を空更新
  // 更新項目Fixture_OneToOne_Link__c.In_wh_Fu_Shu_Pin_You_Xiao_Ku_Cun__c = Fixture_OneToOne_Link__c.In_wh_Fu_Shu_Pin_You_Xiao_Ku_Cun_F__c
  private void mainAssetUpdateed_OneToOneRecord() {
    Set<Id> aSetIdSet = new Set<Id>();
    System.debug(LoggingLevel.INFO, '*** mainAssetUpdateed_OneToOneRecord: ');
    for (Integer i = 0; i < newList.size(); i++) {
      Asset nObj = newList[i];
      Asset oObj = oldList[i];
      if (
        oObj.Last_Reserve_RAES_Detail__c != nObj.Last_Reserve_RAES_Detail__c
      ) {
        if (String.isNotBlank(oObj.Id)) {
          aSetIdSet.add(oObj.Id);
        }
        if (String.isNotBlank(nObj.Id)) {
          aSetIdSet.add(nObj.Id);
        }
      }
    }
    if (!aSetIdSet.isEmpty()) {
      List<Fixture_OneToOne_Link__c> oneToOneList = [
        SELECT Id
        FROM Fixture_OneToOne_Link__c
        WHERE Main_Asset__c IN :aSetIdSet
      ];
      if (!oneToOneList.isEmpty()) {
        update oneToOneList;
      }
    }
  }
 
  // * 不会有暂定分配后再拿去修理的备品走重新设置暂定分配的逻辑(queueRedistribution方法)
  // * 理由:明细暂定分配的时候创建修理的话会报以下错误
  // * 借出_分配_数 不能大于 设备的总数 ------> Asset 入力规则 You_Xiao_Ku_Cun_chk
  // * 暂定分配-1
  // * 修理-1
  // * 数量1
  // * 1-1-1 = -1
  // *
  // * 如果暂定分配想修理的话分配暂定分配的那一条明细
  // * 然后再出出库前检测的时候选择NG修理
  // かならず after
  private void queueRedistribution() {
    if (queueRaesdMap == null) {
      queueRaesdMap = new Map<String, List<Rental_Apply_Equipment_Set_Detail__c>>();
    }
    Map<String, Set<Id>> modelNoAssetIdMap = new Map<String, Set<Id>>();
    Set<Id> raesdIdSet = new Set<Id>();
    // List<Rental_Apply_Equipment_Set_Detail__c> updList = new List<Rental_Apply_Equipment_Set_Detail__c>();
    String whkey = '';
    for (Asset nObj : newList) {
      //ToDo現在排队できるのは主体だけなので,今後个体管理の附属品も排队できるの場合があったらこのIFぶんを直す必要があります
      if (
        !(nObj.Loaner_accsessary__c == false &&
        nObj.Asset_Owner__c == 'Olympus' &&
        nObj.Equipment_Type__c != '检测用备品' &&
        nObj.Delete_Flag__c == false &&
        nObj.You_Xiao_Ku_Cun__c > 0 &&
        nObj.Freeze_sign_Abandoned_Flag__c == false)
      ) {
        continue;
      }
 
      String key = nObj.Fixture_Model_No_F__c;
      //暂定分配不看存放地 OLY_OCM-722 恢复存放地的条件
      if (String.isNotBlank(nObj.Internal_asset_location__c)) {
        key += nObj.Internal_asset_location__c;
      }
 
      if (String.isNotBlank(nObj.Salesdepartment__c)) {
        key += nObj.Salesdepartment__c;
      }
      if (String.isNotBlank(nObj.Equipment_Type__c)) {
        key += nObj.Equipment_Type__c;
      }
      if (String.isNotBlank(nObj.Product_category__c)) {
        key += nObj.Product_category__c;
      }
 
      System.debug(LoggingLevel.INFO, '*** key: ' + key);
      //有新的Asset的时候 暂定分配
      // You_Xiao_Ku_Cun__c > 0 在上面已经做了判断
      if (
        Trigger.isInsert && String.isBlank(nObj.Last_Reserve_RAES_Detail__c)
      ) {
        if (String.isBlank(nObj.Fixture_Model_No_F__c) == false) {
          // modelNoAssetIdMap.put(nObj.Fixture_Model_No_F__c, nObj.Id);
          if (modelNoAssetIdMap.containsKey(key) == false) {
            modelNoAssetIdMap.put(key, new Set<Id>());
          }
          modelNoAssetIdMap.get(key).add(nObj.Id);
        }
      }
      //当主体参照的Asset的Last断开的时候重新寻找暂定分配
      //ToDo状況確認
      /*
            || (nObj.Asset_Owner__c != oObj.Asset_Owner__c && nObj.Asset_Owner__c == 'Olympus')
            || (nObj.Equipment_Type__c != oObj.Equipment_Type__c && oObj.Equipment_Type__c == '检测用备品')
            || (nObj.Delete_Flag__c != oObj.Delete_Flag__c && nObj.Delete_Flag__c == false)
            || (nObj.Freeze_sign__c != oObj.Freeze_sign__c && nObj.Delete_Flag__c == false)
            */
      // You_Xiao_Ku_Cun__c > 0 在上面已经做了判断
      else {
        Asset oObj = oldMap.get(nObj.Id);
        if (
          nObj.Loaner_accsessary__c == false &&
          String.isBlank(nObj.Last_Reserve_RAES_Detail__c) &&
          (nObj.Last_Reserve_RAES_Detail__c !=
          oObj.Last_Reserve_RAES_Detail__c ||
          (nObj.Asset_Owner__c != oObj.Asset_Owner__c &&
          nObj.Asset_Owner__c == 'Olympus') ||
          //备品存放地 OLY_OCM-722 恢复存放地的条件
          (nObj.Internal_asset_location__c !=
          oObj.Internal_asset_location__c) ||
          //备品分类并且不是 检测用备品
          (nObj.Equipment_Type__c != oObj.Equipment_Type__c &&
          nObj.Equipment_Type__c != '检测用备品') ||
          //销售本部
          (nObj.Salesdepartment__c != oObj.Salesdepartment__c) ||
          //产品分类(GI/SP)
          (nObj.Product_category__c != oObj.Product_category__c) ||
          //备品配套明细型号
          (nObj.Fixture_Model_No_F__c != oObj.Fixture_Model_No_F__c) ||
          (nObj.Delete_Flag__c != oObj.Delete_Flag__c &&
          nObj.Delete_Flag__c == true) ||
          (nObj.Freeze_sign_Abandoned_Flag__c !=
          oObj.Freeze_sign_Abandoned_Flag__c &&
          nObj.Freeze_sign_Abandoned_Flag__c == false))
        ) {
          if (String.isBlank(nObj.Fixture_Model_No_F__c) == false) {
            if (modelNoAssetIdMap.containsKey(key) == false) {
              modelNoAssetIdMap.put(key, new Set<Id>());
            }
            modelNoAssetIdMap.get(key).add(nObj.Id);
          }
          if (String.isNotBlank(oObj.Last_Reserve_RAES_Detail__c)) {
            raesdIdSet.add(oObj.Last_Reserve_RAES_Detail__c);
          }
        }
      }
    }
    if (modelNoAssetIdMap.isEmpty()) {
      return;
    }
    System.debug(
      LoggingLevel.INFO,
      '*** raesdIdSet: ' + JSON.serialize(raesdIdSet)
    );
    //modified by denny 2021-11-17
    List<String> keyList = new List<String>();
    keyList.addAll(modelNoAssetIdMap.keySet());
    System.debug(LoggingLevel.INFO, '*** keyList: ' + keyList);
    List<Rental_Apply_Sequence__c> targetSequence = [
      SELECT
        Id,
        Apply_Set_Detail__c,
        Apply_Set_Detail_ExternalKey__c,
        Demo_Purpose2__c,
        Equipment_Type__c,
        ExternalKey__c,
        Fixture_Model_No__c,
        Internal_asset_location__c,
        Invalid_Flag__c,
        Product_category__c,
        Rental_Apply__c,
        Series_No__c,
        Series_Unequal_Queue_Flag__c,
        Salesdepartment__c
      FROM Rental_Apply_Sequence__c
      WHERE
        Series_No__c > 0
        AND Invalid_Flag__c = FALSE
        AND Apply_Set_Detail__c NOT IN :raesdIdSet
        AND ExternalKey__c IN :keyList
        AND Apply_Set_Detail__r.Cancel_Select__c = FALSE
      ORDER BY Series_No__c
    ];
    System.debug(LoggingLevel.INFO, '*** targetSequence: ' + targetSequence);
    Map<String, List<Rental_Apply_Sequence__c>> sequenceMap = new Map<String, List<Rental_Apply_Sequence__c>>();
    for (Rental_Apply_Sequence__c sequeuece : targetSequence) {
      if (!sequenceMap.containsKey(sequeuece.Externalkey__c)) {
        sequenceMap.put(
          sequeuece.Externalkey__c,
          new List<Rental_Apply_Sequence__c>()
        );
      }
      sequenceMap.get(sequeuece.Externalkey__c).add(sequeuece);
    }
    Map<String, Rental_Apply_Equipment_Set_Detail__c> updateMap = new Map<String, Rental_Apply_Equipment_Set_Detail__c>();
    for (String key : sequenceMap.keySet()) {
      for (Rental_Apply_Sequence__c sequeuece : sequenceMap.get(key)) {
        if (!updateMap.containsKey(sequeuece.Apply_Set_Detail__c)) {
          System.debug(
            LoggingLevel.INFO,
            '*** modelNoAssetIdMap: ' + JSON.serialize(modelNoAssetIdMap)
          );
          if (modelNoAssetIdMap.containsKey(key)) {
            List<Id> assIdList = new List<Id>();
            assIdList.addAll(modelNoAssetIdMap.get(key));
            String assIdbk = assIdList.get(0);
            Rental_Apply_Equipment_Set_Detail__c raesd = new Rental_Apply_Equipment_Set_Detail__c();
            raesd.Id = sequeuece.Apply_Set_Detail__c;
            raesd.Asset__c = assIdbk;
            System.debug('raesd.Asset__c' + raesd.Asset__c);
            raesd.Queue_Number__c = 0; // 暂定分配
            updateMap.put(raesd.Id, raesd);
 
            modelNoAssetIdMap.get(key).remove(assIdbk);
            if (modelNoAssetIdMap.get(key).isEmpty()) {
              modelNoAssetIdMap.remove(key);
            }
            System.debug(
              LoggingLevel.INFO,
              '*** modelNoAssetIdMap: ' + JSON.serialize(modelNoAssetIdMap)
            );
          }
        }
      }
    }
    System.debug(
      LoggingLevel.INFO,
      '*** updateMap.values(): ' + JSON.serialize(updateMap.values())
    );
    update updateMap.values();
 
    // Fixture_Model_No_F__c を見ることができない、データがおおいので。
    // Fixture_Set_Detail__r.Fixture_Model_No_F__c をみるか Fixture_Model_No_text__c をみるか
    //     whkey += ' (';
    //     whkey += '   ((Fixture_Set_Detail__c != null and Fixture_Set_Detail__r.Product2__r.Fixture_Model_No_T__c =\'' + String.escapeSingleQuotes(nObj.Fixture_Model_No_F__c) + '\')';
    //     whkey += '      OR Fixture_Model_No_text__c =\'' + String.escapeSingleQuotes(nObj.Fixture_Model_No_F__c) + '\'';
    //     whkey += '   )';
 
    //     String wher = '';
    //     //暂定分配不看存放地 OLY_OCM-722 恢复存放地的条件
    //     if (String.isNotBlank(nObj.Internal_asset_location__c)) {
    //         wher += ' and Internal_asset_location_before__c =\'' + String.escapeSingleQuotes(nObj.Internal_asset_location__c) + '\'';
    //     }
 
    //     if (String.isNotBlank(nObj.Salesdepartment__c)) {
    //         wher += ' and Salesdepartment_before__c =\'' + String.escapeSingleQuotes(nObj.Salesdepartment__c) + '\'';
    //     }
 
    //     if (String.isNotBlank(nObj.Product_category__c)) {
    //         wher += ' and Product_category_text__c =\'' + String.escapeSingleQuotes(nObj.Product_category__c) + '\'';
    //     }
 
    //     if (String.isNotBlank(nObj.Equipment_Type__c)) {
    //         wher += ' and Equipment_Type_text__c =\'' + String.escapeSingleQuotes(nObj.Equipment_Type__c) + '\'';
    //     }
 
    //     whkey += wher + ' ) OR';
    // }
 
    // if (String.isNotBlank(whkey)) {
    //     whkey = '( ' + whkey.removeEnd('OR') + ')';
    // }
 
    // String soql = 'SELECT Fixture_Model_No_F__c, Substitute_flag__c, Asset__c,'
    //             + ' Queue_Number__c, Fixture_Model_No_text__c, Salesdepartment_before__c,'
    //             + ' Product_category_text__c, Equipment_Type_text__c, Internal_asset_location_before__c'
    //             + ' FROM Rental_Apply_Equipment_Set_Detail__c'
    //             + ' where Id != :raesdIdSet and '
    //             +  whkey
    //             + ' and Queue_Number__c > 0'
    //             + ' and Cancel_Select__c = false'
    //             + ' order by Queue_Number__c ASC';
    // System.debug('whkey' + whkey);
    // System.debug('soql' + soql);
    // List<Rental_Apply_Equipment_Set_Detail__c> targetRaesd = Database.query(soql);
    // System.debug('targetRaesd' + targetRaesd);
    // for (Rental_Apply_Equipment_Set_Detail__c raesd : targetRaesd) {
    //     // TODO Fixture_Set_Detail__c に チェック追加 Rental_Apply_Equipment_Set_Detail__c 新数据, 有 没有分配(分配时间) 的话, 不能 Delete Fixture_Set_Detail__c
    //     String key = '';
    //     if (raesd.Substitute_flag__c) {
    //         key = raesd.Fixture_Model_No_text__c;
    //     } else {
    //         key = raesd.Fixture_Model_No_F__c;
    //     }
    //     //暂定分配不看存放地 OLY_OCM-722 恢复存放地的条件
    //     if (String.isNotBlank(raesd.Internal_asset_location_before__c)) {
    //         key += '_' + raesd.Internal_asset_location_before__c;
    //     }
 
    //     if (String.isNotBlank(raesd.Salesdepartment_before__c)) {
    //         key += '_' + raesd.Salesdepartment_before__c;
    //     }
 
    //     if (String.isNotBlank(raesd.Product_category_text__c)) {
    //         key += '_' + raesd.Product_category_text__c;
    //     }
 
    //     if (String.isNotBlank(raesd.Equipment_Type_text__c)) {
    //         key += '_' + raesd.Equipment_Type_text__c;
    //     }
    //     if (queueRaesdMap.containsKey(key) == false) {
    //         queueRaesdMap.put(key, new List<Rental_Apply_Equipment_Set_Detail__c>());
    //     }
    //     queueRaesdMap.get(key).add(raesd);
    // }
 
    // System.debug('queueRaesdMap' + queueRaesdMap);
    // System.debug('modelNoAssetIdMap' + modelNoAssetIdMap);
 
    // List<Rental_Apply_Equipment_Set_Detail__c> uplist = new List<Rental_Apply_Equipment_Set_Detail__c>();
    // for (String raesdkey : queueRaesdMap.keySet()) {
    //     for (Rental_Apply_Equipment_Set_Detail__c raesd : queueRaesdMap.get(raesdkey)) {
    //         System.debug(raesdkey);
    //         // 这里的queueRaesdMap在用完后没有清空,导致与最新查出的targetRaesd不一致
    //         // 担心直接清空会造成其它问题,所以加or来保证明细的Asset__c只会被更新一次
    //         if (modelNoAssetIdMap.containsKey(raesdkey) == false || String.isNotBlank(raesd.Asset__c)) {
    //             // 基本発生しない、queueRaesdMap <= modelNoAssetIdMap
    //             continue;
    //         }
    //         Id assIdbk;
    //         for (Id assId : modelNoAssetIdMap.get(raesdkey)) {
    //             assIdbk = assId;
    //             raesd.Asset__c = assId;
    //             System.debug('raesd.Asset__c' + raesd.Asset__c);
    //             raesd.Queue_Number__c = 0;      // 暂定分配
    //             uplist.add(raesd);
    //             System.debug('raesd Idis' + raesd.Id);
    //             break;
    //         }
    //         modelNoAssetIdMap.get(raesdkey).remove(assIdbk);
    //         if (modelNoAssetIdMap.get(raesdkey).isEmpty()) {
    //             modelNoAssetIdMap.remove(raesdkey);
    //         }
    //     }
    // }
 
    // //排队更新
    // if (!uplist.isEmpty()) {
    //     update uplist;
    // }
  }
 
  //before 数式の値がnullになる可能性がありますのでここでも一回チェックします
  private void formulaToTextCheck() {
    List<Asset> assets = new List<Asset>();
    for (Asset nObj : newList) {
      if (nObj.Fixture_Status2_text__c != nObj.Fixture_Status2__c) {
        Asset ass = new Asset(Id = nObj.Id);
        ass.Fixture_Status2_text__c = nObj.Fixture_Status2__c;
        assets.add(ass);
      }
    }
    if (!assets.isEmpty()) {
      update assets;
    }
  }
 
  private void checkOneToOneLink() {
    Set<Id> otoIds = new Set<Id>(); // 待删除link的Id
    Set<Id> assetIds = new Set<Id>();
    Set<String> centers = new Set<String>{
      '北京 备品中心',
      '上海 备品中心',
      '广州 备品中心'
    };
    for (Asset nObj : newList) {
      //待废弃,废弃,和数量0的备品需要断开一对一link (目前只处理个体管理的)
      if (
        (nObj.Fixture_Status__c ==
        FixtureUtil.assetFixtureStatusMap.get(
          FixtureUtil.AssetFixtureStatus.Fei_Qi.ordinal()
        ) ||
        nObj.Fixture_Status__c ==
        FixtureUtil.assetFixtureStatusMap.get(
          FixtureUtil.AssetFixtureStatus.Dai_Fei_Qi.ordinal()
        ) ||
        nObj.Quantity == 0) &&
        nObj.Manage_type__c ==
        FixtureUtil.managetypeMap.get(FixtureUtil.Managetype.Ge_Ti_Guan_Li)
      ) {
        //是一对一主体或者是一对一个体附属品
        if (
          nObj.Main_OneToOne__c == true ||
          nObj.Fixture_OneToOne_Link__c <> null
        ) {
          if (centers.contains(nObj.Internal_asset_location__c)) {
            assetIds.add(nObj.Id);
          }
        }
      }
    }
 
    if (assetIds.size() > 0) {
      Map<Id, Fixture_OneToOne_Link__c> linkMap = new Map<Id, Fixture_OneToOne_Link__c>(
        [
          SELECT Id
          FROM Fixture_OneToOne_Link__c
          WHERE Main_Asset__c IN :assetIds OR Accessory_Asset__c IN :assetIds
        ]
      );
      if (!linkMap.isEmpty()) {
        delete linkMap.values();
      }
    }
  }
 
  /**
   * 动态设定 Asset.AccountId (备品共享_杭州_华东营业本部)
   * Condition:
   *    - before insert, before update
   *    - 确认字段变化 (保有设备的备品存放地(Internal_asset_location__c)+所在地区(本部)(Salesdepartment__c))
   *    - Salesdepartment__c IN ('1.华北营业本部','2.东北营业本部','3.西北营业本部','4.华东营业本部','5.华南营业本部','6.西南营业本部')
   *    - Asset 是 办事处备品
   * Execute:
   *    - 找 Label: OCM_Management_Province_Mapping, 的 办事处, 设定 AccountId
   *    - 没有找的话, 不更新AccountId, 自动做 Account, Group, ApexShare
   */
  private void beforeSetAccountId() {
    Set<String> targetDepts = new Set<String>{
      '1.华北营业本部',
      '2.东北营业本部',
      '3.西北营业本部',
      '4.华东营业本部',
      '5.华南营业本部',
      '6.西南营业本部'
    };
    Set<String> targetCenters = new Set<String>{
      '北京 备品中心',
      '上海 备品中心',
      '广州 备品中心'
    };
    if (Test.isRunningTest() && testTargetDepts != null) {
      targetDepts = testTargetDepts;
    }
    // 存放地 → 省 的 Map
    Map<String, String> targetProvs = AssetWebService.getOcmMgtProvMap();
 
    // 收集对象 Asset
    Map<Asset, String> assetAccShareNameMap = new Map<Asset, String>();
    Datetime execNow = System.now();
    for (Asset nObj : newList) {
      Asset oObj = (null == this.oldMap) ? null : this.oldMap.get(nObj.Id);
 
      // 作成, 确认字段有没有变化
      if (
        Trigger.isInsert ||
        (oObj != null &&
        (oObj.RecordTypeId != nObj.RecordTypeId ||
        oObj.Asset_loaner_category__c != nObj.Asset_loaner_category__c ||
        oObj.AssetManageConfirm__c != nObj.AssetManageConfirm__c ||
        oObj.Internal_asset_location__c != nObj.Internal_asset_location__c ||
        oObj.Salesdepartment__c != nObj.Salesdepartment__c ||
        oObj.OlympusAccShareName__c != nObj.OlympusAccShareName__c) &&
        (targetCenters.contains(nObj.Internal_asset_location__c) ||
        targetProvs.containsKey(nObj.Internal_asset_location__c)) &&
        !nObj.TransferToOther__c)
      ) {
        // 是不是备品的确认
        if (
          System.Label.Asset_RecordType == nObj.RecordTypeId &&
          true == nObj.AssetManageConfirm__c &&
          nObj.Asset_loaner_category__c != '耗材'
        ) {
          // 办事处备品 → 动态设定 Asset.AccountId 的対象
          if (
            targetProvs.containsKey(nObj.Internal_asset_location__c) &&
            targetDepts.contains(nObj.Salesdepartment__c)
          ) {
            String accShareName =
              '备品共享_' +
              targetProvs.get(nObj.Internal_asset_location__c) +
              '_' +
              nObj.Salesdepartment__c.right(6);
            nObj.OlympusAccShareName__c = accShareName;
            assetAccShareNameMap.put(nObj, accShareName);
          } else {
            if (AssetHandler.Account_Asset_Id == null) {
              // Static 只会执行一遍
              AssetHandler.Account_Asset_Id = [
                SELECT Id
                FROM Account
                WHERE AgentCode_Ext__c = :System.Label.Account_Asset
              ]
              .Id;
            }
            nObj.OlympusAccShareName__c = '';
            nObj.AccountId = AssetHandler.Account_Asset_Id;
          }
        } else {
          // 更新成 不是备品 的时候, 更新的程序里 要 care AccountId
          nObj.OlympusAccShareName__c = '';
        }
      }
    }
 
    // check 是不是 accShareName 都有
    Set<String> insertAccShareNameSet = new Set<String>();
    if (assetAccShareNameMap.size() > 0) {
      Map<String, Id> accShareId = new Map<String, Id>();
      for (Account accShare : [
        SELECT Id, Department_Name__c
        FROM Account
        WHERE
          RecordTypeId = :System.Label.Department_OTH
          AND Department_Name__c IN :assetAccShareNameMap.values()
      ]) {
        accShareId.put(accShare.Department_Name__c, accShare.Id);
      }
 
      // assetAccShareNameMap 的 Key会有变化
      // 这个 for loop后 就不能使用 assetAccShareNameMap.get(XXXX) 了
      for (Asset nObj : assetAccShareNameMap.keySet()) {
        String accShareName = assetAccShareNameMap.get(nObj);
        if (accShareId.containsKey(accShareName)) {
          // 找到 Account 设定 AccountId, "Olympus社内 其他 备品" => "Olympus社内 其他 备品共享_XXX"
          nObj.AccountId = accShareId.get(accShareName);
        } else {
          // 找不到 AccountId, 新建 Account, Group, ApexShare
          insertAccShareNameSet.add(accShareName);
        }
      }
    }
    if (insertAccShareNameSet.size() > 0) {
      // AssetHandler.futureInsertAccShare(JSON.serialize(insertAccShareNameSet), execNow);
      System.enqueueJob(
        new MyQueueableClass(JSON.serialize(insertAccShareNameSet), execNow)
      );
    }
  }
 
  /**
   * 新建 备品共享_XXX 客户数据
   * @param insertAccShareNameJson Json String of List<String> ["备品共享_XXX", "备品共享_YYY"]
   */
  private static void insertAccShare(
    String insertAccShareNameJson,
    Datetime execNow
  ) {
    Set<String> insertAccShareNameSet = (Set<String>) JSON.deserialize(
      insertAccShareNameJson,
      Set<String>.class
    );
    if (insertAccShareNameSet.isEmpty()) {
      return;
    }
 
    //  Olympus社内 其他
    List<Account> olympusAccount_OtherDC;
    try {
      olympusAccount_OtherDC = [
        SELECT Id, ParentId
        FROM Account
        WHERE
          Parent.AgentCode_Ext__c = '9999999'
          AND Department_Class_Name__c = '其他'
        FOR UPDATE
      ];
    } catch (Exception e) {
      System.enqueueJob(new MyQueueableClass(insertAccShareNameJson, execNow));
      return;
    }
 
    List<Account> isInsertedList = [
      SELECT Id, Department_Name__c
      FROM Account
      WHERE
        ParentId = :olympusAccount_OtherDC[0].Id
        AND Department_Name__c IN :insertAccShareNameSet
    ];
    if (isInsertedList.size() > 0) {
      Map<String, Account> insertedAccount = new Map<String, Account>();
      for (Account insertedAcc : isInsertedList) {
        insertedAccount.put(insertedAcc.Department_Name__c, insertedAcc);
        insertAccShareNameSet.remove(insertedAcc.Department_Name__c);
      }
      // Update Asset.AccountId
      AssetHandler.updateAssetAccount(insertedAccount, execNow);
    }
 
    if (insertAccShareNameSet.size() > 0) {
      Map<String, Account> insertAccount = new Map<String, Account>();
      for (String accShareName : insertAccShareNameSet) {
        insertAccount.put(
          accShareName,
          new Account(
            Name = '*',
            Hospital__c = olympusAccount_OtherDC[0].ParentId,
            ParentId = olympusAccount_OtherDC[0].Id,
            Department_Class__c = olympusAccount_OtherDC[0].Id,
            Other_dept_category__c = '其他科室',
            Department_Name__c = accShareName,
            OwnerId = System.Label.Batch_User_Id,
            RecordTypeId = System.Label.Department_OTH
          )
        );
      }
      AssetHandler.insertAccGrantShare(insertAccount, execNow);
    }
  }
 
  private static void insertAccGrantShare(
    Map<String, Account> insertAccountMap,
    Datetime execNow
  ) {
    if (insertAccountMap.isEmpty()) {
      return;
    }
    Set<String> accShareNameSet = insertAccountMap.keySet();
    // insert Account的时候, 跳过 NFM001
    // OLY_OCM-1230 需要执行NFM001Trigger
    // ControllerUtil.EscapeNFM001Trigger = true;
    insert insertAccountMap.values();
 
    Map<String, Group> insertGroup = new Map<String, Group>();
    Map<String, Group> groupNameMap = new Map<String, Group>();
    for (String accShareName : accShareNameSet) {
      insertGroup.put(accShareName, new Group(Name = accShareName));
    }
 
    // Check 有没有 Group
    for (Group grp : [
      SELECT Id, Name
      FROM Group
      WHERE Type = 'Regular' AND Name IN :accShareNameSet
    ]) {
      // 已经有Group 的话 不用 insert
      insertGroup.remove(grp.Name);
      groupNameMap.put(grp.Name, grp);
    }
    if (insertGroup.size() > 0) {
      insert insertGroup.values();
      // groupNameMap 含 所有 accShareNameSet 的 Group, 并且 都有 Id
      groupNameMap.putAll(insertGroup);
    }
 
    // 赋 Account 共享权限
    List<AccountShare> insertShareList = new List<AccountShare>();
    for (String accShareName : accShareNameSet) {
      insertShareList.add(
        new AccountShare(
          UserOrGroupId = groupNameMap.get(accShareName).Id,
          AccountId = insertAccountMap.get(accShareName).Id,
          AccountAccessLevel = 'Edit',
          OpportunityAccessLevel = 'None'
        )
      );
    }
    insert insertShareList;
    // Update Asset.AccountId
    AssetHandler.updateAssetAccount(insertAccountMap, execNow);
  }
 
  private static void updateAssetAccount(
    Map<String, Account> accShareNameAccountMap,
    Datetime execNow
  ) {
    if (accShareNameAccountMap.isEmpty()) {
      return;
    }
    Set<String> accShareNameSet = accShareNameAccountMap.keySet();
 
    List<Asset> updAssetAccount = new List<Asset>();
    for (Asset nObj : [
      SELECT Id, OlympusAccShareName__c, AccountId
      FROM Asset
      WHERE
        OlympusAccShareSameFlag__c = '0'
        AND OlympusAccShareName__c IN :accShareNameSet
        AND LastModifiedDate >= :execNow
    ]) {
      nObj.AccountId = accShareNameAccountMap.get(nObj.OlympusAccShareName__c)
        .Id;
      updAssetAccount.add(nObj);
    }
    update updAssetAccount;
  }
 
  @TestVisible
  class MyQueueableClass implements Queueable {
    String insertAccShareNameJson;
    Datetime execNow;
 
    public MyQueueableClass(String insertAccShareNameJson, Datetime execNow) {
      this.insertAccShareNameJson = insertAccShareNameJson;
      this.execNow = execNow;
    }
 
    public void execute(QueueableContext context) {
      AssetHandler.insertAccShare(insertAccShareNameJson, execNow);
    }
  }
}