19626
2023-07-12 fbd4bea7bd57b4d4a33cb9ed0ebc15d9bf6551c0
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
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
global without sharing class ControllerUtil {
    // トリガ実行回数を制御する、一回目false、二回目(workflow対応用)true
    //public static Boolean XinEventOppotunityPileUpExeFlg = false;
    // 積み上げをIsScheduledフラグ設定の後に実行
    public static Boolean EventOpportunityPileUpExeFlg = false;
    // EventC⇒Event処理後、逆更新をスルー用
    public static Boolean NotUpdEventCFlg = false;
    // 積み上げ処理後、トリガをスルー用
    public static Boolean EscapeNFM001Trigger = false;
    public static Boolean EscapeNFM001AgencyContractTrigger = false;
    public static Boolean EscapeNFM007Trigger = false;
    public static Boolean EscapeOpportunityBefUpdTrigger = false;
    public static Boolean EscapeOpportunityHpDeptUpdTrigger = false;
    public static Boolean EscapeSyncOpportunityTrigger = false;
    public static Boolean EscapeMaintenanceContractAfterUpdateTrigger = false;
    public static Boolean EscapeSyncProduct2Trigger = false;
    
    // 商談の更新不可項目リスト
    public static List<String> oppColumnList = System.Label.Opportunity_Columns.split(',');
    
    // 削除対象のEvent
    public static Set<Id> delEventIdSet = new Set<Id>();     
 
    // 100日定数
    public static Integer ReportDayRange = 100;
    
    // 商談レコードタイプ
    public static String[] oppRecordTypeDevNames = new String[] {'Opportunity'};
    
    public static final String chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
    
 
    public ControllerUtil() {
        Integer i = 0;
        
    }
    @AuraEnabled
    WebService static String selectCommonSequence(String valueField, String formatField) {
        Boolean insertNew = false;
        //取得共通採番序列
        String soql = 'select id,' + valueField + ',' + formatField + ' from Common_Sequence__c for update';
        List<Common_Sequence__c> csList = Database.query(soql);
        if (csList.size() == 0) {
            //共通採番序列没数据,新建
            Common_Sequence__c newCS = new Common_Sequence__c();
            newCS.Name = '共通採番序列';
            newCS.EvaluationPDF_NextValue__c = 1;
            insert newCS;
            insertNew = true;
            //再取得共通採番序列
            csList = Database.query(soql);
        }
        Common_Sequence__c cs = csList[0];
        //採番编码
        String format = String.valueOf(cs.get(formatField));
        //下个採番值
        Decimal nextValue = Decimal.valueOf(String.valueOf(cs.get(valueField)));
        //採番
        nextValue += 1;
        cs.put(valueField, nextValue);
        update csList;
        //返回採番编码
        return format;
    }
    
    public static String generateRandomStr(Integer len) {
        String randStr = '';
        while (randStr.length() < len) {
           Integer idx = Math.mod(Math.abs(Crypto.getRandomInteger()), chars.length());
           randStr += chars.substring(idx, idx+1);
        }
        return randStr;
    }
    
    public static List<Document> getPdfBlobForPreview(String docId) {
        return [select Id, Name, Body, CreatedDate from Document where Id = :docId];
    }
    
    public static List<SMARM__c> getSmarmByUser(Map<String, Schema.SObjectField> fieldMap, String fromUserId, String toUserId) {
        String sql = 'select ';
        String fields = '';
        for (String field : fieldMap.keySet()) {
            if (fields.length() > 0) {
                fields += ', '; 
            }
            fields += field;
        }
        sql += fields;
        sql += ' from SMARM__c where Review_Practitioner__c = :fromUserId and Review_Target__c = :toUserId and (Status__c = \'草案中\' or Status__c = \'Delete\')';
        List<SMARM__c> sList = Database.query(sql);
        return sList;
    }
    
    public static void createDocForEmail(List<Document> docList) {
        Folder f = [select Id from Folder where DeveloperName = 'EmailImgFolder'];
        for (Document doc : docList) {
            doc.FolderId = f.Id;
            doc.IsPublic = true;
        }
        insert docList;
    }
    
    public static List<SMARM__c> getSmarmById(String sql) {
        return Database.query(sql);
    }
    
    public static List<Attachment> getSmarmAtts(String smarmId) {
        return [select Id, Name, Body from Attachment where ParentId = :smarmId order by Name];
    }
    
    public static void insertAttachments(List<Attachment> atts) {
        if (atts.size() > 0) insert atts;
    }
    
    public static void updateAttachments(List<Attachment> atts) {
        if (atts.size() > 0) update atts;
    }
    
    public static void deleteAttachments(List<Attachment> atts) {
        if (atts.size() > 0) delete atts;
    }
 
    public static List<ContentDocument> getSmarmAttsLightning(String smarmId) {
        List<ContentDocumentLink> cdlList = [SELECT ContentDocumentId
                                                   FROM ContentDocumentLink
                                                   WHERE LinkedEntityId = :smarmId];
            List<ID> fileIDs = new List<ID>();
            for (ContentDocumentLink docLink : cdlList) {
                fileIDs.add(docLink.ContentDocumentId);
            }        
        return [SELECT Title,OwnerId from ContentDocument WHERE id IN :fileIDs];
    }
 
    // public static void insertAttachmentsLightning(List<ContentDocument> atts) {
    //     if (atts.size() > 0) insert atts;
    // }
 
    public static void updateAttachmentsLightning(List<ContentDocument> atts) {
        if (atts.size() > 0) update atts;
    }
 
    public static void deleteAttachmentsLightning(List<ContentDocument> atts) {
        if (atts.size() > 0) delete atts;
    }
    
    public static void upsertSMARM(SMARM__c smarm) {
        upsert smarm;
    }
    
    public static void insertSMARMShare(List<SObject> smarmShare) {
        insert smarmShare;
    }
    
    public static List<Account> selectAccountForTrigger(List<String> accIds) {
        return [Select Id, Name, Management_Code__c, OwnerId, ParentId, Parent.ParentId,Parent.Parent.Name, RecordTypeId from Account where Id IN :accIds];
    }
    public static Map<Id, Contact> selectContactAccountForTrigger(List<Id> contactIds) {
        return new Map<Id, Contact>([Select Id, AccountId, Account.ParentId, Account.Parent.ParentId, Account.RecordTypeId from Contact where Id IN :contactIds]);
    }
    public static list<Contact> selectContactForCampaignMember(Set<Id> contactIds) {
        return [Select Id, campaign__c,campaign__r.Lesson_Type__c, campaign__r.TrainingType__c from Contact where Id IN :contactIds];
    }
    public static List<Contact> selectDummyContact() {
        return [select id, Email from Contact where email <> null limit 1];
    }
    
    public static List<Account> selectBossMailAddr(List<String> accIds) {
        return [select Id, Parent.Boss__r.Email, Parent.Sub_Boss__r.Email, Parent.Boss__r.Name, Parent.Sub_Boss__r.Name from Account where Id in : accIds];
    }
    
    public static List<Event> eventSelectById(String id){
        List<Event> eParamList = [select id, ActivityDate, OwnerId, Subject, whatid__c, EventC_ID__c, NextEventC_ID__c, AppCdId__c, SyncCreatedDate__c, 
                                  StartDateTime, DurationInMinutes, Main_Visit_Location__c, Activity_Type2__c, IsScheduled__c, BeforeActivityDate__c,
                                  Visitor1__c, Visitor2__c, Visitor3__c, Visitor4__c, Visitor5__c, Visitor1_ID__c, Visitor2_ID__c, Visitor3_ID__c, Visitor4_ID__c, Visitor5_ID__c,
                                  Purpose_Type__c, Location, Related_Opportunity1__c, Related_Service1__c, Related_Opportunity1_ID__c, Related_Service1_ID__c,
                                  Related_Opportunity2__c, Related_Opportunity3__c, Related_Opportunity4__c, Related_Opportunity5__c,OPDPlan_Flag__c,
                                  Related_Opportunity2_ID__c, Related_Opportunity3_ID__c, Related_Opportunity4_ID__c, Related_Opportunity5_ID__c,
                                  Activity_Purpose__c, Activity_PurposeFSE__c, Activity_PurposeEscFSE__c, Purpose_TypeFSE__c, Purpose_TypeEscFSE__c
                                  from Event where id = :id];
        return eParamList;
    }
    public static List<Event> eventSelectByDate(Date whereDate, User ur){
        List<Event> calenderList = [select id, ActivityDate, OwnerId, Subject, whatid__c, EventC_ID__c, NextEventC_ID__c, AppCdId__c, SyncCreatedDate__c, 
                                  StartDateTime, DurationInMinutes, Main_Visit_Location__c, Activity_Type2__c, IsScheduled__c, BeforeActivityDate__c,
                                  Visitor1__c, Visitor2__c, Visitor3__c, Visitor4__c, Visitor5__c, Visitor1_ID__c, Visitor2_ID__c, Visitor3_ID__c, Visitor4_ID__c, Visitor5_ID__c,
                                  Purpose_Type__c, Location, Related_Opportunity1__c, Related_Service1__c, Related_Opportunity1_ID__c, Related_Service1_ID__c, WS_flg__c,
                                  Related_Opportunity2__c, Related_Opportunity3__c, Related_Opportunity4__c, Related_Opportunity5__c,OPDPlan_Flag__c,
                                  Related_Opportunity2_ID__c, Related_Opportunity3_ID__c, Related_Opportunity4_ID__c, Related_Opportunity5_ID__c,Opd_Plan__c,
                                  Activity_Purpose__c, Activity_PurposeFSE__c, Activity_PurposeEscFSE__c, Purpose_TypeFSE__c, Purpose_TypeEscFSE__c,EventStatus__c,cancelReason__c,cancelReasonOther__c,cancelReasonSelect__c,cancelReasonSelectFSE__c,delayReason__c,delayReasonOther__c,delayReasonSelect__c,delayReasonSelectFSE__c,delayToDate__c  
                                  from Event where WS_flg__c = false and ActivityDate = :whereDate and OwnerId = :ur.Id and EventStatus__c not in ('04 取消','05 延期','06 关闭','07 未执行') order by StartDateTime];
        return calenderList;
    }
    
    public static List<Daily_Report__c> reportSelectByDate(Date whereDate, String ownerId){
        List<Daily_Report__c> reportList = [select id, name, Reporter__c, Reported_Date__c, Daily_Report_Data_Type__c,
                                            Working_Time_From__c, Working_Time_To__c, Status__c, Mail_Send_Check__c,
                                            Business_Trip__c, Submit_Date_New__c, Submit_DateTime_New__c, Approved_Date__c,
                                            Approved_DateTime__c, CreatedById, Feed_Back_From_Manager__c, FeedbackManager__c,
                                            Planning_Time__c, Submission_Elapsed_Hour__c, Approval_Elapsed_Time__c,
                                            Activity_ID__c, Manager_Mail__c, Status_With_Check__c
                                            from Daily_Report__c where Reported_Date__c =:whereDate and OwnerId =:ownerId];
        return reportList;
    }
    
    public static List<RecordType> recordTypeSelectForTrainingtestResult(){
        List<RecordType> rtList = [select Id, DeveloperName from RecordType where IsActive = true and SobjectType = 'Training_test_Result__c'];
        return rtList;
    }
    
    public static List<Training_test_Result__c> trainingtestResultSelectByContactIds(Set<Id> ids){
        List<Training_test_Result__c> ttrList = [select Id, RecordType.DeveloperName, employee__c from Training_test_Result__c where employee__c in :ids];
        return ttrList;
    }
    
    public static void updateSObjectContact(List<SObject> contactList) {
        if (contactList != null && contactList.size() > 0) update contactList;
    }
    
    public static Map<Id, Contact> selectActiveUserFromContact(List<Id> contactIds) {
        return new Map<Id, Contact>([Select Id, User__c From Contact Where Id IN: contactIds and User__r.isActive = true]);
    }
 
 
    /**
     * add      2021/12/23        wangweipeng                 satrt
     * [updateFutureOds 更新ods的user__c字段]
     * @param odsEmployeeNoList [员工编码]
     * @param odsEmployeeNoMap  [员工编码对应的user Id]
     * 
     */
    @future
    public static void updateFutureOds(List<String> odsEmployeeNoList,Map<String,Id> odsEmployeeNoMap) {
        if(odsEmployeeNoList != null && odsEmployeeNoList.size() > 0){
            List<ODS__c> odsData = [select id,name,User__c,Employee_No__c from ODS__c where Employee_No__c in :odsEmployeeNoList];
            if(odsData != null && odsData.size() > 0){
                for(ODS__c ods : odsData){
                    ods.User__c = odsEmployeeNoMap.get(ods.Employee_No__c);
                }
                update odsData;
            }
        }
    }
    //add      2021/12/23        wangweipeng                 end
    
    /*
    https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dml_non_mix_sobjects.htm
    */
    @future
    public static void upsertFutureContact(List<String> userEmployeeNoList) {
        upsertFutureContactInterface(userEmployeeNoList);
    }
    //@future
    public static void upsertFutureContactInterface(List<String> userEmployeeNoList) {
 
        // 社内员工のレコードタイプ
        Id rtId = '01210000000Qtky';
        // 现有联系人
        Map<String, Contact> conMap = new Map<String, Contact>();
        // UserToContact の 変更したか にて判断した項目です
        //20220425  LLIU-CCY9TA you 查询post的地方换成 HR_Post__c
        List<User> usrList = [select Id,PositionSubsequence__c,Rank__c, Notes_File_Name__c,FirstName, LastName, Email, Mobile_Phone__c, Employee_No__c, Work_Location__c, HR_Post__c,Post__c, Job_Category__c, Hire_Date__c, Gender__c, Dept__c, Pregnant_Rest__c, Salesdepartment__c, Stay_or_not__c,IsMEBG__c, Work_Location_HR__c from User where Employee_No__c IN :userEmployeeNoList];
        List<Contact> conList = [select Id,Notes_File_Name__c, User__c, Employee_No_manual__c,Isactive__c,IsMEBG__c, Work_Location_HR__c from Contact where Employee_No_manual__c IN :userEmployeeNoList and RecordTypeId = :rtId];
        for (Contact con : conList) {
            //conMap.put(con.Employee_No_manual__c, con);
            conMap.put(con.Employee_No_manual__c.toLowerCase(), con);
        }
        system.debug('youchangtest1');
        List<Contact> upsertList = new List<Contact>();
        for (User local : usrList) {
            //update                          wangweipeng                2021/11/19  
            //不能填写诸如“医生”,“老师”,“护士”,“院长”,“某某”等头衔代称
            if(String.isNotBlank(local.FirstName)){
                if(UserInfo.getProfileId() != '00e10000000Y3o5' && UserInfo.getProfileId() != '00e10000000Y3o5'){
                    if(local.FirstName == '老师' || local.FirstName == '医生' || local.FirstName == '主任' || local.FirstName == '院长' 
                        || local.FirstName == '科长' || local.FirstName == '课长' || local.FirstName == '护士' || local.FirstName == '护士长'
                         || local.FirstName == '先生' || local.FirstName == '女士' || local.FirstName == '等等' || local.FirstName == '某'
                          || local.FirstName == '某某' || local.FirstName == '某某某' || local.FirstName == '大夫')
                    {
                        System.debug('----代码:请填写正确的名字,不能填写诸如“医生”,“老师”,“护士”,“院长”,“某某”等头衔代称!');
                        continue;
                    }
                }
            }
            //由于测试时,发现contact的员工编码为大写,user表为小写,但是新增时falseforce大小写不敏感,所以会报重复值的错误
            // 所以为了避免以上问题,把员工编码都转为小写
            if (conMap.containsKey(local.Employee_No__c.toLowerCase())) {
            //if (conMap.containsKey(local.Employee_No__c)) {
                // 更新现有联系人
                Contact tmp = conMap.get(local.Employee_No__c.toLowerCase());
                tmp.User__c = local.Id;
                tmp.FirstName = local.FirstName;
                tmp.LastName = local.LastName;
                tmp.Email = local.Email;
                tmp.Notes_File_Name__c = local.Notes_File_Name__c;//20170220新增
                tmp.MobilePhone = local.Mobile_Phone__c;
                tmp.Employee_No_manual__c = local.Employee_No__c;
                tmp.Work_Location_manual__c = local.Work_Location__c;
                //用户的工作地(人事)改变更新到联系人上 thh 2022-02-16 start
                tmp.Work_Location_HR__c = local.Work_Location_HR__c;
                //用户的工作地(人事)改变更新到联系人上 thh 2022-02-16 end
                tmp.Post_picklist__c = local.Post__c; //20220426  LLIU-CCY9TA you用户的 Post__c ,还是对应联系人
                tmp.HR_Post__c = local.HR_Post__c;//HR通用职级 //20220425  LLIU-CCY9TA you
                tmp.Job_Category_picklist__c = local.Job_Category__c;
                tmp.Hire_date_text__c = local.Hire_Date__c; 
                tmp.Gender_text__c = local.Gender__c; 
                tmp.Dept__c = local.Dept__c;
                tmp.Pregnant_Rest__c = local.Pregnant_Rest__c;
                tmp.Salesdepartment_Text__c = local.Salesdepartment__c;
                tmp.Stay_or_not__c = local.Stay_or_not__c;
                tmp.IsMEBG__c = local.IsMEBG__c;//是否MEBG
                //20220428 LLIU-CDW5ZW you start 
                tmp.PositionSubsequence__c = local.PositionSubsequence__c;
                //20220428 LLIU-CDW5ZW you end
                //20220512 you LLIU-CDW5ZW start
                tmp.Rank__c = local.Rank__c;
                //20220428 you LLIU-CDW5ZW end
                
                if(String.isNotBlank(local.Stay_or_not__c)){
                    tmp.Isactive__c = local.Stay_or_not__c == '在职' ? '有效':'无效(退休)';
                }
                upsertList.add(tmp);
                system.debug('youchangtest2'+tmp.HR_Post__c);
            } else {
                // 新做联系人
                Contact tmp = new Contact();
                tmp.RecordTypeId = rtId;
                tmp.AccountId = System.Label.Olympus_AccountID_Internal_staff;
                tmp.User__c = local.Id;
                tmp.FirstName = local.FirstName;
                tmp.LastName = local.LastName;
                tmp.Notes_File_Name__c = local.Notes_File_Name__c;//20170220新增
                tmp.Email = local.Email;
                tmp.MobilePhone = local.Mobile_Phone__c;
                tmp.Employee_No_manual__c = local.Employee_No__c;
                tmp.Work_Location_manual__c = local.Work_Location__c;
                //如果根据HR信息新建用户,则把HR信息的工作地传给用户的工作地和工作地(人事) thh 2022-02-16 start
                tmp.Work_Location_HR__c = local.Work_Location__c;
                tmp.Work_Location_picklist__c = local.Work_Location__c;
                //如果根据HR信息新建用户,则把HR信息的工作地传给用户的工作地和工作地(人事) thh 2022-02-16 end
                tmp.Post_picklist__c = local.Post__c;//20220426  LLIU-CCY9TA you用户的 Post__c ,还是对应联系人
                tmp.HR_Post__c = local.HR_Post__c;//HR通用职级 //20220425  LLIU-CCY9TA you
                tmp.Job_Category_picklist__c = local.Job_Category__c;
                tmp.Hire_date_text__c = local.Hire_Date__c; 
                tmp.Gender_text__c = local.Gender__c; 
                tmp.Dept__c = local.Dept__c;
                tmp.Pregnant_Rest__c = local.Pregnant_Rest__c;
                tmp.Salesdepartment_Text__c = local.Salesdepartment__c;
                tmp.Stay_or_not__c = local.Stay_or_not__c;
                tmp.IsMEBG__c = local.IsMEBG__c;//是否MEBG
                //20220428 LLIU-CDW5ZW you start 
                tmp.PositionSubsequence__c = local.PositionSubsequence__c;
                //20220428 LLIU-CDW5ZW you end
                //20220512 you LLIU-CDW5ZW start
                tmp.Rank__c = local.Rank__c;
                //20220428 you LLIU-CDW5ZW end
                if(String.isNotBlank(local.Stay_or_not__c)){
                    tmp.Isactive__c = '在职'.equals(local.Stay_or_not__c) ? '有效':'无效(退休)';
                }
                upsertList.add(tmp);
                system.debug('youchangtest3'+tmp.HR_Post__c);
            }
        }
        upsert upsertList;
    }
// 20220425 you 经查看 此对象应该是没有任何地方用到了,可以注释掉    
    public static void updateFutureUserByContact(List<String> userEmployeeNoList) {
        // 现有用户
        Map<String, User> usrMap = new Map<String, User>();
        // ContactToUser の 変更したか にて判断した項目です
        List<Contact> conList = [select Id, FirstName, LastName, Email, MobilePhone, Employee_No_manual__c, Work_Location_manual__c, Post_picklist__c, Job_Category_picklist__c, Hire_date_text__c, Gender_text__c, Dept__c, Pregnant_Rest__c, Stay_or_not__c from Contact where Employee_No_manual__c IN :userEmployeeNoList];
        List<User> usrList = [select Id, Employee_No__c from User where Employee_No__c IN :userEmployeeNoList];
        for (User usr : usrList) {
            //update                          wangweipeng                2021/11/19 
            //由于测试时,发现contact的员工编码为大写,user表为小写,但是新增时falseforce大小写不敏感,所以会报重复值的错误
            //所以为了避免以上问题,把员工编码都转为小写
            usrMap.put(usr.Employee_No__c.toLowerCase(), usr);
        }
        
        List<User> updateList = new List<User>();
        for (Contact local : conList) {
            //update                          wangweipeng                2021/11/19  
            //由于测试时,发现contact的员工编码为大写,user表为小写,但是新增时falseforce大小写不敏感,所以会报重复值的错误
            // 所以为了避免以上问题,把员工编码都转为小写
            if (usrMap.containsKey(local.Employee_No_manual__c.toLowerCase())) {
                // 更新现有用户
                User tmp = usrMap.get(local.Employee_No_manual__c);
                tmp.FirstName = local.FirstName;
                tmp.LastName = local.LastName;
                tmp.Email = local.Email;
                tmp.Mobile_Phone__c = local.MobilePhone;
                //tmp.Employee_No__c = local.Employee_No_manual__c;
                tmp.Work_Location__c = local.Work_Location_manual__c;
                tmp.Post__c = local.Post_picklist__c;
                tmp.Job_Category__c = local.Job_Category_picklist__c;
                tmp.Hire_Date__c = local.Hire_date_text__c; 
                tmp.Gender__c = local.Gender_text__c; 
                tmp.Dept__c = local.Dept__c;
                tmp.Pregnant_Rest__c = local.Pregnant_Rest__c;
                tmp.Stay_or_not__c = local.Stay_or_not__c;
                updateList.add(tmp);
            }
        }
        update updateList;
    }
 
    //add   wangweipeng                      2021/11/18               start
    //根据ods的员工编码,更新或新增 user表的数据
    public static void updateFutureOdsByUser(List<String> userEmployeeNoList) {
        //20220426  LLIU-CCY9TA you start 通用职衔和user上的职位互相映射,
        SS_BatchColumnMapping__c mpdMapping = SS_BatchColumnMapping__c.getValues('HR_Post_To_UserAndContact__c');
                  
            Map<String,String> UserAndContactMap = new Map<String,String>();
            for (Integer i = 1; i <= 30; i++) {
                String lpadI = ('00' + i).right(3);
                String fromColumn = 'From_Column_' + lpadI + '__c';
                if(mpdMapping!=null){
                    String apiStr = String.valueOf(mpdMapping.get(fromColumn));
                    if (String.isBlank(apiStr) == false) {
                        String ssColumn = 'SS_Column_' + lpadI + '__c';
                        String ssApiStr = String.valueOf(mpdMapping.get(ssColumn));
                        UserAndContactMap.put(apiStr,ssApiStr);   
                    }
                }      
         } 
         //20220426  LLIU-CCY9TA you end
 
        //20220721 you LLIU-CGH8EY start 本部分类-岗位子序列,映射 user上的职种
        SS_BatchColumnMapping__c JobmpdMapping = SS_BatchColumnMapping__c.getValues('HR_Post_To_Job_Category__c');
                  
            Map<String,String> Job_CategoryMap = new Map<String,String>();
            for (Integer i = 1; i <= 30; i++) {
                String lpadI = ('00' + i).right(3);
                String fromColumn = 'From_Column_' + lpadI + '__c';
                if(JobmpdMapping!=null){
                    String apiStr = String.valueOf(JobmpdMapping.get(fromColumn));
                    if (String.isBlank(apiStr) == false) {
                        String ssColumn = 'SS_Column_' + lpadI + '__c';
                        String ssApiStr = String.valueOf(JobmpdMapping.get(ssColumn));
                        Job_CategoryMap.put(apiStr,ssApiStr);   
                    }
                }      
         } 
        //20220721 you LLIU-CGH8EY end
        
       //20220823 you LLIU-CHL8FB start 本部是--solution本部的通过映射,更新用户上的 本部(选项),如果是其他,那么正常走逻辑
        SS_BatchColumnMapping__c DeptMapping = SS_BatchColumnMapping__c.getValues('HR_Category4_To_Dept__c');
                  
            Map<String,String> DeptMap = new Map<String,String>();
            for (Integer i = 1; i <= 30; i++) {
                String lpadI = ('00' + i).right(3);
                String fromColumn = 'From_Column_' + lpadI + '__c';
                if(DeptMapping!=null){
                    String apiStr = String.valueOf(DeptMapping.get(fromColumn));
                    if (String.isBlank(apiStr) == false) {
                        String ssColumn = 'SS_Column_' + lpadI + '__c';
                        String ssApiStr = String.valueOf(DeptMapping.get(ssColumn));
                        DeptMap.put(apiStr,ssApiStr);   
                    }
                }      
         } 
        //20220823 you LLIU-CHL8FB end
 
        system.debug(mpdMapping+'==UserAndContactMap=='+UserAndContactMap);
        //获取自定义标签,自己定义,用来空更新数据或处理历史数据
        //在处理历史记录时:职位和职种 如果ods的值为空,那么user对象的这两个字段就不需要更新
        Integer buffer = Integer.valueOf(System.Label.ODS_Null_Update_Sign);
        // 现有用户
        Map<String, User> usrMap = new Map<String, User>();
        // ContactToUser の 変更したか にて判断した項目です
        List<ODS__c> conList = [select id,Alias__c,Branch__c,PositionSubsequence__c,Rank__c,Category3__c,Category4__c,Category5__c,Category6__c,Employee_No__c,Hire_Date__c,FirstName__c,LastName__c,Name__c,Email__c,MobilePhone__c,Post__c,Job_Category__c,Job_Type__c,Product_specialist_incharge_product__c,Sales_Speciality__c,Work_Location__c,Stay_or_not__c,LeaveDate__c,UniqueId__c,Null_Update__c,Salesdepartment__c from ODS__c where Employee_No__c in :userEmployeeNoList];
 
        List<User> usrList = [select Id, PBI_Enable__c ,PBIAuthorizedSetting__c,Employee_No__c from User where Employee_No__c IN :userEmployeeNoList];
        for (User usr : usrList) {
            //usrMap.put(usr.Employee_No__c, usr);
            //由于测试时,发现ods的员工编码和user的员工编码大小写不一致,所有我们在这里把员工编码全部转为小写
            //所以为了避免以上问题,把员工编码都转为小写
            usrMap.put(usr.Employee_No__c.toLowerCase(), usr);
        }
        
        List<User> updateList = new List<User>();
        List<User> insertList = new List<User>();
        List<String> updateId = new List<String>();
        for (ODS__c odsc : conList) {
            //由于测试时,发现ods的员工编码和user的员工编码大小写不一致,所有我们在这里把员工编码全部转为小写
            // 所以为了避免以上问题,把员工编码都转为小写
            if (usrMap.containsKey(odsc.Employee_No__c.toLowerCase())) {
                // 更新现有用户
                User userData = usrMap.get(odsc.Employee_No__c.toLowerCase());
 
                userData.Group_sales_dept__c = odsc.Category3__c;//统括本部
                if(String.isNotBlank(odsc.Category4__c)){
                    //20220823 you LLIU-CHL8FB start 
                    if(null!=DeptMap && DeptMap.containsKey(odsc.Category4__c)){
                       userData.Dept__c = DeptMap.get(odsc.Category4__c);//本部
                     }else{
                       userData.Dept__c = odsc.Category4__c;//本部
                     }
                     //20220823 you LLIU-CHL8FB end 
                }
                userData.Category5__c = odsc.Category5__c;//部
                //LLIU-CCS8ZB-当新创建的时候接收人事信息中的课信息,之后不进行更新 thh 20220324 start
                // userData.Category6__c = odsc.Category6__c;//课
                //LLIU-CCS8ZB-当新创建的时候接收人事信息中的课信息,之后不进行更新 thh 20220324 end
                //userData.Employee_No__c = odsc.Employee_No__c;//员工编码
                userData.Hire_Date__c = odsc.Hire_Date__c;//入职日期
                //userData.Email = odsc.Email__c;//电子邮件
                userData.Mobile_Phone__c = odsc.MobilePhone__c;//手机号码
                //如果自定义变迁的值为1,那么证明现在是在处理历史数据,而历史数据规定,如果ods的职位为空,那么就不需要更新user的职种
               //20220425  LLIU-CCY9TA you ods 的 通用职衔   对应用户上新创建的 HR通用职级     断开跟职位的关系
 
                if(String.isNotBlank(odsc.Post__c) || buffer != 1){
                    //userData.Post__c = odsc.Post__c;//职位
                     userData.HR_Post__c = odsc.Post__c;//HR通用职级
                     system.debug(odsc.Post__c+'===='+UserAndContactMap.containsKey(odsc.Post__c));
                     if(null!=UserAndContactMap && UserAndContactMap.containsKey(odsc.Post__c)){
                         userData.Post__c =  UserAndContactMap.get(odsc.Post__c);
                      }
                }
                //20220426  LLIU-CCY9TA you end
                
                //20220428 LLIU-CDW5ZW you start 
                userData.PositionSubsequence__c = odsc.PositionSubsequence__c;
                //20220428 LLIU-CDW5ZW you end
                //20220512 you LLIU-CDW5ZW start
                userData.Rank__c = odsc.Rank__c;
                //20220428 you LLIU-CDW5ZW end
                
                // 20220721 you LLIU-CGH8EY start 注释,依据本部和岗位子序列 给职种赋值
                /**
                String zz = '';
                if(odsc.Job_Category__c == '服务'){
                    zz = '销售服务';
                }else if(odsc.Job_Category__c == '推广'){
                    zz = '销售推广';
                }else{
                    zz = odsc.Job_Category__c;
                }
                //如果自定义变迁的值为1,那么证明现在是在处理历史数据,而历史数据规定,如果ods的职种为空,那么就不需要更新user的职种
                if(String.isNotBlank(zz) || buffer != 1){
                    userData.Job_Category__c = zz;//职种
                }**/
                String bbz=odsc.Category4__c+'-' +odsc.PositionSubsequence__c; //本部-岗位子序列
                String ldbb=odsc.Salesdepartment__c+'-' +odsc.PositionSubsequence__c; //六大本部-岗位子序列
                String bbz1=odsc.Category5__c+'-' +odsc.PositionSubsequence__c;  //部-岗位子序列
                system.debug(bbz+'==='+ldbb+'==Job_CategoryMap=='+Job_CategoryMap);
                //本部不等于空,看本部
                String zz = '';
                if( (String.isNotBlank(odsc.PositionSubsequence__c) && odsc.PositionSubsequence__c=='供应链管理') || ( String.isNotBlank(odsc.Category4__c) && odsc.Category4__c=='战略创新本部')){
                     zz = '管理';
                }else if( String.isNotBlank(odsc.Category4__c) && odsc.Category4__c=='Solution本部'){
                     zz = '市场';
                }else if(String.isNotBlank(odsc.Category4__c)){
                    if(null!=Job_CategoryMap && Job_CategoryMap.containsKey(bbz)){
                       if(Job_CategoryMap.get(bbz) == '服务'){
                         zz = '销售服务';
                       }else if(Job_CategoryMap.get(bbz) == '推广'){
                         zz = '销售推广';
                       }else{
                         zz = Job_CategoryMap.get(bbz);
                       }   
                    }
                    if(null!=Job_CategoryMap && Job_CategoryMap.containsKey(ldbb)){
                       if(Job_CategoryMap.get(ldbb) == '服务'){
                         zz = '销售服务';
                       }else if(Job_CategoryMap.get(ldbb) == '推广'){
                         zz = '销售推广';
                       }else{
                         zz = Job_CategoryMap.get(ldbb);
                       }  
                    } 
                    
                    system.debug('=='+Job_CategoryMap.get(bbz)+'==='+Job_CategoryMap.get(ldbb)+'==='+zz);
                  }else if(String.isBlank(odsc.Category4__c) && String.isNotBlank(odsc.Category5__c)){
                    //本部等于空,看部
                    if(odsc.Category5__c=='华北东北运营管理部' || odsc.Category5__c=='西北西南运营管理部' || odsc.Category5__c=='西北西南运营支援部' || bbz1=='华北东北服务部-综合行政' || bbz1=='华北东北市场部-综合行政'){
                      zz = '支援'; 
                    }else if(bbz1=='华北东北服务部-FSE'){
                      zz = '销售服务';
                    }else if(odsc.Category5__c=='西部战略推进部' || bbz1=='华北东北市场部-推广'){
                      zz = '销售推广';
                    }
                  }
                  userData.Job_Category__c = zz;
 
                // 20220721 you LLIU-CGH8EY end
 
                //userData.Product_specialist_incharge_product__c = odsc.Product_specialist_incharge_product__c;//负责产品(主)
                //userData.Sales_Speciality__c = odsc.Sales_Speciality__c;//销售工作内容
                //HR信息上的工作地更新到用户的工作地(人事)上 thh 2022-02-16 start
                userData.Work_Location_HR__c = odsc.Work_Location__c;
                //HR信息上的工作地更新到用户的工作地(人事)上 thh 2022-02-16 end
                userData.Stay_or_not__c = odsc.Stay_or_not__c;//在职/已离职
                //由于user有一个验证规则,如果值为已离职,那么PBI不能为true,所以手动设置为false,并把PBI对象的值设为false
                if(userData.Stay_or_not__c == '已离职' && userData.PBI_Enable__c){//PBI是否启用
                    userData.PBI_Enable__c = false;
                    updateId.add(userData.id);
                }
                userData.Null_Update__c = odsc.Null_Update__c;
                userData.QuitDate__c = odsc.LeaveDate__c;//离职日期
                userData.IsMEBG__c=true;//是否MEBG
                updateList.add(userData);
            }else{
                //如果没有在user表中找到对应的员工编码,那么新增user
                User userData = new User();
                userData.Group_sales_dept__c = odsc.Category3__c;//统括本部
                if(String.isNotBlank(odsc.Category4__c)){
                     //20220823 you LLIU-CHL8FB start 
                    if(null!=DeptMap && DeptMap.containsKey(odsc.Category4__c)){
                       userData.Dept__c = DeptMap.get(odsc.Category4__c);//本部
                     }else{
                       userData.Dept__c = odsc.Category4__c;//本部
                     }
                     //20220823 you LLIU-CHL8FB end 
                }
                userData.Category5__c = odsc.Category5__c;//部
                userData.Category6__c = odsc.Category6__c;//课
                userData.Employee_No__c = odsc.Employee_No__c;//员工编码
                userData.Hire_Date__c = odsc.Hire_Date__c;//入职日期
                userData.Email = odsc.Email__c;//电子邮件,新建时,填写电子邮件
                userData.Username = '_'+odsc.Email__c;//用户名
                userData.Mobile_Phone__c = odsc.MobilePhone__c;//手机号码
                //如果自定义变迁的值为1,那么证明现在是在处理历史数据,而历史数据规定,如果ods的职位为空,那么就不需要更新user的职种
                //20220426  LLIU-CCY9TA you start
                if(String.isNotBlank(odsc.Post__c) || buffer != 1){
                    //userData.Post__c = odsc.Post__c;//职位
                    userData.HR_Post__c = odsc.Post__c;//HR通用职级
                    if(null!=UserAndContactMap && UserAndContactMap.containsKey(odsc.Post__c)){
                         userData.Post__c =  UserAndContactMap.get(odsc.Post__c);
                      }
                }
                //20220426  LLIU-CCY9TA you end
                
                //20220428 LLIU-CDW5ZW you start 
                userData.PositionSubsequence__c = odsc.PositionSubsequence__c;
                //20220428 LLIU-CDW5ZW you end
                //20220512 you LLIU-CDW5ZW start
                userData.Rank__c = odsc.Rank__c;
                //20220428 you LLIU-CDW5ZW end
                // 20220721 you LLIU-CGH8EY start 注释,依据本部和岗位子序列 给职种赋值
                /**
                String zz = '';
                if(odsc.Job_Category__c == '服务'){
                    zz = '销售服务';
                }else if(odsc.Job_Category__c == '推广'){
                    zz = '销售推广';
                }else{
                    zz = odsc.Job_Category__c;
                }
                //如果自定义变迁的值为1,那么证明现在是在处理历史数据,而历史数据规定,如果ods的职种为空,那么就不需要更新user的职种
                if(String.isNotBlank(zz) || buffer != 1){
                    userData.Job_Category__c = zz;//职种
                }**/
                String bbz=odsc.Category4__c+'-' +odsc.PositionSubsequence__c; //本部-岗位子序列
                String ldbb=odsc.Salesdepartment__c+'-' +odsc.PositionSubsequence__c; //六大本部-岗位子序列
                String bbz1=odsc.Category5__c+'-' +odsc.PositionSubsequence__c;  //部-岗位子序列
                //本部不等于空,看本部
                String zz = '';
                if( (String.isNotBlank(odsc.PositionSubsequence__c) && odsc.PositionSubsequence__c=='供应链管理') || ( String.isNotBlank(odsc.Category4__c) && odsc.Category4__c=='战略创新本部')){
                     zz = '管理';
                }else if( String.isNotBlank(odsc.Category4__c) && odsc.Category4__c=='Solution本部'){
                     zz = '市场';
                }else if(String.isNotBlank(odsc.Category4__c)){
                    if(null!=Job_CategoryMap && Job_CategoryMap.containsKey(bbz)){
                       if(Job_CategoryMap.get(bbz) == '服务'){
                         zz = '销售服务';
                       }else if(Job_CategoryMap.get(bbz) == '推广'){
                         zz = '销售推广';
                       }else{
                         zz = Job_CategoryMap.get(bbz);
                       }   
                    }
                    if(null!=Job_CategoryMap && Job_CategoryMap.containsKey(ldbb)){
                       if(Job_CategoryMap.get(ldbb) == '服务'){
                         zz = '销售服务';
                       }else if(Job_CategoryMap.get(ldbb) == '推广'){
                         zz = '销售推广';
                       }else{
                         zz = Job_CategoryMap.get(ldbb);
                       }  
                    } 
                    
                  }else if(String.isBlank(odsc.Category4__c) && String.isNotBlank(odsc.Category5__c)){
                    //本部等于空,看部 LLIU-CKE3UG 增加映射关系
                    if(odsc.Category5__c=='华北东北运营管理部' || odsc.Category5__c=='西北西南运营管理部' || odsc.Category5__c=='西北西南运营支援部' || bbz1=='华北东北服务部-综合行政' || bbz1=='华北东北市场部-综合行政'){
                      zz = '支援'; 
                    }else if(bbz1=='华北东北服务部-FSE'){
                      zz = '销售服务';
                    }else if(odsc.Category5__c=='西部战略推进部' || bbz1=='华北东北市场部-推广'){
                      zz = '销售推广';
                    }
                  }
                  userData.Job_Category__c = zz;
 
                // 20220721 you LLIU-CGH8EY end
                userData.Null_Update__c = odsc.Null_Update__c;
                userData.Product_specialist_incharge_product__c = odsc.Product_specialist_incharge_product__c;//负责产品(主)
                userData.Sales_Speciality__c = odsc.Sales_Speciality__c;//销售工作内容
                //如果根据HR信息新建用户,则把HR信息的工作地传给用户的工作地和工作地(人事) thh 2022-02-16 start
                userData.Work_Location_HR__c = odsc.Work_Location__c;
                userData.Work_Location__c = odsc.Work_Location__c;
                //如果根据HR信息新建用户,则把HR信息的工作地传给用户的工作地和工作地(人事) thh 2022-02-16 end
                userData.Stay_or_not__c = odsc.Stay_or_not__c;//在职/已离职
                userData.QuitDate__c = odsc.LeaveDate__c;//离职日期
                userData.IsMEBG__c=true;//是否MEBG
                //由于ods的姓和名都是拼音,所以获取name__c的值,并且首字母第一位为姓,其余为名
                if(String.isNotBlank(odsc.Name__c)){
                    if(odsc.Name__c.length() > 1){
                        userData.LastName = odsc.Name__c.substring(0,1);
                        userData.FirstName = odsc.Name__c.substring(1,odsc.Name__c.length());
                        userData.Alias = odsc.Name__c;
                    }
                }
                //以下是系统默认
                userData.FederationIdentifier = odsc.Employee_No__c + '@olympus.com.cn';
                userData.EmailEncodingKey = 'UTF-8';//电子邮件编码
                userData.IsActive = false;
                userData.TimeZoneSidKey = 'Asia/Shanghai';//时区
                userData.LocaleSidKey = 'ja_JP';//区域
                userData.LanguageLocaleKey = 'zh_CN';//语言
                //userData.DefaultCurrencyIsoCode = 'CNY';//默认币种 ISO 代码
                //userData.CurrencyIsoCode = 'CNY';//信息币种
                //默认ods创建的user用户的简档为  999_看不见Profile
                userData.Profileid = '00e10000000dFYJ';
 
                insertList.add(userData);
            }
        }
 
        //PBI数据更新
        //由于user有一个验证规则,如果值变为已离职,那么PBI不能为true,所以手动设置为false,并把PBI对象的值设为false
        if(updateId.size() > 0){
            List<PBIAuthorization__c> pbiUpd = [select id,name,PBI_Enable__c,User__c from PBIAuthorization__c where user__c in :updateId and PBI_Enable__c = true];
            if(pbiUpd != null && pbiUpd.size() > 0){
                for(PBIAuthorization__c pc : pbiUpd){
                    pc.PBI_Enable__c = false;
                }
            }
            //首先更新 PBI权限为false
            if(pbiUpd.size() > 0){
                update pbiUpd;
            }
        }
        if(insertList.size() > 0 || updateList.size() > 0){
            ID jobId = system.enqueueJob(new UserUpsertQueueable(insertList,updateList));
            AsyncApexJob jobInfo = [select status,NumberOfErrors from AsyncApexJob where id =:jobId];
            System.debug('--------------------队列日志'+jobInfo);
        }
    }
    //add   wangweipeng                    2021/11/18               start
 
    @future (callout=true)
    public static void upsertFutureContact(String sessionId, List<Id> userIdList) {
        HttpRequest req = new HttpRequest();
        req.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm() + '/services/apexrest/UserToContact');
System.debug('Endpoint ' + req.getEndpoint());
        req.setMethod('POST');
 
        // header
        String authorizationHeader = 'OAuth ' + sessionId;
System.debug(authorizationHeader);
        req.setHeader('Authorization', authorizationHeader);
        
        // body
        String restBody = '{"userIdList":' + JSON.serialize(userIdList) + '}';
System.debug('JSON ' + restBody);
        req.setBody(restBody);
 
        // Create a new http object to send the request object
        Http http = new Http();
        HTTPResponse res = http.send(req);
System.debug(res.getBody());
    }
    
    public static List<Daily_Report__c> reportSelectById(String id){
        List<Daily_Report__c> reportList = [select id, name, Reporter__c, Reported_Date__c, Daily_Report_Data_Type__c,
                                            Working_Time_From__c, Working_Time_To__c, Status__c, Mail_Send_Check__c,
                                            Business_Trip__c, Submit_Date_New__c, Submit_DateTime_New__c, Approved_Date__c,
                                            Approved_DateTime__c, CreatedById, Feed_Back_From_Manager__c, FeedbackManager__c,
                                            Planning_Time__c, Submission_Elapsed_Hour__c, Approval_Elapsed_Time__c,
                                            Activity_ID__c, Manager_Mail__c, Status_With_Check__c
                                            from Daily_Report__c where Id = :id];
        return reportList;
    }
    
    public static List<Event> eventSelectByUsers(String soql, List<Date> mdates, List<Id> users) {
        return Database.query(soql);
    }
    public static Map<Id, Daily_Report__c> reportMapSelectByIds(List<Id> ids){
        Map<Id, Daily_Report__c> reportMap = new Map<Id, Daily_Report__c>([select id, Status__c, Submit_Date_New__c
                                            from Daily_Report__c where Id IN :ids]);
        return reportMap;
    }
    
    public static List<Opportunity> oppSelectForPersonTaget(Id rtId, User[] users, String currentPeriod) {
        Opportunity[] opportunitys = [select
                        Id, OwnerId, Opportunity_Category__c, Proportion__c, CloseDate,
                        Amount, Objective__c, Target_category__c,
                        SAP_Province__c, RecordTypeId, OCM_Target_period__c
                 from Opportunity
                where Target_category__c = '担当目标'
                  and RecordTypeId = :rtId
                  and OwnerId in :users
                  and OCM_Target_period__c = :currentPeriod
                ];
        return opportunitys;
    }
 
    public static List<Opportunity> oppSelectForLock(List<String> oppIds) {
        List<Opportunity> opps = [select Id
                ,Last_Visit_Scheduled_Date__c
                ,Xin_Last_Follow_Up_Date_For_Report__c, Xin_Gross_Follow_Num__c,Visit_President_Count__c,Visit_Head_Doctor_Count__c,Num_Of_NTC__c
                // CHAN-BE6CZZ 最后跟进结果 LHJ 20190724 Start
                ,Follow_up_comment__c 
                // CHAN-BE6CZZ 最后跟进结果 LHJ 20190724 End
                ,Num_Of_OPD__c
            from Opportunity where Id in :oppIds for update];
        return opps;
    }
    
    public static List<Opportunity> oppSelectForCity(List<String> oppIds) {
        List<Opportunity> opps = [select Id, Account.Parent.RecordTypeId, Account.Parent.Parent.RecordTypeId, Account.Parent.Parent.City_Master__r.Name, Account.City_Master__r.Name from Opportunity where Id in :oppIds];
        return opps;
    }
    
    public static void updOppList(List<Opportunity> oppUpdateList){
        if (oppUpdateList != null && oppUpdateList.size() > 0) update oppUpdateList;
    }
    
    public static void updOpp(Opportunity opp) {
        update opp;
    }
    
    public static List<Opportunity2__c> opp2SelectForSync(List<String> oppIds) {
        List<Opportunity2__c> opp2s = [select Id, Opportunity__c from Opportunity2__c where Opportunity__c in :oppIds];
        return opp2s;
    }
    
    public static List<Product2__c> pr2SelectForSync(List<Product2> pr2Ids) {
        List<Product2__c> pr2s = [select Id, Product2__c from Product2__c where Product2__c in :pr2Ids];
        return pr2s;
    }
    
    public static List<Maintenance_Contract__c> mcSelectForLock(List<String> serviceIds) {
        List<Maintenance_Contract__c> mcs = [select Id, Xin_Last_Follow_Day__c from Maintenance_Contract__c where Id in :serviceIds for update];
        return mcs;
    }
    
    public static void delEvent1ForTrigger(List<String> conIds) {
        List<Activity_History_Daily_Report__c> ahdrList = [select Id from Activity_History_Daily_Report__c where Contact__c in :conIds];
        if (ahdrList.size() > 0) delete ahdrList;
    }
    
    public static void delEvent2ForTrigger(List<String> oppIds) {
        List<Event_Oppotunity__c> eoList = [select Id from Event_Oppotunity__c where Opportunity__c in :oppIds];
        if (eoList.size() > 0) delete eoList;
    }
    
    public static void delEvent3ForTrigger(List<String> mcIds) {
        List<Event_Service__c> esList = [select Id from Event_Service__c where Service__c in :mcIds];
        if (esList.size() > 0) delete esList;
    }
    
    public static void upsEventC(List<Event__c> acts) {
        System.debug('Event__c1111' + acts);
        if(acts.size() > 0) upsert acts;
    }
    
    public static void upsEvent(List<Event> acts) {
        if(acts.size() > 0) upsert acts;
    }
    
    public static void delEvent(Set<String> eventCIdSet, Map<Id, Event__c> eventC_eventMap) {
        // 削除する前に、delete_flgをtrueにする
        List<Event> delList = [select Id from Event where EventC_ID__c in :eventCIdSet];
        ControllerUtil.delEventIdSet.addAll((new Map<Id, SObject>(delList)).keySet());
        if (delList.size() > 0) {
            delete delList;
        }
        // Event__cにEventへの参照IDがある
        delList = [select Id from Event where Id in :eventC_eventMap.keySet()];
        ControllerUtil.delEventIdSet.addAll((new Map<Id, SObject>(delList)).keySet());
        if (delList.size() > 0) {
            delete delList;
        }
    }
    
    public static void delEventOnly(String Id) {
        List<Event> delList = [select Id from Event where id = :Id];
        if (delList.size() > 0) {
            delete delList;
        }
    }
    
    public static void insSFDelete(List<SFDelete__c> dlist) {
        if (dlist.size() > 0) insert dList;
    }
    
    public static void upsEventC2Event(Map<Id, Event__c> eventCMap, Map<Id, Event__c> eventC_eventMap) {
        List<Event> unDelList = new List<Event>();
        List<Event> upsList = new List<Event>();
        List<Id> updateEIds = new List<Id>();
        //2021-08-30 mzy SWAG-C5784H 【委托】事件无法延期 start
        Set<String> idSet = new Set<String>();
        //2021-08-30 mzy SWAG-C5784H 【委托】事件无法延期 end
        Map<String, String> dupUpdIdMap = new Map<String, String>();
        
        // 日報画面からEvent__cを更新する時
        // ①EventにEvent__cへの参照IDがある
        // IsArchived = false を条件に追加することにより、1年以上の場合Event_CからEventへ同期しません!!
        if (eventCMap.keySet().size() > 0) {
            List<Event> eList = [select Id, EventC_ID__c, IsDeleted from Event where EventC_ID__c in :eventCMap.keySet() and IsArchived = false all rows];
            if (eList.size() > 0) {
                for (Event e : eList) {
                    updateEIds.add(e.Id);
                    Event__c ec = eventCMap.get(e.EventC_ID__c);
System.debug('EventにEvent__cへの参照IDがある:::::' + e.Id + ',' + e.EventC_ID__c);
System.debug('ec.Subject__c:::::'+ec.Subject__c);
System.debug('ec.StartDateTime__c:::::'+ec.StartDateTime__c);
System.debug('ec.EndDateTime__c:::::'+ec.EndDateTime__c);
System.debug('ec.DurationInMinutes:::::' + Integer.valueOf((ec.EndDateTime__c.getTime() - ec.StartDateTime__c.getTime()) / 1000 / 60));
System.debug('ec.Daily_Report__c:::::'+ec.Daily_Report__c);
System.debug('ec.Main_Visit_Location__c:::::'+ec.Main_Visit_Location__c);
System.debug('ec.Activity_Type2__c:::::'+ec.Activity_Type2__c);
System.debug('ec.Purpose_Type__c:::::'+ec.Purpose_Type__c);
System.debug('ec.Location__c:::::'+ec.Location__c);
System.debug('ec.Related_Opportunity1__c:::::'+ec.Related_Opportunity1__c);
System.debug('ec.Related_Opportunity1_ID__c:::::'+ec.Related_Opportunity1_ID__c);
System.debug('ec.Related_Service1__c:::::'+ec.Related_Service1__c);
System.debug('ec.Related_Service1_ID__c:::::'+ec.Related_Service1_ID__c);
System.debug('ec.whatid__c:::::'+ec.whatid__c);
                    e.Subject = (ec.Subject__c==null||ec.Subject__c=='')?ec.Activity_Purpose__c:ec.Subject__c;
                    e.IsAllDayEvent = false;
                    e.ActivityDateTime = ec.StartDateTime__c;
                    e.StartDateTime = ec.StartDateTime__c;
                    e.EndDateTime = ec.EndDateTime__c;
                    e.DurationInMinutes = Integer.valueOf((ec.EndDateTime__c.getTime() - ec.StartDateTime__c.getTime()) / 1000 / 60);
                    e.Main_Visit_Location__c = ec.Main_Visit_Location__c;
                    e.Activity_Type2__c = ec.Activity_Type2__c;
                    e.Purpose_Type__c = ec.Purpose_Type__c;
                    e.Purpose_TypeFSE__c = ec.Purpose_TypeFSE__c;
                    e.Purpose_TypeEscFSE__c = ec.Purpose_TypeEscFSE__c;
                    e.Location = String.isBlank(ec.Location__c) ? ec.Visitor_Place_Free__c : ec.Location__c;
                    e.Related_Opportunity1__c = ec.Related_Opportunity1__c;
                    e.Related_Opportunity1_ID__c = ec.Related_Opportunity1_ID__c;
                    e.Related_Opportunity2__c = ec.Related_Opportunity2__c;
                    e.Related_Opportunity2_ID__c = ec.Related_Opportunity2_ID__c;
                    e.Related_Opportunity3__c = ec.Related_Opportunity3__c;
                    e.Related_Opportunity3_ID__c = ec.Related_Opportunity3_ID__c;
                    e.Related_Opportunity4__c = ec.Related_Opportunity4__c;
                    e.Related_Opportunity4_ID__c = ec.Related_Opportunity4_ID__c;
                    e.Related_Opportunity5__c = ec.Related_Opportunity5__c;
                    e.Related_Opportunity5_ID__c = ec.Related_Opportunity5_ID__c;
                    e.Related_Service1__c = ec.Related_Service1__c;
                    e.Related_Service1_ID__c = ec.Related_Service1_ID__c;
                    e.Visitor1__c = ec.Visitor1__c;
                    e.Visitor2__c = ec.Visitor2__c;
                    e.Visitor3__c = ec.Visitor3__c;
                    e.Visitor4__c = ec.Visitor4__c;
                    e.Visitor5__c = ec.Visitor5__c;
                    e.Visitor1_ID__c = ec.Visitor1_ID__c;
                    e.Visitor2_ID__c = ec.Visitor2_ID__c;
                    e.Visitor3_ID__c = ec.Visitor3_ID__c;
                    e.Visitor4_ID__c = ec.Visitor4_ID__c;
                    e.Visitor5_ID__c = ec.Visitor5_ID__c;
                    e.Activity_Purpose__c = ec.Activity_Purpose__c;
                    e.Activity_PurposeFSE__c = ec.Activity_PurposeFSE__c;
                    e.Activity_PurposeEscFSE__c = ec.Activity_PurposeEscFSE__c;
                    e.whatid__c = ec.whatid__c;
                    e.EventC_ID__c = ec.Id;
                    e.WhatId = ec.Daily_Report__c;
                    e.IsScheduled__c = ec.IsScheduled__c;
                    e.BeforeActivityDate__c = ec.BeforeActivityDate__c;
                    e.AppCdId__c = ec.AppCdId__c;
                    e.SyncCreatedDate__c = ec.SyncCreatedDate__c;
                    e.WS_flg__c = false;
                    if (e.IsDeleted) {
System.debug('e.IsDeleted:::::'+e.IsDeleted);
                        unDelList.add(e);
                    }
                    if (ec.Activity_Type2__c == 'Holiday') {
                        e.ShowAs = 'OutOfOffice';
                    }
                    upsList.add(e);
                    eventCMap.remove(e.EventC_ID__c);  // 更新したものをMapから削除
                    dupUpdIdMap.put(e.Id, e.Id);
                }
            }
        }
        List<Event__c> ecList = eventCMap.values();
        // ②参照IDあるものを除いて、新規
        if (ecList.size() > 0) {
            List<Event> insE = new List<Event>();
            for (Event__c ec : ecList) {
                // Event__cにEvent_ID__cがない、つまり日報画面から作成された時
                if (ec.Event_ID__c == null) {
System.debug('Event__cにEvent_ID__cがない、つまり日報画面から作成された時:::::' + ec.Id);
System.debug('ec.Subject__c:::::'+ec.Subject__c);
System.debug('ec.StartDateTime__c:::::'+ec.StartDateTime__c);
System.debug('ec.EndDateTime__c:::::'+ec.EndDateTime__c);
System.debug('ec.DurationInMinutes:::::' + Integer.valueOf((ec.EndDateTime__c.getTime() - ec.StartDateTime__c.getTime()) / 1000 / 60));
System.debug('ec.Daily_Report__c:::::'+ec.Daily_Report__c);
System.debug('ec.Main_Visit_Location__c:::::'+ec.Main_Visit_Location__c);
System.debug('ec.Activity_Type2__c:::::'+ec.Activity_Type2__c);
System.debug('ec.Purpose_Type__c:::::'+ec.Purpose_Type__c);
System.debug('ec.Location__c:::::'+ec.Location__c);
System.debug('ec.Related_Opportunity1__c:::::'+ec.Related_Opportunity1__c);
System.debug('ec.Related_Opportunity1_ID__c:::::'+ec.Related_Opportunity1_ID__c);
System.debug('ec.Related_Service1__c:::::'+ec.Related_Service1__c);
System.debug('ec.Related_Service1_ID__c:::::'+ec.Related_Service1_ID__c);
System.debug('ec.whatid__c:::::'+ec.whatid__c);
                    Event e = new Event(
                        OwnerId = ec.Reporter__c,
                        Subject = (ec.Subject__c==null||ec.Subject__c=='')?ec.Activity_Purpose__c:ec.Subject__c,
                        IsAllDayEvent = false,
                        ActivityDateTime = ec.StartDateTime__c,
                        StartDateTime = ec.StartDateTime__c,
                        EndDateTime = ec.EndDateTime__c,
                        DurationInMinutes = Integer.valueOf((ec.EndDateTime__c.getTime() - ec.StartDateTime__c.getTime()) / 1000 / 60),
                        Main_Visit_Location__c = ec.Main_Visit_Location__c,
                        Activity_Type2__c = ec.Activity_Type2__c,
                        Purpose_Type__c = ec.Purpose_Type__c,
                        Purpose_TypeFSE__c = ec.Purpose_TypeFSE__c,
                        Purpose_TypeEscFSE__c = ec.Purpose_TypeEscFSE__c,
                        Location = String.isBlank(ec.Location__c) ? ec.Visitor_Place_Free__c : ec.Location__c,
                        Related_Opportunity1__c = ec.Related_Opportunity1__c,
                        Related_Opportunity1_ID__c = ec.Related_Opportunity1_ID__c,
                        Related_Opportunity2__c = ec.Related_Opportunity2__c,
                        Related_Opportunity2_ID__c = ec.Related_Opportunity2_ID__c,
                        Related_Opportunity3__c = ec.Related_Opportunity3__c,
                        Related_Opportunity3_ID__c = ec.Related_Opportunity3_ID__c,
                        Related_Opportunity4__c = ec.Related_Opportunity4__c,
                        Related_Opportunity4_ID__c = ec.Related_Opportunity4_ID__c,
                        Related_Opportunity5__c = ec.Related_Opportunity5__c,
                        Related_Opportunity5_ID__c = ec.Related_Opportunity5_ID__c,
                        Related_Service1__c = ec.Related_Service1__c,
                        Related_Service1_ID__c = ec.Related_Service1_ID__c,
                        Visitor1__c = ec.Visitor1__c,
                        Visitor2__c = ec.Visitor2__c,
                        Visitor3__c = ec.Visitor3__c,
                        Visitor4__c = ec.Visitor4__c,
                        Visitor5__c = ec.Visitor5__c,
                        Visitor1_ID__c = ec.Visitor1_ID__c,
                        Visitor2_ID__c = ec.Visitor2_ID__c,
                        Visitor3_ID__c = ec.Visitor3_ID__c,
                        Visitor4_ID__c = ec.Visitor4_ID__c,
                        Visitor5_ID__c = ec.Visitor5_ID__c,
                        Activity_Purpose__c = ec.Activity_Purpose__c,
                        Activity_PurposeFSE__c = ec.Activity_PurposeFSE__c,
                        Activity_PurposeEscFSE__c = ec.Activity_PurposeEscFSE__c,
                        whatid__c = ec.whatid__c,
                        EventC_ID__c = ec.Id,
                        IsScheduled__c = ec.IsScheduled__c,
                        WhatId = ec.Daily_Report__c,
                        BeforeActivityDate__c = ec.BeforeActivityDate__c,
                        AppCdId__c = ec.AppCdId__c,
                        SyncCreatedDate__c = ec.SyncCreatedDate__c,
                        WS_flg__c = false,
                        EventStatus__c = '02 接受'
                    );
                    if (ec.Activity_Type2__c == 'Holiday') {
                        e.ShowAs = 'OutOfOffice';
                    }
                    upsList.add(e);
                    //2021-08-30 mzy SWAG-C5784H 【委托】事件无法延期 start
                    //报告一览新建事件时,将事件的Id赋值到报告一览上
                    idSet.add(ec.Id);
                    //2021-08-30 mzy SWAG-C5784H 【委托】事件无法延期 end
                } else {
                    // シンプルから遷移する場合、Event_ID__c必ずあるから、パス
                }
            }
        }
 
        // Event__cにEventへの参照IDがある
        if (eventC_eventMap.keySet().size() > 0) {
            List<Event> eList = [select Id, IsDeleted from Event where Id in :eventC_eventMap.keySet() and IsArchived = false all rows];
            if (eList.size() > 0) {
                for (Event e : eList) {
                    if (dupUpdIdMap.containsKey(e.Id)) {
                        continue;
                    }
                    updateEIds.add(e.Id);
                    Event__c ec = eventC_eventMap.get(e.Id);
System.debug('Event__cにEventへの参照IDがある:::::' + e.Id + ',' + ec.Id);
System.debug('ec.Subject__c:::::'+ec.Subject__c);
System.debug('ec.StartDateTime__c:::::'+ec.StartDateTime__c);
System.debug('ec.EndDateTime__c:::::'+ec.EndDateTime__c);
System.debug('ec.DurationInMinutes:::::' + Integer.valueOf((ec.EndDateTime__c.getTime() - ec.StartDateTime__c.getTime()) / 1000 / 60));
System.debug('ec.Daily_Report__c:::::'+ec.Daily_Report__c);
System.debug('ec.Main_Visit_Location__c:::::'+ec.Main_Visit_Location__c);
System.debug('ec.Activity_Type2__c:::::'+ec.Activity_Type2__c);
System.debug('ec.Purpose_Type__c:::::'+ec.Purpose_Type__c);
System.debug('ec.Location__c:::::'+ec.Location__c);
System.debug('ec.Related_Opportunity1__c:::::'+ec.Related_Opportunity1__c);
System.debug('ec.Related_Opportunity1_ID__c:::::'+ec.Related_Opportunity1_ID__c);
System.debug('ec.Related_Service1__c:::::'+ec.Related_Service1__c);
System.debug('ec.Related_Service1_ID__c:::::'+ec.Related_Service1_ID__c);
System.debug('ec.whatid__c:::::'+ec.whatid__c);
                    e.Subject = (ec.Subject__c==null||ec.Subject__c=='')?ec.Activity_Purpose__c:ec.Subject__c;
                    e.IsAllDayEvent = false;
                    e.ActivityDateTime = ec.StartDateTime__c;
                    e.StartDateTime = ec.StartDateTime__c;
                    e.EndDateTime = ec.EndDateTime__c;
                    e.DurationInMinutes = Integer.valueOf((ec.EndDateTime__c.getTime() - ec.StartDateTime__c.getTime()) / 1000 / 60);
                    e.Main_Visit_Location__c = ec.Main_Visit_Location__c;
                    e.Activity_Type2__c = ec.Activity_Type2__c;
                    e.Purpose_Type__c = ec.Purpose_Type__c;
                    e.Purpose_TypeFSE__c = ec.Purpose_TypeFSE__c;
                    e.Purpose_TypeEscFSE__c = ec.Purpose_TypeEscFSE__c;
                    e.Location = String.isBlank(ec.Location__c) ? ec.Visitor_Place_Free__c : ec.Location__c;
                    e.Related_Opportunity1__c = ec.Related_Opportunity1__c;
                    e.Related_Opportunity1_ID__c = ec.Related_Opportunity1_ID__c;
                    e.Related_Opportunity2__c = ec.Related_Opportunity2__c;
                    e.Related_Opportunity2_ID__c = ec.Related_Opportunity2_ID__c;
                    e.Related_Opportunity3__c = ec.Related_Opportunity3__c;
                    e.Related_Opportunity3_ID__c = ec.Related_Opportunity3_ID__c;
                    e.Related_Opportunity4__c = ec.Related_Opportunity4__c;
                    e.Related_Opportunity4_ID__c = ec.Related_Opportunity4_ID__c;
                    e.Related_Opportunity5__c = ec.Related_Opportunity5__c;
                    e.Related_Opportunity5_ID__c = ec.Related_Opportunity5_ID__c;
                    e.Related_Service1__c = ec.Related_Service1__c;
                    e.Related_Service1_ID__c = ec.Related_Service1_ID__c;
                    e.Visitor1__c = ec.Visitor1__c;
                    e.Visitor2__c = ec.Visitor2__c;
                    e.Visitor3__c = ec.Visitor3__c;
                    e.Visitor4__c = ec.Visitor4__c;
                    e.Visitor5__c = ec.Visitor5__c;
                    e.Visitor1_ID__c = ec.Visitor1_ID__c;
                    e.Visitor2_ID__c = ec.Visitor2_ID__c;
                    e.Visitor3_ID__c = ec.Visitor3_ID__c;
                    e.Visitor4_ID__c = ec.Visitor4_ID__c;
                    e.Visitor5_ID__c = ec.Visitor5_ID__c;
                    e.Activity_Purpose__c = ec.Activity_Purpose__c;
                    e.Activity_PurposeFSE__c = ec.Activity_PurposeFSE__c;
                    e.Activity_PurposeEscFSE__c = ec.Activity_PurposeEscFSE__c;
                    e.whatid__c = ec.whatid__c;
                    e.EventC_ID__c = ec.Id;
                    e.IsScheduled__c = ec.IsScheduled__c;
                    e.WhatId = ec.Daily_Report__c;
                    e.BeforeActivityDate__c = ec.BeforeActivityDate__c;
                    e.AppCdId__c = ec.AppCdId__c;
                    e.SyncCreatedDate__c = ec.SyncCreatedDate__c;
                    e.WS_flg__c = false;
                    if (e.IsDeleted) {
System.debug('e.IsDeleted:::::'+e.IsDeleted);
                        unDelList.add(e);
                    }
                    if (ec.Activity_Type2__c == 'Holiday') {
                        e.ShowAs = 'OutOfOffice';
                    }
                    upsList.add(e);
                }
            }
        }
        StaticParameter.NotUpdEventCFlg = true;
        if (unDelList.size() > 0) undelete unDelList;
        if (upsList.size() > 0) {
            List<Event> eList = [select EventC_ID__c, IsDeleted, Related_Opportunity1_ID__c,WhatId, WhoID from Event where Id in :updateEIds and IsArchived = false for update];
System.debug('upsert 直前 start');
            for (Event e : eList) {
System.debug('e.Id:::::'+e.Id);
System.debug('e.EventC_ID__c:::::'+e.EventC_ID__c);
System.debug('e.IsDeleted:::::'+e.IsDeleted);
System.debug('e.Related_Opportunity1_ID__c:::::'+e.Related_Opportunity1_ID__c);
System.debug('e.WhatId:::::'+e.WhatId);
System.debug('e.WhoID:::::'+e.WhoID);
            }
System.debug('upsert 直前 end');
            upsert upsList;
            //2021-08-30 mzy SWAG-C5784H 【委托】事件无法延期 start
            //根据IdSet 给报告一览的事件Id赋值
            List<Event__c> needUpdateEvent = new List<Event__c>();
            for(event e :upsList){
               if( IdSet.contains(e.EventC_ID__c) ){
                  Event__c ec = new Event__c();
                  ec.Id = e.EventC_ID__c;
                  ec.Event_ID__c = e.Id;
                  needUpdateEvent.add(ec);
               }
            }
 
            if(needUpdateEvent.size()>0){
                update needUpdateEvent;
            }
            //2021-08-30 mzy SWAG-C5784H 【委托】事件无法延期 start
 
        }
    }
    
    public static void eventDelIns(Set<Id> actDelListForDelIns, 
            List<Activity_History_Daily_Report__c> ahdrUpSertList, List<Event_Oppotunity__c> eoUpSertList,List<Event_Service__c> esUpSertList){
        // 取引先責任者、引合、サービス契約の活動は delete insert する
        List<Activity_History_Daily_Report__c> ahdrDelList = [select id from Activity_History_Daily_Report__c where EventC_ID__c =:actDelListForDelIns ];
        List<Event_Oppotunity__c> eoDelList = [select id from Event_Oppotunity__c where EventC_ID__c =:actDelListForDelIns ];
        List<Event_Service__c> esDelList = [select id from Event_Service__c where EventC_ID__c =:actDelListForDelIns ];
 
        if(ahdrDelList.size() > 0){
            delete ahdrDelList;
        }
        if(eoDelList.size() > 0){
            delete eoDelList;
        }
        if(esDelList.size() > 0){
            delete esDelList;
        }
        if(ahdrUpSertList.size() > 0){
            insert ahdrUpSertList;
        }
        if(eoUpSertList.size() > 0){
            insert eoUpSertList;
        }
        if(esUpSertList.size() > 0){
            insert esUpSertList;
        }
    }
    
    public static void eventDel(String delId){
        List<Event__c> ecList = [select id from Event__c where Id =:delId];
        if(ecList.size() > 0){
            delete ecList;
        }
        
        List<Report__c> rList = [select id, Delete_Flg__c from Report__c where Event_Id__c =:delId];
        if(rList.size() > 0){
            delete rList;
        }
        
        List<Visit_Report__c> vrList = [select id, Delete_Flg__c from Visit_Report__c where Event_Id__c =:delId];
        if(vrList.size() > 0){
            delete vrList;
        }
        
        List<QIS_Report__c> qrList = [select id from QIS_Report__c where Event_Id__c =:delId];
        if(qrList.size() > 0){
            delete qrList;
        }
        
        List<Activity_History_Daily_Report__c> e1List = [select id from Activity_History_Daily_Report__c where EventC_Id__c =:delId];
        if(e1List.size() > 0){
            delete e1List;
        }
        
        List<Event_Oppotunity__c> e2List = [select id from Event_Oppotunity__c where EventC_Id__c =:delId];
        if(e2List.size() > 0){
            delete e2List;
        }
        
        List<Event_Service__c> e3List = [select id from Event_Service__c where EventC_Id__c =:delId];
        if(e3List.size() > 0){
            delete e3List;
        }
    }
    
    public static void insOpp2List(List<Opportunity2__c> opp2List){
        if (opp2List != null && opp2List.size() > 0) insert opp2List;
    }
    public static void updOpp2List(List<Opportunity2__c> opp2List){
        if (opp2List != null && opp2List.size() > 0) update opp2List;
    }
    public static void delOpp2List(List<Opportunity2__c> opp2List){
        if (opp2List != null && opp2List.size() > 0) delete opp2List;
    }
 
    public static void insPr2List(List<Product2__c> pr2List){
        if (pr2List != null && pr2List.size() > 0) insert pr2List;
    }
    public static void updelPr2List(List<Product2__c> updPr2List, List<Product2__c> delPr2List){
        if (updPr2List != null && updPr2List.size() > 0) update updPr2List;
        if (delPr2List != null && delPr2List.size() > 0) delete delPr2List;
    }
    public static void delPr2List(List<Product2__c> pr2List){
        if (pr2List != null && pr2List.size() > 0) delete pr2List;
    }
    
    public static void insMBAccountList(List<MB_Account__c> mbaccList){
        if (mbaccList != null && mbaccList.size() > 0) insert mbaccList;
    }
    public static void delMBAccountList(List<Account> accountIds){
        List<MB_Account__c> mbaccs = [select Id, Account__c from MB_Account__c where Account__c in :accountIds];
        if (mbaccs != null && mbaccs.size() > 0) delete mbaccs;
    }
    
    public static void updMBAccountList(List<Account> accountIds){
        List<MB_Account__c> mbaccs = [select Id, Account__r.HP_146POCM_Category_From_Dept__c, Account__r.Province_formula__c, Account__r.Department_Class_Name__c from MB_Account__c where Account__c in :accountIds];
        if (mbaccs.size() > 0) {
            for (MB_Account__c mbacc : mbaccs) {
                mbacc.Opp_OCM_text__c = mbacc.Account__r.HP_146POCM_Category_From_Dept__c;
                mbacc.State_Text__c = mbacc.Account__r.Province_formula__c;
                mbacc.Opportunity_Category_text__c = mbacc.Account__r.Department_Class_Name__c;
            }
            update mbaccs;
        }
    }
    
    // 診療科配下のMBテーブルを更新
    public static void updMBChildFromDpt(Map<Id, Account> accDptMap) {
        if (accDptMap.keySet().size() == 0) return;
        List<MB_Repair__c> mbRepList = [Select Id, Repair__r.Account__c from MB_Repair__c where Repair__r.Account__c IN :accDptMap.keySet()];
        if (mbRepList.size() > 0) {
            for (MB_Repair__c mb : mbRepList) {
                mb.Opp_OCM_text__c = accDptMap.get(mb.Repair__r.Account__c).OCM_Category__c;
                mb.State_Text__c = accDptMap.get(mb.Repair__r.Account__c).State_Text__c;
                mb.Opportunity_Category_text__c = accDptMap.get(mb.Repair__r.Account__c).Department_Class_Name__c;
            }
            update mbRepList;
        }
        List<MB_Event__c> mbEvtList = [Select Id, Event__r.Account_ID__c from MB_Event__c where Event__r.Account_ID__c IN :accDptMap.keySet()];
        if (mbEvtList.size() > 0) {
            for (MB_Event__c mb : mbEvtList) {
                mb.Opp_OCM_text__c = accDptMap.get(mb.Event__r.Account_ID__c).OCM_Category__c;
                mb.State_Text__c = accDptMap.get(mb.Event__r.Account_ID__c).State_Text__c;
                mb.Opportunity_Category_text__c = accDptMap.get(mb.Event__r.Account_ID__c).Department_Class_Name__c;
            }
            update mbEvtList;
        }
        List<MB_Report__c> mbRptList = [Select Id, Report__r.Hospital_Department__c from MB_Report__c where Report__r.Hospital_Department__c IN :accDptMap.keySet()];
        if (mbRptList.size() > 0) {
            for (MB_Report__c mb : mbRptList) {
                mb.Opp_OCM_text__c = accDptMap.get(mb.Report__r.Hospital_Department__c).OCM_Category__c;
                mb.State_Text__c = accDptMap.get(mb.Report__r.Hospital_Department__c).State_Text__c;
                mb.Opportunity_Category_text__c = accDptMap.get(mb.Report__r.Hospital_Department__c).Department_Class_Name__c;
            }
            update mbRptList;
        }
        List<MB_Maintenance_Contract__c> mbmcList = [Select Id, Maintenance_Contract__r.Department__c from MB_Maintenance_Contract__c where Maintenance_Contract__r.Department__c IN :accDptMap.keySet()];
        if (mbmcList.size() > 0) {
            for (MB_Maintenance_Contract__c mb : mbmcList) {
                mb.Opp_OCM_text__c = accDptMap.get(mb.Maintenance_Contract__r.Department__c).OCM_Category__c;
                mb.State_Text__c = accDptMap.get(mb.Maintenance_Contract__r.Department__c).State_Text__c;
                mb.Opportunity_Category_text__c = accDptMap.get(mb.Maintenance_Contract__r.Department__c).Department_Class_Name__c;
            }
            update mbmcList;
        }
        List<MB_Asset__c> mbAstList = [Select Id, Asset__r.AccountId from MB_Asset__c where Asset__r.AccountId IN :accDptMap.keySet()];
        if (mbAstList.size() > 0) {
            for (MB_Asset__c mb : mbAstList) {
                mb.Opp_OCM_text__c = accDptMap.get(mb.Asset__r.AccountId).OCM_Category__c;
                mb.State_Text__c = accDptMap.get(mb.Asset__r.AccountId).State_Text__c;
                mb.Opportunity_Category_text__c = accDptMap.get(mb.Asset__r.AccountId).Department_Class_Name__c;
            }
            update mbAstList;
        }
        // 商談、商談商品、注残について、OCM_Category__c が違う場合のみ 更新対象
        List<MB_Opportunity__c> mboppList = [Select Id, Opportunity__r.AccountId from MB_Opportunity__c where OCM_IsSame__c = false and Opportunity__r.AccountId IN :accDptMap.keySet()];
        if (mboppList.size() > 0) {
            for (MB_Opportunity__c mb : mboppList) {
                mb.Opp_OCM_text__c = accDptMap.get(mb.Opportunity__r.AccountId).OCM_Category__c;
            }
            update mboppList;
        }
        List<MB_OpportunityLineItem__c> mbOliList = [Select Id, Opportunity__r.AccountId from MB_OpportunityLineItem__c where OCM_IsSame__c = false and Opportunity__r.AccountId IN :accDptMap.keySet()];
        if (mbOliList.size() > 0) {
            for (MB_OpportunityLineItem__c mb : mbOliList) {
                mb.Opp_OCM_text__c = accDptMap.get(mb.Opportunity__r.AccountId).OCM_Category__c;
            }
            update mbOliList;
        }
        List<MB_Statu_Achievements__c> mbSAList = [Select Id, Statu_Achievements__r.Opportunity__r.AccountId from MB_Statu_Achievements__c where OCM_IsSame__c = false and Statu_Achievements__r.Opportunity__r.AccountId IN :accDptMap.keySet()];
        if (mbSAList.size() > 0) {
            for (MB_Statu_Achievements__c mb : mbSAList) {
                mb.Opp_OCM_text__c = accDptMap.get(mb.Statu_Achievements__r.Opportunity__r.AccountId).OCM_Category__c;
            }
            update mbSAList;
        }
    }
    public static void updMBChildFromOpp(Map<Id, Opportunity> oppMap) {
        if (oppMap.keySet().size() == 0) return;
        List<MB_Opportunity__c> mboppList = [Select Id, Opportunity__c from MB_Opportunity__c where Opportunity__c IN :oppMap.keySet()];
        if (mboppList.size() > 0) {
            for (MB_Opportunity__c mb : mboppList) {
                mb.State_Text__c = oppMap.get(mb.Opportunity__c).SaleProvince_SAP__c;
                mb.Opportunity_Category_text__c = oppMap.get(mb.Opportunity__c).Opportunity_Category__c;
                mb.Distributor_InCharge_opp__c = oppMap.get(mb.Opportunity__c).Distributor_InCharge_opp__c;
                mb.Group_purchase_PCL__c = oppMap.get(mb.Opportunity__c).Group_purchase_PCL__c;
            }
            update mboppList;
        }
        List<MB_OpportunityLineItem__c> mbOliList = [Select Id, Opportunity__c from MB_OpportunityLineItem__c where Opportunity__c IN :oppMap.keySet()];
        if (mbOliList.size() > 0) {
            for (MB_OpportunityLineItem__c mb : mbOliList) {
                mb.State_Text__c = oppMap.get(mb.Opportunity__c).SaleProvince_SAP__c;
                mb.Opportunity_Category_text__c = oppMap.get(mb.Opportunity__c).Opportunity_Category__c;
                mb.Distributor_InCharge_opp__c = oppMap.get(mb.Opportunity__c).Distributor_InCharge_opp__c;
                mb.Group_purchase_PCL__c = oppMap.get(mb.Opportunity__c).Group_purchase_PCL__c;
            }
            update mbOliList;
        }
        List<MB_Statu_Achievements__c> mbSAList = [Select Id, Statu_Achievements__r.Opportunity__c from MB_Statu_Achievements__c where Statu_Achievements__r.Opportunity__c IN :oppMap.keySet()];
        if (mbSAList.size() > 0) {
            for (MB_Statu_Achievements__c mb : mbSAList) {
                mb.State_Text__c = oppMap.get(mb.Statu_Achievements__r.Opportunity__c).SaleProvince_SAP__c;
                mb.Opportunity_Category_text__c = oppMap.get(mb.Statu_Achievements__r.Opportunity__c).Opportunity_Category__c;
                mb.Distributor_InCharge_opp__c = oppMap.get(mb.Statu_Achievements__r.Opportunity__c).Distributor_InCharge_opp__c;
//                mb.Group_purchase_PCL__c = oppMap.get(mb.Statu_Achievements__r.Opportunity__c).Group_purchase_PCL__c;
            }
            update mbSAList;
        }
    }
    public static void updMBChildFromUser(Map<Id, User> userMap) {
        // 目標について、運用側で、目標画面にて再保存すること
        if (userMap.keySet().size() == 0) return;
        List<MB_Daily_Report__c> mbDRList = [Select Id, Daily_Report__r.Reporter__c from MB_Daily_Report__c where Daily_Report__r.Reporter__c IN :userMap.keySet()];
        if (mbDRList.size() > 0) {
            for (MB_Daily_Report__c mb : mbDRList) {
                mb.State_Text__c = userMap.get(mb.Daily_Report__r.Reporter__c).Province__c;
            }
            update mbDRList;
        }
        List<MB_Event__c> mbEvtList = [Select Id, Event__r.Daily_Report__r.Reporter__c from MB_Event__c where Event__r.Hospital_ID__c = null and Event__r.Daily_Report__r.Reporter__c IN :userMap.keySet()];
        if (mbEvtList.size() > 0) {
            for (MB_Event__c mb : mbEvtList) {
                mb.State_Text__c = userMap.get(mb.Event__r.Daily_Report__r.Reporter__c).Province__c;
            }
            update mbEvtList;
        }
    }
    public static void upUserFederationIdentifier(List<User> userList) {
        update userList;
    }
 
    public static void insMBStatuAchievementList(List<MB_Statu_Achievements__c> ins_mbs){
        if (ins_mbs != null && ins_mbs.size() > 0) insert ins_mbs;
    }
    public static void delMBStatuAchievementList(List<Statu_Achievements__c> del_parents){
        List<MB_Statu_Achievements__c> mbSAList = [select Id, Statu_Achievements__c from MB_Statu_Achievements__c where Statu_Achievements__c in :del_parents];
        if (mbSAList != null && mbSAList.size() > 0) delete mbSAList;
    }
 
    public static void insMBRepairList(List<MB_Repair__c> mbrepairList){
        if (mbrepairList != null && mbrepairList.size() > 0) insert mbrepairList;
    }
    public static void delMBRepairList(List<Repair__c> del_parents){
        List<MB_Repair__c> mbrepairList = [select Id, Repair__c from MB_Repair__c where Repair__c in :del_parents];
        if (mbrepairList != null && mbrepairList.size() > 0) delete mbrepairList;
    }
    
    public static void insMBEventList(List<MB_Event__c> mbeventList){
        if (mbeventList != null && mbeventList.size() > 0) insert mbeventList;
    }
    public static void delMBEventList(List<Event__c> del_parents){
        List<MB_Event__c> mbeventList = [select Id, Event__c from MB_Event__c where Event__c in :del_parents];
        if (mbeventList != null && mbeventList.size() > 0) delete mbeventList;
    }
    
    public static void insMBReportList(List<MB_Report__c> mbreportList){
        if (mbreportList != null && mbreportList.size() > 0) insert mbreportList;
    }
    public static void delMBReportList(List<Report__c> del_parents){
        List<MB_Report__c> mbreportList = [select Id, Report__c from MB_Report__c where Report__c in :del_parents];
        if (mbreportList != null && mbreportList.size() > 0) delete mbreportList;
    }
    
    public static void insMBDRList(List<MB_Daily_Report__c> mbdrList){
        if (mbdrList != null && mbdrList.size() > 0) insert mbdrList;
    }
    public static void delMBDRList(List<Daily_Report__c> del_parents){
        List<MB_Daily_Report__c> mbdrList = [select Id, Daily_Report__c from MB_Daily_Report__c where Daily_Report__c in :del_parents];
        if (mbdrList != null && mbdrList.size() > 0) delete mbdrList;
    }
    
    public static void insMBMCList(List<MB_Maintenance_Contract__c> mbmcList){
        if (mbmcList != null && mbmcList.size() > 0) insert mbmcList;
    }
    public static void delMBMCList(List<Maintenance_Contract__c> del_parents){
        List<MB_Maintenance_Contract__c> mbmcList = [select Id, Maintenance_Contract__c from MB_Maintenance_Contract__c where Maintenance_Contract__c in :del_parents];
        if (mbmcList != null && mbmcList.size() > 0) delete mbmcList;
    }
    
    public static void insMBTgtList(List<MB_Target__c> mbtgtList){
        if (mbtgtList != null && mbtgtList.size() > 0) insert mbtgtList;
    }
    public static void delMBTgtList(List<Opportunity> del_parents){
        List<MB_Target__c> mbtgtList = [select Id, Opportunity__c from MB_Target__c where Opportunity__c in :del_parents];
        if (mbtgtList != null && mbtgtList.size() > 0) delete mbtgtList;
    }
    public static void insMBOppList(List<MB_Opportunity__c> mboppList){
        if (mboppList != null && mboppList.size() > 0) insert mboppList;
    }
    public static void delMBOppList(List<Opportunity> del_parents){
        List<MB_Opportunity__c> mboppList = [select Id, Opportunity__c from MB_Opportunity__c where Opportunity__c in :del_parents];
        if (mboppList != null && mboppList.size() > 0) delete mboppList;
    }
    
    public static void insMBTgtLineItemList(List<MB_TargetLineItem__c> mbTliList){
        if (mbTliList != null && mbTliList.size() > 0) insert mbTliList;
    }
    public static void delMBTgtLineItemList(List<String> del_parentIds){
        List<MB_TargetLineItem__c> mbTliList = [select Id, Opportunity__c from MB_TargetLineItem__c where OpportunityLineItemId__c in :del_parentIds];
        if (mbTliList != null && mbTliList.size() > 0) delete mbTliList;
    }
    public static void insMBOppLineItemList(List<MB_OpportunityLineItem__c> mbOliList){
        if (mbOliList != null && mbOliList.size() > 0) insert mbOliList;
    }
    public static void delMBOppLineItemList(List<String> del_parentIds){
        List<MB_OpportunityLineItem__c> mbOliList = [select Id, Opportunity__c from MB_OpportunityLineItem__c where OpportunityLineItemId__c in :del_parentIds];
        if (mbOliList != null && mbOliList.size() > 0) delete mbOliList;
    }
 
    public static void insMBAssetList(List<MB_Asset__c> mbassList){
        if (mbassList != null && mbassList.size() > 0) insert mbassList;
    }
    public static void delMBAssetList(List<Asset> del_parentIds) {
        List<MB_Asset__c> mbassList = [select Id, Asset__c from MB_Asset__c where Asset__c in :del_parentIds];
        if (mbassList != null && mbassList.size() > 0) delete mbassList;
    }
 
    public static void updDailyReport(Daily_Report__c report) {
        System.debug('Daily_Report__c11111' + report);
        update report;
    }
 
    public static void updMcList(List<Maintenance_Contract__c> mcs) {
        update mcs;
    }
 
    public static void updQuote(Quote quo) {
        update quo;
    }
 
    public static void delOppLine(List<OpportunityLineItem> ols) {
        delete ols;
    }
 
    public static void insOppLine(List<OpportunityLineItem> ols) {
        insert ols;
    }
    
    public static void updateMaintenance_Contract_Estimate(List<Maintenance_Contract_Estimate__c> mces) {
        update mces;
    }
    public static void deleteMaintenance_Contract_Asset_Estimate(List<Maintenance_Contract_Asset_Estimate__c> mcaes) {
        delete mcaes;
    }
    public static void insertMaintenance_Contract_Asset_Estimate(List<Maintenance_Contract_Asset_Estimate__c> mcaes) {
        insert mcaes;
    }
    
    public static void insMaterialFor(List<Material_For__c> mfList) {
        if (mfList != null && mfList.size() > 0) insert mfList;
    }
    
    public static void insProDocMidTbl(List<Product_and_document_middle_table__c> pdmtList) {
        if (pdmtList != null && pdmtList.size() > 0) insert pdmtList;
    }
    
    public static void insCicProMidTbl(List<CIC_case_and_product_middle_table__c> cpmtList) {
        if (cpmtList != null && cpmtList.size() > 0) insert cpmtList;
    }
    
    public static void delMaterialFor(String materialId, List<String> productIds) {
        List<Material_For__c> dels = [select Id from Material_For__c where Material__c = :materialId and Product__c in :productIds];
        if (dels.size() > 0) delete dels;
    }
    
    public static void delProDocMidTbl(String proDocId, List<String> productIds) {
        List<Product_and_document_middle_table__c> dels = [select Id from Product_and_document_middle_table__c where Product_document__c = :proDocId and Product_name__c in :productIds];
        if (dels.size() > 0) delete dels;
    }
    
    public static void delCicProMidTbl(String cicProId, List<String> productIds) {
        List<CIC_case_and_product_middle_table__c> dels = [select Id from CIC_case_and_product_middle_table__c where CIC__c = :cicProId and Product__c in :productIds];
        if (dels.size() > 0) delete dels;
    }
    
//bp2
//    // 备品用
//    public static void updEquipmentSetList(List<Equipment_Set__c> esList) {
//        if (esList != null && esList.size() > 0) update esList;
//    }
//    public static void updEquipmentSet(Equipment_Set__c es) {
//        if (es != null) update es;
////    }
//bp2
//    public static void setEquipmentSetProvisionFlg(Set<Id> esIds) {
//        // 備品Setと貸出備品Set一覧の主従関係を解除したため、こうして備品Setに貸出備品Set一覧の件数を計算するしかない
//        // 件数>0:「引当済」フラグ=True、でなければFalse
//        AggregateResult[] ars = [select Count(Id) cnt, Equipment_Set__c from Rental_Apply_Equipment_Set__c where Equipment_Set__c in :esIds and RAES_Status__c != '上架完了'and RAES_Status__c != '取消分配' group by Equipment_Set__c];
//        List<Equipment_Set__c> esList = new List<Equipment_Set__c>();
//        for (AggregateResult ar : ars) {
//            Equipment_Set__c es = new Equipment_Set__c();
//            // レコードある
//            if (esIds.contains(String.valueOf(ar.get('Equipment_Set__c')))) {
//                esList.add(new Equipment_Set__c(
//                    Id = String.valueOf(ar.get('Equipment_Set__c')),
//                    Provision_finish__c = true
//                ));
//                esIds.remove((Id)String.valueOf(ar.get('Equipment_Set__c')));
//            }
//        }
//        if (esIds.size() > 0) {
//            for (Id id : esIds) {
//                esList.add(new Equipment_Set__c(
//                    Id = id,
//                    Provision_finish__c = false
//                ));
//            }
//        }
//        update esList;
//    }
//bp2
//    public static Equipment_Set__c setEquipmentSetProvisionFlg(Equipment_Set__c es) {
//        // 自分が「上架完了」になるのは、その後トリガでやりますから、ここは自分のIdを抜けて、自分以外の一覧は「上架完了」であるかを判断
//        List<Rental_Apply_Equipment_Set__c> raeslist = [select Id from Rental_Apply_Equipment_Set__c where Equipment_Set__c = :es.Id and Id != :es.Last_Reserve_Rental_Apply_Equipment_Set__c and RAES_Status__c != '上架完了'and RAES_Status__c != '取消分配'];
//        if (raeslist.size() == 0) {
//            es.Provision_finish__c = false;
//        }
//        return es;
//    }
    
//bp2    // 备品Set回库後、ほかの借出备品Set一览を通知
//    public static void informOtherRAES(Id esId, Id lastRAESId) {
//        List<Rental_Apply_Equipment_Set__c> raesList = [select Id, Re_Inform_Mail__c from Rental_Apply_Equipment_Set__c where Equipment_Set__c = :esId and Id != :lastRAESId order by Rental_Start_Date__c];
//        if (raesList.size() > 0) {
//            raesList[0].Re_Inform_Mail__c = (raesList[0].Re_Inform_Mail__c == null || raesList[0].Re_Inform_Mail__c == '0') ? '1' : '0';
//            update raesList[0];
//        }
//    }
    
//bp2
//    public static void insEquipmentSetDetail(List<Equipment_Set_Detail__c> esdList) {
//        if (esdList != null && esdList.size() > 0) insert esdList;
//    }
//    public static void updEquipmentSetDetail(List<Equipment_Set_Detail__c> esdList) {
//        if (esdList != null && esdList.size() > 0) update esdList;
//    }
//    public static void delEquipmentSetDetail(List<Equipment_Set_Detail__c> esdList) {
//        if (esdList != null && esdList.size() > 0) delete esdList;
//    }
 
    public static void insRentalApply(Rental_Apply__c ra) {
        if (ra != null) insert ra;
    }
    public static void updRentalApply(Rental_Apply__c ra) {
        if (ra != null) update ra;
    }
    public static void updRentalApplyList(List<Rental_Apply__c> ra) {
        if (ra.size() > 0) update ra;
    }
    public static void insRentalApplyEquipmentSet(List<Rental_Apply_Equipment_Set__c> raesList) {
        if (raesList != null && raesList.size() > 0) insert raesList;
    }
    public static void delRentalApplyEquipmentSet(List<Rental_Apply_Equipment_Set__c> raesList) {
        if (raesList != null && raesList.size() > 0) delete raesList;
    }
    public static void delConsumableAccessoriesInvoiceSet(List<Consumable_accessories_invoice__c> raesList) {
        if (raesList != null && raesList.size() > 0) delete raesList;
    }
 
////bp2
//    public static void RAESDetailRollup(List<Id> raesIds) {
//        Map<Id, AggregateResult> allCntAr = new Map<Id, AggregateResult>([
//                select count(Id) Cnt_Id, Rental_Apply_Equipment_Set__c Id
//                  from Rental_Apply_Equipment_Set_Detail__c
//                 where Rental_Apply_Equipment_Set__c in : raesIds
//                 group by Rental_Apply_Equipment_Set__c
//        ]);
//        Map<Id, AggregateResult> cliCntAr = new Map<Id, AggregateResult>([
//                select count(Id) Cnt_Id, Rental_Apply_Equipment_Set__c Id
//                  from Rental_Apply_Equipment_Set_Detail__c
//                 where Rental_Apply_Equipment_Set__c in : raesIds
//                   and Check_lost_Item__c = '欠品'
//                 group by Rental_Apply_Equipment_Set__c
//        ]);
//        Map<Id, AggregateResult> cdsCntAr = new Map<Id, AggregateResult>([
//                select count(Id) Cnt_Id, Rental_Apply_Equipment_Set__c Id
//                  from Rental_Apply_Equipment_Set_Detail__c
//                 where Rental_Apply_Equipment_Set__c in : raesIds
////bp2                   and CDS_complete_time__c = null
//                   and Asset__r.Loaner_CDS_Info__c = '需要清洗'
//                 group by Rental_Apply_Equipment_Set__c
//        ]);
//        Map<Id, AggregateResult> iraCntAr = new Map<Id, AggregateResult>([
//                select count(Id) Cnt_Id, Rental_Apply_Equipment_Set__c Id
//                  from Rental_Apply_Equipment_Set_Detail__c
//                 where Rental_Apply_Equipment_Set__c in : raesIds
//                   and Inspection_result_after__c = 'NG'
//                 group by Rental_Apply_Equipment_Set__c
//        ]);
//        Map<Id, AggregateResult> aiwCntAr = new Map<Id, AggregateResult>([
//                select count(Id) Cnt_id, Rental_Apply_Equipment_Set__c Id
//                  from Rental_Apply_Equipment_Set_Detail__c
//                 where Rental_Apply_Equipment_Set__c in : raesIds
//                   and Arrival_in_wh__c = false
//                 group by Rental_Apply_Equipment_Set__c
//        ]);
//        Map<Id, Rental_Apply_Equipment_Set__c> raesUpdMap = new Map<Id, Rental_Apply_Equipment_Set__c>();
//        for (Id raesId : raesIds) {
//            Rental_Apply_Equipment_Set__c raes = raesUpdMap.get(raesId);
//            if (raes == null) {
//                // raesIds に重複がある場合の対応、親Idなので配下のものを一緒に処理するとき発生します。
//                // 集計した値は同じのはず、一回だけ設定すればいいです。
//                raes = new Rental_Apply_Equipment_Set__c(
//                        Id = raesId,
//                        Count_Detail__c = 0,
//                        Count_Lost__c = 0,
//                        Count_NotComplete_CDS__c = 0,
//                        Count_NG_Inspection_Result_After__c = 0,
//                        Count_Not_Arrival_in_wh__c = 0
//                );
//                raesUpdMap.put(raesId, raes);
//                if (allCntAr.get(raesId) != null) {
//                    raes.Count_Detail__c                     = Integer.valueOf(allCntAr.get(raesId).get('Cnt_Id'));
//                }
//                if (cliCntAr.get(raesId) != null) {
//                    raes.Count_Lost__c                       = Integer.valueOf(cliCntAr.get(raesId).get('Cnt_Id'));
//                }
//                if (cdsCntAr.get(raesId) != null) {
//                    raes.Count_NotComplete_CDS__c            = Integer.valueOf(cdsCntAr.get(raesId).get('Cnt_Id'));
//                }
//                if (iraCntAr.get(raesId) != null) {
//                    raes.Count_NG_Inspection_Result_After__c = Integer.valueOf(iraCntAr.get(raesId).get('Cnt_Id'));
//                }
//                if (aiwCntAr.get(raesId) != null) {
//                    raes.Count_Not_Arrival_in_wh__c          = Integer.valueOf(aiwCntAr.get(raesId).get('Cnt_Id'));
//                }
//            }
//        }
//        update raesUpdMap.values();
//    }
 
    // Assetから病院に積み上げよう
    public static AggregateResult[] selectAssetSetHospitalCount(Set<Id> hpIds) {
        return [select Account.Parent.ParentId Parent_ParentId,
                       Sum(This_year_inspection_times__c) SUM_inspection_times,
                       Sum(This_year_inspection_count__c) SUM_inspection_count
                  from Asset where Account.Parent.ParentId in : hpIds
                group by Account.Parent.ParentId];
    }
    // Assetから戦略科室に積み上げよう
    public static AggregateResult[] selectAssetSetDCCount(Set<Id> dcIds) {
        return [select Account.ParentId Parent_Id,
                       Sum(This_year_inspection_times__c) SUM_inspection_times,
                       Sum(This_year_inspection_count__c) SUM_inspection_count
                  from Asset where Account.ParentId in : dcIds
                group by Account.ParentId];
    }
    //日报用的,显示不属于自身权限的医院
    public static List<Account> ShowAccount(list<String> AccountIdList){
        List<Account> accountList = [select id,Name from Account where Id in :AccountIdList];
        return accountList;
    }
    public static List<Campaign> ShowCampaign(list<String> CampaignIdList){
        List<Campaign> campaignList = [select Id, Name from Campaign where Id in :CampaignIdList];
        return campaignList;
    }
    // Smarm__cからUserに積み上げよう
    public static AggregateResult[] selectSmarmSetUserCount(Set<Id> userIds, List<Id> delIds) {
        if (delIds.size() == 0) {
            return [select Review_Target__c Review_Target,
                           COUNT(Id) Cnt_Id,
                           Max(Report_Date__c) Max_Report_Date
                      from SMARM__c where Review_Target__c in : userIds
                    group by Review_Target__c];
        } else {
            return [select Review_Target__c Review_Target,
                           COUNT(Id) Cnt_Id,
                           Max(Report_Date__c) Max_Report_Date
                      from SMARM__c where Review_Target__c in : userIds
                       and Id not in : delIds
                    group by Review_Target__c];
        }
    }
    public static void updateUserList(List<User> userList) {
        update userList;
    }
 
    public static void upsertAsset(List<Asset> astList) {
        if (astList.size() > 0) {
            upsert astList;
        }
    }
    public static void deleteAsset(List<Id> astIds) {
        if (astIds.size() > 0) {
            delete [Select Id from Asset where Id In: astIds];
        }
    }
 
    // SoNo_DeliveryDate_Text__c にて upsert
    public static void upsertStatuAchievementsJournalByKey(List<Statu_Achievements_Journal__c> pList) {
        if (pList.size() > 0) {
            upsert pList SoNo_DeliveryDate_Text__c;
        }
    }
    public static List<Statu_Achievements_Journal__c> selectStatuAchievementsJournalByKey(List<String> pList) {
        return [Select SoNo_DeliveryDate_Text__c, ShippedAmount__c from Statu_Achievements_Journal__c where SoNo_DeliveryDate_Text__c in :pList];
    }
    
    // CHAN-BCPCA3  插入并更新 虚拟 DN start
    public static void upsertStatuAchievementsDNByKey(List<Statu_Achievements_DN__c> pList) {
        if (pList.size() > 0) {
            upsert pList DNKey__c;
        }
    }
    // CHAN-BCPCA3 插入并更新 虚拟 DN end
    
    public static void deleteStatuAchievementsJournalByKey(List<String> pList) {
        for(List<Statu_Achievements_Journal__c> delList : [Select SoNo_DeliveryDate_Text__c, ShippedAmount__c from Statu_Achievements_Journal__c where SoNo_DeliveryDate_Text__c in :pList]) {
            delete delList;
        }
    }
 
    // 省単位 or 全国の診療科を検索,最初の50件
    public static Map<Id, Account> selectDepartByHospitalState(String nameCondition, String reporterState, Integer limitCnt) {
        User loginUser = [Select Id, State_Hospital__c, Job_Category__c from User where Id =: UserInfo.getUserId()];
        String queryString = 'select Id, Name, Department_Class__c, Department_Class__r.Name, Hospital__c, Hospital__r.Name from Account where' + nameCondition + ' Hospital__r.RecordType.DeveloperName = \'HP\' and Is_Active__c <> \'無効\'';
        if (loginUser.Job_Category__c == 'GI市场'
                || loginUser.Job_Category__c == 'SP市场'
                || loginUser.Job_Category__c == '服务本部'
                || loginUser.Job_Category__c == '培训'
        ) {
            // 全国範囲、なにもしない
        } else {
            // 省単位の条件追加
            system.debug('selectDepartByHospitalState reporterState=' + reporterState);
            queryString += ' and Parent.Parent.State_Master__r.Name = :reporterState';
        }
        queryString += ' order by Name limit :limitCnt';
        system.debug('selectDepartByHospitalState queryString=' + queryString);
        return new Map<Id, Account>((List<Account>) Database.query(queryString));
    }
 
    public static void updateAgencyName(Map<Id, Account> hpNameAfterAccMap) {
        List<Agency_Hospital_Link__c> ahls = [Select Id, Name,Hospital__c From Agency_Hospital_Link__c where Hospital__c in :hpNameAfterAccMap.keySet()];
        List<Agency_Hospital_Link__c> updAHList = new List<Agency_Hospital_Link__c>();
        if (ahls.size() > 0) {
            for (Agency_Hospital_Link__c ahl: ahls) {
                Account hp = hpNameAfterAccMap.get(ahl.Hospital__c);
                String hpName = hp.Name;
                if (ahl.Name != hpName) {
                    ahl.Name = hpName;
                    updAHList.add(ahl);
                }
            }
            update updAHList;
        }
    }
 
    public static void updateDeptName(Map<Id, Account> hpAfterAccMap) {
        if (hpAfterAccMap.size() > 0) {
            // 変更必要な 戦略課室、IDを集める
            List<String> dcNameIds = new List<String>();
            List<Account> updAccList = new List<Account>();
            List<Account> updChkList = new List<Account>();
            // 戦略課室ID:NAME
            Map<String, String> dcNameMap = new Map<String, String>();
            // 戦略課室名称を設定
            List<Account> accDcs = [Select Id, Name, ParentId, Parent.RecordTypeId, Department_Class_Label__c from Account where ParentId IN :hpAfterAccMap.keySet()];
            if (accDcs.size() > 0) {
                for (Account child: accDcs) {
                    dcNameIds.add(child.Id);
                    if (child.Name != hpAfterAccMap.get(child.ParentId).Name + ' ' + child.Department_Class_Label__c) {
                        child.Name = hpAfterAccMap.get(child.ParentId).Name + ' ' + child.Department_Class_Label__c;
                        // 入力規則回避
                        child.Sys_Dept_Name_Change_Chk__c = true;
                        updChkList.add(child);
                    }
                    child.OCM_Category__c = hpAfterAccMap.get(child.ParentId).OCM_Category__c;
                    child.State_Text__c = hpAfterAccMap.get(child.ParentId).State_Text__c;
                    dcNameMap.put(child.Id, child.Name);
                    updAccList.add(child);
                }
                // 診療科名称を設定
                List<Account> accDpts = [Select Id, Name, ParentId, Parent.ParentId, Department_Name__c from Account where ParentId IN :dcNameIds];
                if (accDpts.size() > 0) {
                    for (Account child: accDpts) {
                        child.Name = dcNameMap.get(child.ParentId) + ' ' + child.Department_Name__c;
                        child.OCM_Category__c = hpAfterAccMap.get(child.Parent.ParentId).OCM_Category__c;
                        child.State_Text__c = hpAfterAccMap.get(child.Parent.ParentId).State_Text__c;
                        updAccList.add(child);
                    }
                }
                update updAccList;
                // 入力規則回復
                if (updChkList.size() > 0) {
                    for (Account child: updChkList) {
                        child.Sys_Dept_Name_Change_Chk__c = false;
                    }
                    update updChkList;
                }
            }
        }
    }
    
    public static void collectDeptId(List<String> accIds, Map<String, String> purposeOfAdviceMap, List<String> hospitalIds) {
        if (hospitalIds.size() > 0) {
            List<Account> accList = [Select Id, Name, Is_Active__c, Hospital__c from Account where Hospital__c IN :hospitalIds];
            for (Account acc : accList) {
                accIds.add(acc.Id);
                purposeOfAdviceMap.put(acc.Id, purposeOfAdviceMap.get(acc.Hospital__c));
            }
        }
    }
    
    public static void collectChildIdForAgent(List<String> accIds, Map<String, String> purposeOfAdviceMap, List<String> agentIds) {
        if (agentIds.size() > 0) {
            //-----------20180913---------XinHongLu-------------------Start--------------------
            //Is_Active_Formula__c = '有效',该条件为"契约"为有效时,我们传给sap
            //-----------20180913---------XinHongLu-------------------End--------------------
            List<Account> accList = [Select Id, Name, Is_Active__c, Agent_Ref__c, AgencyContract_Management_Code__c from Account where Is_Active_Formula__c = '有效' and Agent_Ref__c IN :agentIds order by Agent_Ref__c, AgencyContract_Management_Code__c, CreatedDate desc];
            if (accList.size() > 0) update accList;
            String tmpAgentRef = null;
            String tmpAgencyContractManagementCode = null;
            for (Account acc : accList) {
                if ((tmpAgentRef == null || tmpAgentRef != acc.Agent_Ref__c)
                    || (tmpAgencyContractManagementCode == null || tmpAgencyContractManagementCode != acc.AgencyContract_Management_Code__c)) {
                    tmpAgentRef = acc.Agent_Ref__c;
                    tmpAgencyContractManagementCode = acc.AgencyContract_Management_Code__c;
                    accIds.add(acc.Id);
                    purposeOfAdviceMap.put(acc.Id, purposeOfAdviceMap.get(acc.Agent_Ref__c));
                    NFM001Controller.debug_msg += '_1';
System.debug(Logginglevel.DEBUG, 'collectChildIdForAgent acc.AgencyContract_Management_Code__c:::::' + acc.AgencyContract_Management_Code__c);
                }
            }
        }
    }
//    public static List<Account> getDoubleChildForAgent(Map<String, Account> agentStateIds) {
//        List<Account> childList = new List<Account>();
//        if (agentStateIds.size() > 0) {
//            childList = [Select Id, Agency_State_Master__c, AgencyContract_Management_Code__c from Account where RecordType.Name IN ('契約') and Agency_State_Master__c IN :agentStateIds.keySet() and Id NOT IN :agentStateIds.values()];
//        }
//        return childList;
//    }
 
    public static void updateDeptIsActive(List<String> accIds, Map<String, String> purposeOfAdviceMap,
            List<String> hospitalIdsNeedUpdateAccountIsActive, Map<Id, String> hpIsActiveMap, Map<Id, String> hpDateToMap) {
        if (hospitalIdsNeedUpdateAccountIsActive.size() > 0) {
            List<Account> accList = [
              Select Id, Name,Is_Active__c, DepartmentEffectiveDateTo__c, Hospital__c, Hospital__r.DepartmentEffectiveDateTo__c
                from Account
               where Hospital__c IN :hospitalIdsNeedUpdateAccountIsActive];
            List<Account> accUpdList = new List<Account>();
            for (Account acc : accList) {
                if (acc.Is_Active__c == hpIsActiveMap.get(acc.Hospital__c)) {
                    // 病院(変更後)と診療科のIs_Active__cが同じの場合
                    continue;
                }
                if (hpIsActiveMap.get(acc.Hospital__c) == '無効' && acc.DepartmentEffectiveDateTo__c == null) {
                    // 無効に変更する、診療科の有効終了日がnullのものが対象、処理対象
System.debug(Logginglevel.DEBUG, '無効に変更する、診療科の有効終了日がnullのものが対象、処理対象');
                }
                else if (hpIsActiveMap.get(acc.Hospital__c) == '有効' && acc.DepartmentEffectiveDateTo__c == acc.Hospital__r.DepartmentEffectiveDateTo__c) {
                    // 無効に変更する、診療科の有効終了日が病院(変更前)と同じのものが対象、処理対象
System.debug(Logginglevel.DEBUG, '無効に変更する、診療科の有効終了日が病院と同じのものが対象、処理対象');
                } else {
System.debug(Logginglevel.DEBUG, '処理対象外、病院Is_Active__c=' + hpIsActiveMap.get(acc.Hospital__c) + ', 診療科Dateto=' + acc.DepartmentEffectiveDateTo__c + ', 病院Dateto=' + hpDateToMap.get(acc.Hospital__c));
                    continue;
                }
                accIds.add(acc.Id);
                purposeOfAdviceMap.put(acc.Id, purposeOfAdviceMap.get(acc.Hospital__c));
System.debug(Logginglevel.DEBUG, 'purposeOfAdviceMap 病院=' + purposeOfAdviceMap.get(acc.Hospital__c));
                accUpdList.add(acc);
                acc.Is_Active__c = hpIsActiveMap.get(acc.Hospital__c);
                acc.DepartmentEffectiveDateTo__c = hpDateToMap.get(acc.Hospital__c);
            }
            if (accUpdList.size() > 0) {
                update accUpdList;
            }
        }
    }
    //CHAN-AZJ6JS 追溯系统来的询价,取消WIN时,经销商订单自动改到“驳回”
    public static void selectAndupdateOrderSatus(List<String> idList) {
        List<Consumable_order__c> orderList = [select id, Order_status__c from Consumable_order__c where Name = :idList and Order_status__c = '批准' and RecordType.DeveloperName = 'Order'];
        for (Consumable_order__c order : orderList) {
            order.Order_status__c = '驳回';
        }
        update orderList;
    }
    //更新订单
    public static void updateOrderSatus(List<Consumable_order__c> docList) {
        update docList;
    }
    //更新明细2
    public static void updateOrderDetailsSatus(List<Consumable_order_details2__c> docList) {
        update docList;
    }
    //更新明细1
    public static void updateOrderDetails1Satus(List<Consumable_orderdetails__c> docList) {
        update docList;
    }
    
    public static void updRentalApplyList(List<Consumable_order__c> ra) {
        if (ra.size() > 0) update ra;
    }
    
    public static List<Event__c> getEventCList(Date whereDate, Daily_Report__c oya) {
        return [
            select Id, Event_ID__c, Daily_Report__c, Subject__c, StartDateTime__c, EndDateTime__c, Main_Visit_Location__c,
                    Location__c, whatId__c, Activity_Type2__c, Activity_Type2_Before__c,
                    Visitor1__c, Visitor2__c, Visitor3__c, Visitor4__c, Visitor5__c,
                    Visitor1_ID__c, Visitor2_ID__c, Visitor3_ID__c, Visitor4_ID__c, Visitor5_ID__c, 
                    Companion__c, Purpose__c, Purpose_Type__c, Purpose_Type2__c, Purpose_Type3__c, Purpose_Type4__c, Purpose_Type5__c,
                    Purpose_TypeFSE__c, Purpose_TypeFSE2__c, Purpose_TypeFSE3__c, Purpose_TypeFSE4__c, Purpose_TypeFSE5__c,
                    Purpose_TypeEscFSE__c, Purpose_TypeEscFSE2__c, Purpose_TypeEscFSE3__c, Purpose_TypeEscFSE4__c, Purpose_TypeEscFSE5__c,
                    Related_Opportunity1__c, Related_Opportunity2__c, Related_Opportunity3__c, Related_Opportunity4__c, Related_Opportunity5__c,
                    Related_Opportunity1_ID__c, Related_Opportunity2_ID__c, Related_Opportunity3_ID__c, Related_Opportunity4_ID__c, Related_Opportunity5_ID__c,
                    Related_Service1__c, Related_Service2__c,
                    Related_Service1_ID__c, Related_Service2_ID__c,
                    Description__c, Hospital_Info__c, Doctor_Info__c, Technology_Treatment__c,
                    New_Query__c, Update_Query__c, Lost_Info__c, VOC__c, Meeting_Info__c, Product_Description_Id__c,
                    Maintenance_Contract_ID__c, Asset_Manual_ID__c, Rental_Apply_ID__c,
                    OPD_ID__c, NTC_ID__c, ReportAccompanied_ID__c, CityStatus_ID__c, Conflict_ID__c, Claim_ID__c, Improvement_ID__c, OnCall_ID__c,
                    nextPlanDate__c, nextPlanTimePurpose__c, Activity_ID__c,
                    Minister__c, Minister_Comment__c, Manager__c, Manager_Comment__c,
                    Free_Input__c, Visitor_Place_Free__c, Mail_Send_Btn__c,
                    Lead_ID__c, Lead_Count__c, InsReport_ID__c,
                    Activity_Purpose__c,Activity_PurposeFSE__c,Activity_PurposeEscFSE__c,ETAPPAct__c
                      ,IsAlertInputDep__c // 2018/11/21 SWAG-B6Q8BS 判断是否需要弹窗更新客户信息
                      ,SLARecorded__c,UseReport__c,SLAReportInfo__c//20210701 zh SLA 
                    // 20200420 任务日报管理 add gzw start 
                    // ,eventStatus__c, delayToDate__c, delayReason__c,DurationInMinutes__c,BeforeActivityDate__c,OPDPlan_Flag__c,IsScheduled__c,AppCdId__c,SyncCreatedDate__c
                      
                    ,eventStatus__c, CancelReason__c, delayToDate__c, delayReason__c,DurationInMinutes__c,cancelReasonSelect__c,cancelReasonSelectFSE__c,cancelReasonOther__c,delayReasonOther__c,delayReasonSelect__c,delayReasonSelectFSE__c,BeforeActivityDate__c,OPDPlan_Flag__c,IsScheduled__c,AppCdId__c,SyncCreatedDate__c
                    // 20200420 任务日报管理 add gzw end
                    //,OPD_plan__c // 2022-4-14 yjk 增加OPD计划
            from Event__c where ActivityDate__c =:whereDate and Daily_Report__c = :oya.Id order by StartDateTime__c
        ];
    }
    
    public static List<Event__c> getNextEventCList(List<String> nextEcIds) {
        return [
            select Id, Event_ID__c, Daily_Report__c, Subject__c, StartDateTime__c, EndDateTime__c, Main_Visit_Location__c,
                    Location__c, whatId__c, Activity_Type2__c, Activity_Type2_Before__c,
                    Visitor1__c, Visitor2__c, Visitor3__c, Visitor4__c, Visitor5__c,
                    Visitor1_ID__c, Visitor2_ID__c, Visitor3_ID__c, Visitor4_ID__c, Visitor5_ID__c, 
                    Companion__c, Purpose__c, Purpose_Type__c, Purpose_Type2__c, Purpose_Type3__c, Purpose_Type4__c, Purpose_Type5__c,
                    Purpose_TypeFSE__c, Purpose_TypeFSE2__c, Purpose_TypeFSE3__c, Purpose_TypeFSE4__c, Purpose_TypeFSE5__c,
                    Purpose_TypeEscFSE__c, Purpose_TypeEscFSE2__c, Purpose_TypeEscFSE3__c, Purpose_TypeEscFSE4__c, Purpose_TypeEscFSE5__c,
                    Related_Opportunity1__c, Related_Opportunity2__c, Related_Opportunity3__c, Related_Opportunity4__c, Related_Opportunity5__c,
                    Related_Opportunity1_ID__c, Related_Opportunity2_ID__c, Related_Opportunity3_ID__c, Related_Opportunity4_ID__c, Related_Opportunity5_ID__c,
                    Related_Service1__c, Related_Service2__c,
                    Related_Service1_ID__c, Related_Service2_ID__c,
                    Description__c, Hospital_Info__c, Doctor_Info__c, Technology_Treatment__c,
                    New_Query__c, Update_Query__c, Lost_Info__c, VOC__c, Meeting_Info__c, Product_Description_Id__c,
                    Maintenance_Contract_ID__c, Asset_Manual_ID__c, Rental_Apply_ID__c,
                    OPD_ID__c, NTC_ID__c, ReportAccompanied_ID__c, CityStatus_ID__c, Conflict_ID__c, Claim_ID__c, Improvement_ID__c, OnCall_ID__c,
                    nextPlanDate__c, nextPlanTimePurpose__c, Activity_ID__c,
                    Minister__c, Minister_Comment__c, Manager__c, Manager_Comment__c,
                    Free_Input__c, Visitor_Place_Free__c, Mail_Send_Btn__c,
                    Lead_ID__c, Lead_Count__c, InsReport_ID__c,
                    Activity_Purpose__c,Activity_PurposeFSE__c,Activity_PurposeEscFSE__c
                    ,IsAlertInputDep__c // 2018/11/21 SWAG-B6Q8BS 判断是否需要弹窗更新客户信息
            from Event__c where Id in :nextEcIds order by StartDateTime__c
        ];
    }
    
    public static Map<String, Map<String, String>> getAccsByName(List<String> accList) {
        Map<String, Map<String, String>> accMap = new Map<String, Map<String, String>>();
        Map<String, String> accIds = new Map<String, String>();
        
        List<Account> accs = [select Id, Name from Account where Name in : accList];
        for (Account acc : accs) {
            if (accMap.containsKey(acc.Name)) {
                accIds = accMap.get(acc.Name);
            } else {
                accIds = new Map<String, String>();
            }
            accIds.put(acc.Id, acc.Id);
            accMap.put(acc.Name, accIds);
        }
        return accMap;
    }
    
    public static Map<String, Map<String, String>> getCampsByName(List<String> campList) {
        Map<String, Map<String, String>> campMap = new Map<String, Map<String, String>>();
        Map<String, String> campIds = new Map<String, String>();
        
        List<Campaign> camps = [select Id, Name from Campaign where Name in : campList];
        for (Campaign camp : camps) {
            if (campMap.containsKey(camp.Name)) {
                campIds = campMap.get(camp.Name);
            } else {
                campIds = new Map<String, String>();
            }
            campIds.put(camp.Id, camp.Id);
            campMap.put(camp.Name, campIds);
        }
        return campMap;
    }
 
    // CHAN-BE6CZZ 最后跟进结果 LHJ 20190724 Start
    //public static AggregateResult[] selectForOpp_Last_Follow_Up_Date(List<String> oppIds) {    
        //return [select Opportunity__c, Max(End_Time__c) maxET from Event_Oppotunity__c where Opportunity__c in : oppIds
        //        and Daily_Report__r.Status_With_Check__c <> '草案中' and Daily_Report__r.Status_With_Check__c <> ''
        //        group by Opportunity__c];
    //}
    public static List<Event_Oppotunity__c> selectForOpp_Last_Follow_Up_Date(List<String> oppIds) {
        return [select Opportunity__c, End_Time__c, EventC_ID__r.Description__c
                  from Event_Oppotunity__c 
                 where Opportunity__c in : oppIds
                   and Daily_Report__r.Status_With_Check__c <> '草案中' 
                   and Daily_Report__r.Status_With_Check__c <> ''
              order by Opportunity__c, End_Time__c desc
              ];
    }
    // CHAN-BE6CZZ 最后跟进结果 LHJ 20190724 Start
 
    
    public static List<Event> selectForOpp_Last_Visit_Scheduled_Date(List<String> oppIds) {
        // Max(ActivityDateTime)がつかえないため、group by をやめました。
        return [select Id, Related_Opportunity1_ID__c, ActivityDateTime from Event where Related_Opportunity1_ID__c != null and Related_Opportunity1_ID__c in :oppIds
                order by Related_Opportunity1_ID__c, ActivityDateTime desc];
    }
 
    public static AggregateResult[] selectEventOppForAggregateFollowToOpp(List<String> oppIds) {
        return [select Opportunity__c
                       , count(Name) cnt
                       , sum(Visit_President_Flag__c) vprCnt
                       , sum(Visit_Head_Doctor_Flag__c) vhdCnt
                       , sum(NTC_Flag__c) ntcCnt
                  from Event_Oppotunity__c where Opportunity__c in :oppIds
                  and Daily_Report__r.Status_With_Check__c <> '草案中' and Daily_Report__r.Status_With_Check__c <> ''
                  group by Opportunity__c];
    }
    
    public static List<Report__c> selectReportForAggregateOpdToOpp(List<String> oppIds) {
        return [select Opportunity1__c, Opportunity2__c, Opportunity3__c, Opportunity4__c, Opportunity5__c
                  from Report__c where Status__c <> '作成中' and Status__c <> '取消し' and Status__c <> ''
                  and (Opportunity1__c in :oppIds or Opportunity2__c in :oppIds or Opportunity3__c in :oppIds or Opportunity4__c in :oppIds or Opportunity5__c in :oppIds)
                  and RecordType.DeveloperName = 'OPD'];
    }
 
    // 5つの商談を見るため、group by ができないので、検索後loopして集計する
    public static AggregateResult[] selectForService_Last_Follow_Up_Date(List<String> serviceIds) {
        return [select Service__c, Max(Date__c) maxD from Event_Service__c where Service__c in : serviceIds
                and Daily_Report__r.Status_With_Check__c <> '草案中' and Daily_Report__r.Status_With_Check__c <> ''
                group by Service__c];
    }
    
    public static void updateContactMonth(List<String> conIds, List<Date> conDates) {
        Map<String, Integer> conCntMap = new Map<String, Integer>();
        AggregateResult[] ar = [select count(Id) cnt, Contact__c, Date__c from Activity_History_Daily_Report__c
                                where Daily_Report__r.Status_With_Check__c <> '草案中' and Daily_Report__r.Status_With_Check__c <> ''
                                and Contact__c in :conIds group by Contact__c, Date__c];
        if (ar.size() > 0) {
            for (Integer i = 0; i < ar.size(); i++) {
                Date actDate = (Date) ar[i].get('Date__c');
                String key = String.valueOf(ar[i].get('Contact__c')) + String.valueOf(actDate.year()) + (actDate.month() < 10 ? '0' + actDate.month() : '' + actDate.month());
                if (conCntMap.containsKey(key)) {
                    conCntMap.put(key, conCntMap.get(key) + Integer.valueOf(ar[i].get('cnt')));
                } else {
                    conCntMap.put(key, Integer.valueOf(ar[i].get('cnt')));
                }
            }
        }
        
        // ここから12ヶ月のカウントを更新
        Map<Id, Contact> conThisMap = new Map<Id, Contact>([select Id, Visit_Count1__c, Visit_Count2__c, Visit_Count3__c, Visit_Count4__c, Visit_Count5__c, Visit_Count6__c, 
                                                            Visit_Count7__c, Visit_Count8__c, Visit_Count9__c, Visit_Count10__c, Visit_Count11__c, Visit_Count12__c 
                                                            from Contact where Id in :conIds for update]);
        if (conThisMap.size() > 0) {
            Map<String, Contact> updMap = new Map<String, Contact>();
            for (Integer i = 0; i < conIds.size(); i++) {
                Contact con = conThisMap.get(conIds[i]);
                if (updMap.containsKey(con.Id)) {
                    con = updMap.get(con.Id);
                }
                
                if (con != null) {
                    Date repDate = conDates[i];
                    Integer year = repDate.year();
                    Integer month = repDate.month();
                    
                    Integer cnt = null;
                    if (conCntMap != null) {
                        cnt = conCntMap.get(con.Id + '' + year + ((month < 10) ? '0' : '') + month);
                    }
                    if(month == 1) {
                        if (!equalTwoNum(con.Visit_Count1__c, cnt)) {
                            con.Visit_Count1__c = cnt;
                        }
                    } else if(month == 2) {
                        if (!equalTwoNum(con.Visit_Count2__c, cnt)) {
                            con.Visit_Count2__c = cnt;
                        }
                    } else if(month == 3) {
                        if (!equalTwoNum(con.Visit_Count3__c, cnt)) {
                            con.Visit_Count3__c = cnt;
                        }
                    } else if(month == 4) {
                        if (!equalTwoNum(con.Visit_Count4__c, cnt)) {
                            con.Visit_Count4__c = cnt;
                        }
                    } else if(month == 5) {
                        if (!equalTwoNum(con.Visit_Count5__c, cnt)) {
                            con.Visit_Count5__c = cnt;
                        }
                    } else if(month == 6) {
                        if (!equalTwoNum(con.Visit_Count6__c, cnt)) {
                            con.Visit_Count6__c =cnt;
                        }
                    } else if(month == 7) {
                        if (!equalTwoNum(con.Visit_Count7__c, cnt)) {
                            con.Visit_Count7__c = cnt;
                        }
                    } else if(month == 8) {
                        if (!equalTwoNum(con.Visit_Count8__c, cnt)) {
                            con.Visit_Count8__c = cnt;
                        }
                    } else if(month == 9) {
                        if (!equalTwoNum(con.Visit_Count9__c, cnt)) {
                            con.Visit_Count9__c = cnt;
                        }
                    } else if(month == 10) {
                        if (!equalTwoNum(con.Visit_Count10__c, cnt)) {
                            con.Visit_Count10__c = cnt;
                        }
                    } else if(month == 11) {
                        if (!equalTwoNum(con.Visit_Count11__c, cnt)) {
                            con.Visit_Count11__c = cnt;
                        }
                    } else if(month == 12){
                        if (!equalTwoNum(con.Visit_Count12__c, cnt)) {
                            con.Visit_Count12__c = cnt;
                        }
                    } else {
                        // TODO Exception
                    }
                    updMap.put(con.Id, con);
                }
            }
            List<Contact> updCon = updMap.values();
            if (updCon.size() > 0) update updCon;
        }
    }
    
    public static List<SObject> getPe99Info(String soql, String userId) {
        return Database.query(soql);
    }
    
    public static Boolean checkInsHpChange(Id irHpId, Map<Id, Id> iiHpMap) {
        Boolean isChange = false;
        for (String key : iiHpMap.keySet()) {
            Id iiHpId = iiHpMap.get(key);
            if (irHpId != iiHpId) {
                isChange = true;
                break;
            }
        }
        return isChange;
    }
    
    
    // equal:true
    private static Boolean equalTwoNum(Decimal val1, Integer val2) {
        if (val1 == null && val2 == null) {
            return true;
        } else if (val1 != null && val2 != null && val1 == Decimal.valueOf(val2)) {
            return true;
        } else {
            return false;
        }
    }
    
    // JS用检索
    @ReadOnly
    @RemoteAction
    global static String getQueryJson(String sql) {
        system.debug('=====sql:' + sql);
        List<SObject> rs = Database.query(sql);
        String rsStr = JSON.serialize(rs);
        system.debug('=====rsStr:' + rsStr);
        return rsStr;
    }
    
    // JS用更新
    @ReadOnly
    @RemoteAction
    global static String getUpdateResult(String j) {
        system.debug('=====json:' + j);
        SObject obj = (SObject)JSON.deserializeStrict(j, SObject.class);
        Database.SaveResult rs = Database.update(obj);
        String rsStr = rs.isSuccess() ? '1' : '0';
        system.debug('=====rsStr:' + rsStr);
        return rsStr;
    }
    
    WebService static String getAccessToken() {
        return UserInfo.getSessionId();
    }
    
    WebService static void addBatchIfLog(String typeStr, Integer isError, String logStr) {
        BatchIF_Log__c log = new BatchIF_Log__c(
            Type__c = typeStr,
            Is_Error__c = isError
        );
        if (isError == 0) {
            log.log__c = logStr;
        } else {
            log.ErrorLog__c = logStr;
        }
        insert log;
    }
    
    @AuraEnabled
    WebService static String deleteRepair(String rid) {
        try {
            Repair__c r = new Repair__c(Id = rid);
            delete r;
            return 'OK';
        } catch (Exception e) {
            return e.getMessage();
        }
    }
    /*
    =======================================================================================================================
    ===================================================SI 询价部分util集合=================================================
    =======================================================================================================================
    */
    /**
    OCM-SI需求表用,复制功能,仅限当前所有SI需求表失效的时候,才能使用
    */
    @AuraEnabled
    WebService static String ISO_Copy_Func(id isoID){
        IS_Opportunity_Demand__c checkISO = [select Opportunity_ID__c from IS_Opportunity_Demand__c where id =:isoID];
        String opporID = checkISO.Opportunity_ID__c;
        List<IS_Opportunity_Demand__c> isoListForCheck = [select id, Func_SOD_Status__c,Abort_Date__c from IS_Opportunity_Demand__c where Opportunity_ID__c=:opporID];
        for(IS_Opportunity_Demand__c iso: isoListForCheck){
            if(iso.Abort_Date__c==null){
                return '存在未终止的SI需求表,不能复制';
            }
        }
        
        return ISO_DemandOperAndDemonsController.CopyFunc(isoID);
    }
    /**
    OCM-SI需求表用,自定义提交待审批
    */
    WebService static String ISO_Submit_Func(id isoID){
        List<IS_Opportunity_Demand__c> submintISOList = new List<IS_Opportunity_Demand__c>();
        submintISOList = [SELECT id,Data_Check_TF__c from IS_Opportunity_Demand__c WHERE id =:isoID];
        List<IS_Opportunity_Demand__c> isOppList = new List<IS_Opportunity_Demand__c>();
        for(IS_Opportunity_Demand__c iso: submintISOList){
            if(iso.Data_Check_TF__c){
                Savepoint sp = Database.setSavepoint();
                try {
                    Approval.ProcessSubmitRequest psr = new Approval.ProcessSubmitRequest();
                    psr.setObjectId(isoID);
                    Approval.ProcessResult submitResult = Approval.process(psr);
                    return  'Fin'; 
                }catch(exception e){
                    String ioError = e.getMessage();
                    Database.rollback(sp);
                    return  ''+ioError; 
                }
                }else{
                    return '请现在编辑页面,检查数据完整性,然后再执行提交';
                }
        }
        if(isOppList.size() > 0){
            update isOppList;
        }
        return 'Fin';
    }
    /**
    OCM-SI询价文件上传用,自定义提交待审批
    */
    WebService static String SI_FileUpdateSubmit(id subID){
            //List<Attachment> CheckFile = [select id from Attachment where ParentId=:subID];
            //if(CheckFile.size()==0){
            //    return '请上传附件后再提交';
            //}else{
            Savepoint sp = Database.setSavepoint();
            try {
                    Approval.ProcessSubmitRequest psr = new Approval.ProcessSubmitRequest();
                    psr.setObjectId(subID);
                    Approval.ProcessResult submitResult = Approval.process(psr);
                    return  'Fin'; 
                }catch(exception e){
                    String ioError = e.getMessage();
                    Database.rollback(sp);
                    return  ''+ioError; 
            }
        //}
    }
    /**
    OCM注残用,当注残更新时,判断数个日期是否变革,如若变革,则更新对应询价的映射时间(取最大值);
    */
    public static String updateOppoMuiltDate(id opporID){
        List<AggregateResult> ArResult = [select 
                                    Max(ContractReceivedDate__c ) al,
                                    Max(FirstApproveDate__c ) bl,
                                    Max(LastApproveDate__c  ) cl,
                                    Max(X30_Deposit_Day__c) dl,
                                    Max(Deposit_In_Full_Day__c) el,
                                    Max(SoLatestDeliveryDate__c) fl,
                                    Max(DeliveryDate__c ) gl,
                                    Max(DeliveryDate_backup__c) hl,
                                    Max(InstallDate__c) il,
                                    Max(Collection_Day_Invoice__c) jl,
                                    Max(Inspection_explanation_day__c) kl 
                                    from
                                    Statu_Achievements__c
                                    WHERE Opportunity__c =: opporID];
        Opportunity ops = [SELECT   Contract_Recieve_Date__c ,
                                    First_Review_Date__c ,
                                    LastApproveDate__c ,
                                    X30_Deposit_Day__c,
                                    Pay_All_Money__c,
                                    Last_Delivery_Date__c,
                                    DeliveryDate__c ,
                                    InstallDate__c,
                                    Inspection_explanation_day__c
                            From    Opportunity
                            WHERE   id =:opporID];
        for(AggregateResult ar : ArResult ){
            if(Date.valueOf(ar.get('al')) != ops.Contract_Recieve_Date__c){
                ops.Contract_Recieve_Date__c = Date.valueOf(ar.get('al'));
            }
            if(Date.valueOf(ar.get('bl')) != ops.First_Review_Date__c){
                ops.First_Review_Date__c = Date.valueOf(ar.get('bl'));
            }
            if(Date.valueOf(ar.get('cl')) != ops.LastApproveDate__c){
                ops.LastApproveDate__c = Date.valueOf(ar.get('cl'));
            }
            if(Date.valueOf(ar.get('dl')) != ops.X30_Deposit_Day__c){
                ops.X30_Deposit_Day__c = Date.valueOf(ar.get('dl'));
            }
            if(Date.valueOf(ar.get('el')) != ops.Pay_All_Money__c){
                 ops.Pay_All_Money__c = Date.valueOf(ar.get('el'));
            }
            if(Date.valueOf(ar.get('fl')) != ops.Last_Delivery_Date__c){
                ops.Last_Delivery_Date__c = Date.valueOf(ar.get('fl'));
            }
            if(Date.valueOf(ar.get('gl')) != ops.DeliveryDate__c){
                ops.DeliveryDate__c = Date.valueOf(ar.get('gl'));
            }
            if(Date.valueOf(ar.get('il')) != ops.InstallDate__c){
                ops.InstallDate__c = Date.valueOf(ar.get('il'));
                system.debug(ar.get('il')+'2333333333');
            }
            if(Date.valueOf(ar.get('kl')) != ops.Inspection_explanation_day__c){
                ops.Inspection_explanation_day__c = Date.valueOf(ar.get('kl'));
            }
        }
        update ops;
 
        ControllerUtil.refreshSIOpporStatus(opporID);
        return 'Fin';
    }
    /**
    OCM询价用,刷新OCM——SI的状态
    */
    public static string refreshSIOpporStatus(id opporID){
        Opportunity ops =  [SELECT  Last_Install_Confirm_Date__c,
                                    InstallDate__c,                     
                                    DeliveryDate__c,
                                    Last_Delivery_Date__c,
                                    Pay_All_Money__c ,
                                    X30_Deposit_Day__c ,
                                    LastApproveDate__c,
                                    First_Review_Date__c,
                                    Contract_Recieve_Date__c,
                                    SFDCLast_Process_Date__c,
                                    Input_Dealer_HP_date__c,
                                    Agency_Contract_Date_last_update__c,
                                    Assistant_Applied_Date__c,
                                    Closing_Bid_Date__c,
                                    Bid_Date__c,
                                    Autholization_Activated_Date__c,
                                    Authorized_Date__c,
                                    Last_Follow_Up_Date__c,
                                    Key_tipics_last_update_day__c,
                                    Status_List_SI__c
                            FROM    Opportunity
                            WHERE   id=:opporID];
        if(ops.Last_Install_Confirm_Date__c!=null){ops.Status_List_SI__c ='16 已结束';}
            else if(ops.InstallDate__c!=null){ops.Status_List_SI__c ='15 已安装';}
                else if(ops.DeliveryDate__c!=null){ops.Status_List_SI__c ='14 已发货';}
                    else if(ops.Last_Delivery_Date__c!=null){ops.Status_List_SI__c ='13 已分配,待发货';}
                        else if(ops.Pay_All_Money__c!=null){ops.Status_List_SI__c ='12 已订货,付全款';}
                            else if(ops.X30_Deposit_Day__c!=null){ops.Status_List_SI__c ='11 已订货,付订金';}
                                else if(ops.LastApproveDate__c!=null){ops.Status_List_SI__c ='10 库存已预留,未付款';}
                                    else if(ops.First_Review_Date__c!=null){ops.Status_List_SI__c ='9 已录入订单,未付款';}
                                        else if(ops.Contract_Recieve_Date__c!=null){ops.Status_List_SI__c ='9 已录入订单,未付款';}
                                            else if(ops.SFDCLast_Process_Date__c!=null){ops.Status_List_SI__c ='8 已签约';}
                                                else if(ops.Input_Dealer_HP_date__c!=null){ops.Status_List_SI__c ='7 用户已签约';}
                                                    else if(ops.Agency_Contract_Date_last_update__c!=null){ops.Status_List_SI__c ='6 用户未签约';}
                                                        else if(ops.Assistant_Applied_Date__c!=null){ops.Status_List_SI__c ='5 价格申请中';}
                                                            else if(ops.Closing_Bid_Date__c!=null){ops.Status_List_SI__c ='4 已中标';}
                                                                else if(ops.Bid_Date__c!=null ||ops.Autholization_Activated_Date__c!=null||ops.Authorized_Date__c!=null){ops.Status_List_SI__c ='3 已授权';}
                                                                    else if(ops.Last_Follow_Up_Date__c!=null){ops.Status_List_SI__c ='2 跟进中';}
                                                                        else if(ops.Key_tipics_last_update_day__c!=null){ops.Status_List_SI__c ='1 还没拜访';}
                                                                            else{ops.Status_List_SI__c = '0 还没跟进';}
        update ops;
        return 'Fin';
    }/**
    OCM询价文件上传用,实际上传文件后,刷新上传时间
    */
    public static String UpdateFileDateSet(List<String> SIopportunityIds){
        List<SI_Attachment__c> attFileList = [select id,Opportunity_ID__c,File_Upload_Date__c,Type__c from SI_Attachment__c where id in:SIopportunityIds];
        List<id> oppsId = new List<id>();
        Map<id,id> SODOwnerMap = new Map<id,id>();
        for(SI_Attachment__c siAc : attFileList){
            oppsId.add(siAc.Opportunity_ID__c);
        }
        List<IS_Opportunity_Demand__c> sodList = [select OwnerId,id,Opportunity_ID__c from IS_Opportunity_Demand__c where Opportunity_ID__c in:oppsId];
        for(IS_Opportunity_Demand__c sod: sodList){
            SODOwnerMap.put(sod.Opportunity_ID__c, sod.OwnerId);
        }
        for(SI_Attachment__c siAc : attFileList){
            siAc.File_Upload_Date__c = Date.today();
            siAc.SI_SOD_Owner__c = SODOwnerMap.get(siAc.Opportunity_ID__c);
        }
        savepoint sp = Database.setsavepoint();
        try{
            update attFileList;
            return 'Fin';
        }catch(exception o){
            Database.rollback(sp);
            return 'Database Error';
        }
       
    }
 
    /**
    OCM询价文件上传用,询价上传文件,根据文件种类,更新对应SI需求表状态
    */
    public static String UpdateSIFunctionStatus(List<String> SIopportunityIds){
    system.debug('Inside+++++++++++++++');
        List<SI_Attachment__c> attFileList = [select id,Opportunity_ID__c,Type__c from SI_Attachment__c where id in:SIopportunityIds];
        List<id> oppid = new List<id>();
        for(SI_Attachment__c si : attFileList){
            oppid.add(si.Opportunity_ID__c);
        }
        List<IS_Opportunity_Demand__c> isoFileList = new List<IS_Opportunity_Demand__c>();
        List<Opportunity> opslist = [select id,Project_decide_date__c,bid_Confrim_Date__c from Opportunity where id in:oppid];
        List<Opportunity> opslistUpdate = new List<Opportunity>();
        Map<Id,String> AttTypeToISODate = new Map<Id,String>();
        isoFileList = [ select  Id,CAD_Upload_Date__c,Program_Plan_Upload_Date__c,
                                Param_Upload_Date__c,Bid_Document_Upload_Date__c,
                                ConfirmBook_Upload_Date__c,Opportunity_ID__c 
                        from IS_Opportunity_Demand__c
                        where Opportunity_ID__c in:oppid
                        and  Func_SOD_Status__c !='已终止'];
        for(SI_Attachment__c att: attFileList){
            AttTypeToISODate.put(att.Opportunity_ID__c,att.Type__c);
        }
        for(IS_Opportunity_Demand__c iso : isoFileList){
            if(AttTypeToISODate.get(iso.Opportunity_ID__c) == 'CAD图纸'||
                AttTypeToISODate.get(iso.Opportunity_ID__c) == '手术室净化平面图(含设备定位)'||
                    AttTypeToISODate.get(iso.Opportunity_ID__c) == '目标术间吊塔定位图'||
                        AttTypeToISODate.get(iso.Opportunity_ID__c) == '目标术间净化立体图'||
                            AttTypeToISODate.get(iso.Opportunity_ID__c) == '示教点楼层平面图'||
                                AttTypeToISODate.get(iso.Opportunity_ID__c) == '楼层建筑平面图'||
                                    AttTypeToISODate.get(iso.Opportunity_ID__c) == '其他工程文件清单'){
                    if( iso.CAD_Upload_Date__c == null || AttTypeToISODate.get(iso.Opportunity_ID__c) == '手术室净化平面图(含设备定位)'){
                        iso.CAD_Upload_Date__c = Date.today();
 
                    }
                }else if(AttTypeToISODate.get(iso.Opportunity_ID__c) == '项目方案书'){
                    iso.Program_Plan_Upload_Date__c = Date.today();
                    for(Opportunity op : opslist){
                        op.Project_decide_date__c = Date.today();
                        opslistUpdate.add(op);
                        System.debug('项目方案书op'+opslistUpdate);
                    }
                    }else if(AttTypeToISODate.get(iso.Opportunity_ID__c) == '招标参数'){
                        iso.Param_Upload_Date__c = Date.today();
                        }else if(AttTypeToISODate.get(iso.Opportunity_ID__c) == '标书'  ){
                            iso.Bid_Document_Upload_Date__c = Date.today();
                            for(Opportunity op : opslist){
                                op.bid_Confrim_Date__c = Date.today();
                                opslistUpdate.add(op);
                            }
                            }else if(AttTypeToISODate.get(iso.Opportunity_ID__c) == 'OCAP/TUV认证'){
                                iso.ConfirmBook_Upload_Date__c = Date.today();
                            }
        }
        savepoint sp = Database.setsavepoint();
        try{
            update isoFileList;
            if(opslistUpdate.size()>0){
                 update opslistUpdate;
            }
           
            }catch(exception o){
                Database.rollback(sp);
                return 'Failed: '+o;
                system.debug('服务器侦错:'+o);
            }
        return 'Fin';
    }
    /**
    OCM报价用,当询价编码更新时,报价编码相应改变
    */
    public static String ResetQuoteNo(List<id> oppidList){
        List<Quote> UpdateQuoteList = new  List<Quote>();
        List<Opportunity> oppNoList = new  List<Opportunity>();
        Map<id,String> oppIdnoMap = new Map<id,String>();
        oppNoList = [SELECT id,Opportunity_No__c from Opportunity where id in:oppNoList];
        for(Opportunity ops : oppNoList){
            oppIdnoMap.put(ops.id, ops.Opportunity_No__c);
        }
        UpdateQuoteList = [SELECT id,Quote_No__c,Opportunityid from Quote WHERE Opportunityid in:oppidList order by Opportunityid];
        Integer index = 0;
        id flgId = null;
        for(Quote Qu : UpdateQuoteList){
            if(flgId == null){
                id ids = Qu.Opportunityid;
            }
            if(flgId == Qu.Opportunityid){
                index ++;
            }else{
                flgId = Qu.Opportunityid;
                index = 1;
            }
            Qu.Quote_No__c = oppIdnoMap.get(Qu.Opportunityid) + (index>9?(String.valueof(index)):('0'+String.valueof(index)));
        }
        return 'Fin';
    }
    /**
    OCM_SI更新对应报价状态,
    */
    WebService static String setQuote(string oppid){
        system.debug('2323^^^^^^^^^^^^');
        List<IS_Opportunity_Demand__c> updateList = [SELECT Quote_Locked_Date__c from IS_Opportunity_Demand__c WHERE Opportunity_ID__c =:oppid ];
        for(IS_Opportunity_Demand__c iso : updateList){
            iso.Quote_Locked_Date__c = Date.today();
        }
        update updateList;
        return 'Fin';
    }
    /**
    OCM询价拆单用,用来复制原有询价的报价
    */
    public static String CopyQuoteFromOppor(id oldOppor,String opporName , id newOppor,Opportunity ModelOppor){
        List<Quote> newQuoteList  = new List<Quote>();
        Map<id,id> newToold = new Map<id,id>();
        Map<id,QuoteLineItem> QuidWithQLitem = new Map<id,QuoteLineItem>();
        List<id> QuoteidOldList = new List<id>();
        List<Opportunity> opGetname = [SELECT Opportunity_No__c from Opportunity where id = :newOppor];
        if(opGetname.size()>0){
            String nameCode = opGetname[0].Opportunity_No__c;
            system.debug(nameCode+'nameCode');
        }
        String ele = '%'+ModelOppor.old_Oppo_No__c +'%';
        List<Quote> countQu = [SELECT id from Quote WHERE Quote_No__c like :ele];
        List<Quote> oldQuoteList = [SELECT  Id,
                                        Name,
                                        CurrencyIsoCode,
                                        CreatedDate,
                                        OpportunityId,
                                        Pricebook2Id,
                                        ContactId,
                                        QuoteNumber,
                                        IsSyncing,
                                        ShippingHandling,
                                        Tax,
                                        Status,
                                        ExpirationDate,
                                        Description,
                                        Subtotal,
                                        TotalPrice,
                                        LineItemCount,
                                        BillingName,
                                        ShippingName,
                                        QuoteToName,
                                        AdditionalName,
                                        Email,
                                        Phone,
                                        Fax,
                                        AccountId,
                                        Discount,
                                        GrandTotal,
                                        Agency1__c,
                                        Agency1_Profit__c,
                                        Agency1_Profit_Rate__c,
                                        Agency2__c,
                                        Agency2_Profit__c,
                                        Agency2_Profit_Rate__c,
                                        Agent1_Agent2_Price__c,
                                        OCM_Agent1_Price__c,
                                        OCM_Sales_Forecast__c,
                                        Estimation_List_Price__c,
                                        Stocking_Price__c,
                                        Dealer_Final_Price__c,
                                        Quote_No__c,
                                        Stock_Pre_Arrangement__c,
                                        Quote_Date__c,
                                        Unit_Price__c,
                                        Offer_Amount__c,
                                        TOTAL__c,
                                        Discount__c,
                                        Pricing__c,
                                        Preferential_Trading_Price__c,
                                        Contract__c,
                                        Quote_Expiration_Date__c,
                                        Quote_Comment__c,
                                        Discount_Amount_Calculate__c,
                                        Discount_Amount__c,
                                        Print_HP_Name__c,
                                        Quote_Adjust_Amount__c,
                                        Quote_Adjust_Calculate__c,
                                        Quote_No_Auto__c,
                                        Installation_location__c,
                                        QuoteName__c,
                                        PriceRefreshDate__c,
                                        Quote_Print_Date__c,
                                        OCM_Sales_Forecast_Without_Tax__c,
                                        Quote_Decision__c,
                                        Cancel_Decide__c,
                                        TotalPrice__c,
                                        Quote_Decision_Date__c,
                                        Quote_CreatedDate__c,
                                        IsSelected__c,
                                        HasType3Machine__c,
                                        OCM_Sales_Forecast_F__c,
                                        Dealer_Final_Price_F__c,
                                        Agent1_Agent2_Price_Page__c,
                                        Dealer_Final_Price_Page__c,
                                        OCM_Agent1_Price_Page__c,
                                        QuoteTotal_Page__c,
                                        Quote_Adjust_Amount_Page__c,
                                       
                                        OCM_Agent1_Price_F__c,
                                       
                                        Agent1_Agent2_Price_F__c,
                                        Agency2_Profit_F__c,
                                        Agency2_Profit_Rate_F__c,
                                        Quote_Adjust_Amount_F__c,
                                        Quote_Adjust_Calculate_F__c,
                                        TotalPrice_F__c,
                                        Discount_Amount_F__c,
                                        Discount_Amount_Calculate_F__c,
                                        BidAnnounce__c,
                                        Quote_No_last2__c
                                    FROM
                                        Quote
                                    WHERE 
                                        OpportunityId = :oldOppor
                                    order by 
                                        CreatedDate];
       
        Integer i = countQu.size();
        i=1;
        for(Quote Qu : oldQuoteList){
            //要按照原有顺序采番
            system.debug(Qu.Id+'===============4'); 
            String title = ModelOppor.old_Oppo_No__c;
            QuoteidOldList.add(Qu.Id);
            Qu.Id = null;
            Qu.OpportunityId = newOppor;
            Qu.Quote_No__c = title.substring(0,title.length() - 7)+ModelOppor.Opp_Number__c+ '-'+(i>9?(String.valueof(i)):('0'+i));
            newQuoteList.add(Qu);
            i++;
        }
        Savepoint sp = Database.setSavepoint();
        try{
            insert newQuoteList;
        } catch(Exception o){
            Database.rollback(sp);
            return 'Insert  Failed'+o;
        }
        for(Integer k = 0; k < newQuoteList.size(); k++){
                newToold.put(QuoteidOldList[k],newQuoteList[k].id);
        }
        List<QuoteLineItem> oldQuoteitemList = [Select Id,Asset_Model_No__c,SFDA_Status__c,Product_Sales_Possibility__c,
                                                Name__c,BSS_Category__c,Quote.Quote_Print_Date__c,Quoteid,
                                                Qty_Unit__c,Cost__c,UnitPrice__c,ListPrice__c,Quantity,TotalPrice__c,
                                                PricebookEntry.Product2.SFDA_Status__c, ProductCode__c, Product_Cost__c,PricebookEntry.Product2.VenderName__c, Product2.VenderName__c,Product_ListPrice__c, PricebookEntry.Product2.Sales_Possibility__c, PricebookEntry.Product2.Name,
                                                PricebookEntryId, PricebookEntry.Product2Id,UnitPrice_Page__c,PricebookEntry.Product2.Packing_list_manual__c,PricebookEntry.Product2.StorageStatus__c
                                                // 2022-03-21 SWAG-CBX5NN start
                                                ,If_Cancel_Guarantee__c
                                                ,multiYearWarranty__c
                                                ,CanNotCancelFlag__c 
                                                ,ProductEntend_gurantee_period_all__c
                                                ,warrantyType__c
                                                ,GuaranteePeriod__c
                                                ,GuranteeType__c 
                                                // 2022-03-21 SWAG-CBX5NN end
                                                From QuoteLineItem where Quoteid = :QuoteidOldList];
        for(QuoteLineItem qli : oldQuoteitemList){
            QuidWithQLitem.put(qli.Quoteid,qli);
        }
        system.debug(newToold+'newTooldnewTooldnewToold');
        system.debug(QuoteidOldList+'QuoteListQuoteListQuoteList');
        List<QuoteLineItem> copyQuoteItemList = new List<QuoteLineItem>();
         for(String Qu : QuoteidOldList){
            system.debug(Qu+'===============1');
            for(QuoteLineItem qlir : oldQuoteitemList){
                if(qlir.Quoteid == Qu){
                    system.debug(qlir+'===============2');
                    system.debug(QuidWithQLitem.get(Qu)+'===============3');
                    QuoteLineItem qli = qlir.clone();
                    qli.Quoteid = newToold.get(Qu);
                    qli.Id = null;
                    qli.UnitPrice = 0;
                    copyQuoteItemList.add(qli);
                }
               
            }
        }
        Savepoint spl = Database.setSavepoint();
        try{
            insert copyQuoteItemList;
        } catch(Exception o){
            Database.rollback(spl);
            return 'Insert  Failed copyQuoteItemList '+o;
        }
        return 'Fin';
    }
    /**
    OCM报价用,判断SI需求表的状态
    */
    WebService static String getStatusForISO(id opporID){
        //翻译已批准的数量
        Integer Abort = 0;
        Integer Applying = 0;
        Integer CommitCode = 0;
        List<IS_Opportunity_Demand__c> isoList = [  SELECT 
                                                        id,
                                                        name,
                                                        Abort_Date__c,
                                                        Approval_Date__c,
                                                        Func_SOD_Status__c
                                                    FROM
                                                        IS_Opportunity_Demand__c
                                                    where
                                                        Opportunity_ID__c = :opporID
                                                    AND
                                                        (
                                                        Approval_Date__c !=null
                                                        )]; 
        
        if(isoList.size()==0){
            return 'Abort';
 
        }else if(isoList.size()>0){
            return 'CommitCode';
        }
        return 'NoneIn';
        
    }
    /**
    OCM用,取消SI需求表
    */
    @AuraEnabled
    WebService static String setAbortSI(id isoID,String AbortReason){
        List<IS_Opportunity_Demand__c> updateList = new List<IS_Opportunity_Demand__c>();
        List<id> oppidList = new List<id>();
        List<Opportunity> Opplist = new List<Opportunity>();
        if(AbortReason==null||String.isBlank(AbortReason)){
            return '请输入终止SI需求原因';
        }else{
            updateList = [SELECT id,Abort_SI_Reason__c,Abort_Date__c,Opportunity_ID__c from IS_Opportunity_Demand__c where id = :isoID];
            for(IS_Opportunity_Demand__c iso : updateList){
                iso.Abort_SI_Reason__c = AbortReason;
                iso.Abort_Date__c = Date.today();
                oppidList.add(iso.Opportunity_ID__c);
            }
            Opplist = [SELECT Project_decide_date__c , Stock_Submit_Date__c , Stock_Confrim_Date__c from Opportunity WHERE id in:oppidList];
            for(Opportunity ops : Opplist){
                ops.Project_decide_date__c = null;
                ops.Stock_Submit_Date__c = null;
                ops.Stock_Confrim_Date__c = null;
            }
            Savepoint sp = Database.setSavepoint();
            try{
                update Opplist;
                update updateList;
                return 'Fin';
            }catch (Exception o){
                Database.rollback(sp);
                return 'DataBase is Crashed,Connect with the Developer PLEASE';
            }
        }
    }
    /**
    OCM询价用,取消SI询价,将相关联的SI需求表无效化
    */
    public static void updateSIodcList(List<String> OpporList){
        //询价失单,将询价对应的SI需求表无效化
        List<IS_Opportunity_Demand__c> ODCLIST = new List<IS_Opportunity_Demand__c>();
            ODCLIST = [SELECT id,Abort_Date__c from IS_Opportunity_Demand__c where Opportunity_ID__c in:OpporList and Abort_Date__c=null];
            for(IS_Opportunity_Demand__c Od : ODCLIST){
                Od.Abort_Date__c = Date.today();
            }
            update ODCLIST;
    }
    /*
    =======================================================================================================================
    ===================================================SI 询价部分util集合=================================================
    =======================================================================================================================
    */
    WebService static void addBatchIfLogForCnt(String typeStr, String operationType, String fileType, String hpId) {
        BatchIF_Log__c log = new BatchIF_Log__c(
            Type__c = typeStr,
            Is_Error__c = 0
        );
        log.Account__c = hpId;
        log.Log__c = operationType;
        log.Log2__c = fileType;
        
        insert log;
    }
    @AuraEnabled
    WebService static String setSObjectShare(String sobjectName, String rowCause, String parentId, List<String> userAccess, String ownerId) {
        try {
            List<SObject> sObjList = new List<SObject>();
            for (String ua : userAccess) {
                String userid = ua.split('_')[0];
                String access = ua.split('_')[1];
                SObject sObj = Schema.getGlobalDescribe().get(sobjectName).newSObject();
                if (String.isBlank(userid) == false && userid.substring(0, 15) != ownerId.substring(0, 15)) {
                    sObj.put('RowCause', rowCause);
                    sObj.put('ParentId', parentId);
                    sObj.put('UserOrGroupId', userid);
                    sObj.put('AccessLevel', access);
                    sObjList.add(sObj);
                }
            }
            if (sObjList.size() > 0) insert sObjList;
            return 'OK';
        } catch (Exception e) {
            return e.getMessage();
        }
    }
    // SWAG-BJ29Z4 营业助理共享询价字段审批加入共享 start
    WebService static String setOpportunityShare(String sobjectName, String parentId, List<String> userAccess, String ownerId) {
        System.debug(sobjectName+'======'+parentId+'======'+ownerId);
        try {
            List<SObject> sObjList = new List<SObject>();
            for (String ua : userAccess) {
                String userid = ua.split('_')[0];
                String access = ua.split('_')[1];
                SObject sObj = Schema.getGlobalDescribe().get(sobjectName).newSObject();
                if (String.isBlank(userid) == false && userid.substring(0, 15) != ownerId.substring(0, 15)) {
                    // sObj.put('RowCause', rowCause);
                    sObj.put('ParentId', parentId);
                    sObj.put('UserOrGroupId', userid);
                    sObj.put('AccessLevel', access);
                    sObjList.add(sObj);
                }
            }
            System.debug(sObjList+'======');
            if (sObjList.size() > 0) insert sObjList;
            return 'OK';
        } catch (Exception e) {
            return e.getMessage();
        }
    }
    // SWAG-BJ29Z4 营业助理共享询价字段审批加入共享 end
    
    public static void insertBatchIfLog(BatchIF_Log__c bl) {
        insert bl;
    }
    
    public static List<BatchIF_Log__c> getBatchIfLogForRequest(String typeStr, String hpId, Datetime dt) {
        return [select Id from BatchIF_Log__c where Type__c = :typeStr and Account__c = :hpId
                 and RequestStatus__c != 'Finish' and RequestStatus__c != 'Error' and CreatedDate > :dt];
    }
    public static Integer getOlympusWorkDayCount(Date fromDate, Date toDate) {
        AggregateResult[] calAggResult = [Select Count(Id) cnt From OlympusCalendar__c Where Date__c >= :fromDate And Date__c <= :toDate And IsWorkDay__c = 1];
        Integer workDayCount = (Integer) calAggResult[0].get('cnt');
        return workDayCount;
    }
    
    public static Pricebook2 getStandardPricebook() {
        if (system.Test.isRunningTest()) { 
            return new Pricebook2(Id = System.Test.getStandardPricebookId(), Name = 'Standard Pricebook');
        } else {
            List<Pricebook2> pbs = [Select Id, Name From Pricebook2 where IsStandard = true AND isActive = true];
            if (pbs.size() > 0) {
                return pbs[0];
            } else {
                return null;
            }
        }
    }
    public static Set<Id> getAllSubRoleIds(Id userRoleId, String additionalRoleName) {
        // currentRoleId と additionalRoleName まず queryする
        Map<Id, UserRole> parentRoleMap = new Map<Id, UserRole>();
        Boolean isAdditional = false;
        if (String.isBlank(additionalRoleName) == true) {
            parentRoleMap = new MAP<Id, UserRole>([select Id from UserRole where Id = :userRoleId]);
        } else {
            isAdditional = true;
            List<String> addtionalRoleNameList = additionalRoleName.split(',');
            parentRoleMap = new MAP<Id, UserRole>([select Id from UserRole where Id = :userRoleId or DeveloperName in :addtionalRoleNameList]);
        }
        //MAP<Id, UserRole> parentRoleMap = new MAP<Id, UserRole>([select Id from UserRole where Id = :userRoleId or DeveloperName = :additionalRoleName]);
        Map<Id, Set<Id>> allRoleMap = new Map<Id, Set<Id>>();
        for (UserRole role : [select Id, ParentRoleId from UserRole]) {
            Set<Id> roleIds = allRoleMap.get(role.ParentRoleId);
            if (roleIds == null) {
                roleIds = new Set<Id>();
            }
            roleIds.add(role.Id);
            allRoleMap.put(role.ParentRoleId, roleIds);
        }
        return getSubRoleRecursive(parentRoleMap.keySet(), allRoleMap, isAdditional, userRoleId);
    }
 
    private static Set<Id> getSubRoleRecursive(Set<Id> roleIds, Map<Id, Set<Id>> allRoleMap, Boolean isAdditional, Id userRoleId) {
        Set<Id> currentRoleIds = new Set<Id>();
 
        // get all of the roles underneath the passed roles
        for (Id parentRoleId : roleIds) {
            if (allRoleMap.get(parentRoleId) != null) {
                currentRoleIds.addAll(allRoleMap.get(parentRoleId));
            }
        }
 
        // go fetch some more rolls!
        if(currentRoleIds.size() > 0) {
            currentRoleIds.addAll(getSubRoleRecursive(currentRoleIds, allRoleMap, isAdditional, userRoleId));
        }
        
        // 兼職の場合、兼職Role自身のIdも入れる
        if (isAdditional) {
            roleIds.remove(userRoleId);
            currentRoleIds.addAll(roleIds);
        }
        return currentRoleIds;
    }
 
    public static String getOppSearchSQOL(String visitorPlaceId, String nameCondition) {
        Account a = null;
        a = [select Id, Hospital__c, Agent_Ref__c, Parent.Parent.RecordType.DeveloperName, Parent.RecordType.DeveloperName, RecordType.DeveloperName from Account where Id=:visitorPlaceId];
        
//        String nameCondition = '%' + String.escapeSingleQuotes(query.replaceAll('%', '')) + '%';
        system.debug('cond=' + nameCondition);
        
        // 検索
        String queryString = '';
        String temptoday = Date.today().format().replace('/', '-');
        //String tempLastDate = Date.today().addDays(365).format().replace('/', '-');
        String tempLastDate = Date.today().addDays(-365).format().replace('/', '-');
        // 病院
        if (a.Parent.Parent.RecordType.DeveloperName == 'HP') {
            // queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c, Close_Forecasted_Date__c, Competitor__c, Wholesale_Price__c from Opportunity where' + nameCondition + ' Account.Hospital__c=\'' + a.Hospital__c + '\' and StageName IN (\'引合\',\'注残\',\'出荷\') and RecordTypeId = \'01210000000QekK\' order by Name, Opportunity_No__c, Department_Name__c limit 31';
            // 20200616 CHAN-BQM8LU vivek start
            // 20191126 SWAG-BJA6JK LHJ Start
            // queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c, Close_Forecasted_Date__c, Competitor__c, Wholesale_Price__c from Opportunity where' + nameCondition + ' Account.Hospital__c=\'' + a.Hospital__c + '\' and StageName IN (\'引合\',\'注残\',\'出荷\') and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c limit 31';
            // queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c, Close_Forecasted_Date__c, Competitor__c, Wholesale_Price__c from Opportunity where' + nameCondition + ' Account.Hospital__c=\'' + a.Hospital__c + '\' and StageName IN (\'引合\',\'注残\') and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c limit 31';
            //20210824 zh SWAG-C5S46P start
            //queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c,Field1__c,CountNoInstall__c, Close_Forecasted_Date__c, Competitor__c, Wholesale_Price__c from Opportunity where' + nameCondition + ' Account.Hospital__c=\'' + a.Hospital__c + '\' and ( StageName IN (\'引合\',\'注残\') or ( StageName = \'出荷\' and CountNoInstall__c > 0 )) and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c limit 31';
 
            //queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c,Field1__c,CountNoInstall__c, Close_Forecasted_Date__c, Competitor__c, Wholesale_Price__c from Opportunity where' + nameCondition + ' Account.Hospital__c=\'' + a.Hospital__c + '\' and ( StageName IN (\'引合\',\'注残\') or ( StageName = \'出荷\' and DeliveryDate__c > '+temptoday+' and DeliveryDate__c <= '+tempLastDate+')) and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c limit 31';
            //20210824 zh SWAG-C5S46P end
            // 20191126 SWAG-BJA6JK LHJ End
            //20210826 mzy SWAG-C5S46P start
            //改为用 发货完毕日 判断 且 将 2012年创建的且询价状态是发货/完毕的数据排除
            //queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c,Field1__c,CountNoInstall__c, Close_Forecasted_Date__c, Competitor__c, Wholesale_Price__c from Opportunity where' + nameCondition + ' Account.Hospital__c=\'' + a.Hospital__c + '\' and ( StageName IN (\'引合\',\'注残\') or ( StageName = \'出荷\' and Shipping_Finished_Day__c > '+temptoday+' and Shipping_Finished_Day__c <= '+tempLastDate+' and CALENDAR_YEAR(Created_Day__c) != 2012 )) and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c limit 31';
            queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c,Field1__c,CountNoInstall__c, Close_Forecasted_Date__c, Competitor__c, Wholesale_Price__c from Opportunity where' + nameCondition + ' Account.Hospital__c=\'' + a.Hospital__c + '\' and ( StageName IN (\'引合\',\'注残\') or ( StageName = \'出荷\' and Shipping_Finished_Day__c > '+tempLastDate+' and Shipping_Finished_Day__c <= '+temptoday+' and CALENDAR_YEAR(Created_Day__c) != 2012 )) and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c limit 31';
            //20210826 mzy SWAG-C5S46P end
            // 20200616 CHAN-BQM8LU vivek end
        }
        // 販売店
        else if (a.RecordType.DeveloperName == 'Agency') {
            // queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c, Close_Forecasted_Date__c, Competitor__c, Wholesale_Price__c from Opportunity where' + nameCondition + ' (Agency1__c=\'' + a.Id + '\' or Agency2__c=\'' + a.Id + '\') and StageName IN (\'引合\',\'注残\',\'出荷\') and RecordTypeId = \'01210000000QekK\' order by Name, Opportunity_No__c, Department_Name__c limit 31';
            // 20200616 CHAN-BQM8LU vivek start
            // 20191126 SWAG-BJA6JK LHJ Start
            // queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c, Close_Forecasted_Date__c, Competitor__c, Wholesale_Price__c from Opportunity where' + nameCondition + ' (Agency1__c=\'' + a.Id + '\' or Agency2__c=\'' + a.Id + '\') and StageName IN (\'引合\',\'注残\',\'出荷\') and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c limit 31';
            //queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c, Close_Forecasted_Date__c, Competitor__c, Wholesale_Price__c from Opportunity where' + nameCondition + ' (Agency1__c=\'' + a.Id + '\' or Agency2__c=\'' + a.Id + '\') and StageName IN (\'引合\',\'注残\') and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c limit 31';
            //20210824 zh SWAG-C5S46P start
            //queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c,Field1__c,CountNoInstall__c, Close_Forecasted_Date__c, Competitor__c, Wholesale_Price__c from Opportunity where' + nameCondition + ' Account.Hospital__c=\'' + a.Hospital__c + '\' and ( StageName IN (\'引合\',\'注残\') or ( StageName = \'出荷\' and CountNoInstall__c > 0 )) and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c limit 31';
 
            //queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c,Field1__c,CountNoInstall__c, Close_Forecasted_Date__c, Competitor__c, Wholesale_Price__c from Opportunity where' + nameCondition + ' Account.Hospital__c=\'' + a.Hospital__c + '\' and ( StageName IN (\'引合\',\'注残\') or ( StageName = \'出荷\' and DeliveryDate__c > '+temptoday+' and DeliveryDate__c <= '+tempLastDate+')) and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c limit 31';
            //20210824 zh SWAG-C5S46P end
            //20210826 mzy SWAG-C5S46P start
            //改为用 发货完毕日 判断 且 将 2012年创建的且询价状态是发货/完毕的数据排除
            //queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c,Field1__c,CountNoInstall__c, Close_Forecasted_Date__c, Competitor__c, Wholesale_Price__c from Opportunity where' + nameCondition + ' Account.Hospital__c=\'' + a.Hospital__c + '\' and ( StageName IN (\'引合\',\'注残\') or ( StageName = \'出荷\' and Shipping_Finished_Day__c > '+temptoday+' and Shipping_Finished_Day__c <= '+tempLastDate+' and CALENDAR_YEAR(Created_Day__c) != 2012 )) and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c limit 31';
            queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c,Field1__c,CountNoInstall__c, Close_Forecasted_Date__c, Competitor__c, Wholesale_Price__c from Opportunity where' + nameCondition + ' Account.Hospital__c=\'' + a.Hospital__c + '\' and ( StageName IN (\'引合\',\'注残\') or ( StageName = \'出荷\' and Shipping_Finished_Day__c > '+tempLastDate+' and Shipping_Finished_Day__c <= '+temptoday+' and CALENDAR_YEAR(Created_Day__c) != 2012 )) and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c limit 31';
            //20210826 mzy SWAG-C5S46P end
            // 20191126 SWAG-BJA6JK LHJ End
            // 20200616 CHAN-BQM8LU vivek end
        }
 
        return queryString;
    }
    // 用来解决经销商活动的担当
    public static List<Agency_Opportunity__c> DatabaseQuery(String soql){
        return DataBase.query(soql);
    }
 
    public class myException extends Exception {}
    @AuraEnabled
    WebService static String qureySoql(String soql) {
        List<SObject> rtnList = Database.query(soql);
        String rtnJSON = JSON.serialize(Database.query(soql), true);
        System.debug('rtnJSON:' + rtnJSON);
        return rtnJSON;
    }
 
    // GIR 项目需求用,找不到Add_report的测试程序 20191219 by vivek start
    WebService static Account getAccountForJs(String id){
        return [select Id, Name, Province_formula__c, Hospital__r.Salesdepartment_HP__c,Department_Class__r.Name,Department_Class__r.OwnerId, Department_Class__r.Owner.Name, Department_Class__r.Id, OwnerId, Owner.Name,  
                Hospital__r.Name, Hospital__r.Id, Hospital__r.OCM_Category__c,Hospital__r.OCM_Management_Province__r.GI_assistant__c,Hospital__r.OCM_Management_Province__r.GI_assistant__r.Name
                from Account where Id = :id];
    }
    // GIR 项目需求用,找不到Add_report的测试程序 20191219 by vivek end
 
    // 任务和日报 2020-05-23 update by vivek start
    public static Event__c getNoIdEventC(Event__c dlyevt){
        dlyevt.Id = null;
        return dlyevt;
    }
    public static Event getNoIdEvent(Event dlyec){
        dlyec.Id = null;
        return dlyec;
 
    } 
    public static Event getEventList(Id eventcid){
        Event dlyec = [select id, ActivityDate, OwnerId, Subject, task_id__c,whatid__c, EventC_ID__c, NextEventC_ID__c, AppCdId__c, SyncCreatedDate__c, 
                                  StartDateTime, DurationInMinutes, Main_Visit_Location__c, Activity_Type2__c, IsScheduled__c, BeforeActivityDate__c,
                                  Visitor1__c, Visitor2__c, Visitor3__c, Visitor4__c, Visitor5__c, Visitor1_ID__c, Visitor2_ID__c, Visitor3_ID__c, Visitor4_ID__c, Visitor5_ID__c,
                                  Purpose_Type__c, Location, Related_Opportunity1__c, Related_Service1__c, Related_Opportunity1_ID__c, Related_Service1_ID__c, WS_flg__c,
                                  Related_Opportunity2__c, Related_Opportunity3__c, Related_Opportunity4__c, Related_Opportunity5__c,OPDPlan_Flag__c,
                                  Related_Opportunity2_ID__c, Related_Opportunity3_ID__c, Related_Opportunity4_ID__c, Related_Opportunity5_ID__c,
                                  Activity_Purpose__c, Activity_PurposeFSE__c, Activity_PurposeEscFSE__c, Purpose_TypeFSE__c, Purpose_TypeEscFSE__c,Opd_Plan__c  
                                  from Event where EventC_ID__c = :eventcid];
                                  return dlyec;
    }
 
    public static List<Event> getEventsList(Set<String> eventcid){
        List<Event> dlyec = [select id, ActivityDate, OwnerId, Subject, whatid__c,task_id__c, EventC_ID__c, NextEventC_ID__c, AppCdId__c, SyncCreatedDate__c, 
                                  StartDateTime, DurationInMinutes, Main_Visit_Location__c, Activity_Type2__c, IsScheduled__c, BeforeActivityDate__c,
                                  Visitor1__c, Visitor2__c, Visitor3__c, Visitor4__c, Visitor5__c, Visitor1_ID__c, Visitor2_ID__c, Visitor3_ID__c, Visitor4_ID__c, Visitor5_ID__c,
                                  Purpose_Type__c, Location, Related_Opportunity1__c, Related_Service1__c, Related_Opportunity1_ID__c, Related_Service1_ID__c, WS_flg__c,
                                  Related_Opportunity2__c, Related_Opportunity3__c, Related_Opportunity4__c, Related_Opportunity5__c,OPDPlan_Flag__c,
                                  Related_Opportunity2_ID__c, Related_Opportunity3_ID__c, Related_Opportunity4_ID__c, Related_Opportunity5_ID__c,
                                  Activity_Purpose__c, Activity_PurposeFSE__c, Activity_PurposeEscFSE__c, Purpose_TypeFSE__c, Purpose_TypeEscFSE__c
                                  from Event where Id = :eventcid];
                                  return dlyec;
    }
    // 任务和日报 2020-05-23 update by vivek end
 
    //失但报告申请保存    2021-09-13 upsert  zxk  start
    public static void lostOrder(Lost_Report__c lostData) {
        upsert lostData;
    }
 
    // FY23修改 WLIG-CFV4AV 重点产品维护(新)start
    public static String getKeyByProduct(String keyword) {
        if (String.isBlank(keyword)) {
            return null;
        }
        String KeyProductMapping = System.Label.Key_Product_Mapping;
        Map<String, Object> mapping = (Map<String, Object>) JSON.deserializeUntyped(KeyProductMapping);
        System.debug('==Mapping is: ' + mapping);
        
        return mapping.get(keyword) != null ? String.valueOf(mapping.get(keyword)) : null;
    }
    // FY23修改 WLIG-CFV4AV 重点产品维护(新)end
 
    //20221021  lt SWAG-CHL5XA【FY23询价改善】-统计主机台数 start
    public static void UpdateBiddingFlag(List<String> oppId){
        List<Tender_Opportunity_Link__c> links = [SELECT Id, Tender_information__c, Tender_information__r.IsReactionOpp__c, Opportunity__c 
                                                  FROM Tender_Opportunity_Link__c 
                                                  WHERE Opportunity__c in :oppId ];
 
        Map<String,Tender_information__c> tenderMap = new Map<String,Tender_information__c>();
 
        for (Tender_Opportunity_Link__c link : links){
        
            Tender_information__c temptender = new Tender_information__c();
            temptender.Id = link.Tender_information__c;
            temptender.IsReactionOpp__c = true;
            tenderMap.put(temptender.id ,temptender); 
        
        }
 
        if(tenderMap.size()>0){
            update tenderMap.values();
        }
                    
    }
    //20221021  lt SWAG-CHL5XA【FY23询价改善】-统计主机台数 end
   
}