buli
2023-07-14 36d15f189de2e83ce2576715dac30c3c260388dd
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
public without sharing class LexConsumableController {
    /*****************検索用******************/
    public static Consumable_order__c coc { get; set; } // FIMXE Consumable_order__c のインスタンス、sql多すぎ
    public static String category1 { get; set; }
    public static String category5 { get; set; }
    public static String category4 { get; set; }
    public static String category3 { get; set; }
    public static String category_Goods { get; set; }
    public static Boolean specialCampaign { get; set; }
    public static Boolean cansee { get; set; }
    //经销商合同名称
    public static String contractName { get; set; }
    //经销商合同ID
    public static String contractId { get; set; }
    //经销商定价查看权限
    public static Boolean dealerPricesee { get; set; }
    /*****************画面初始化用********************************/
    /******20160313_add**************/
    //public String idCheck {get;set;}
    public static Boolean editAble { get; set; }
    public static Boolean edoffersPrice { get; set; }
    public static String statusEdit { get; set; }
    public static Boolean returnOrder { get; set; }
    public static String searchDone { get; set; }
    //暂用20160323
    public static Decimal disCount = 0;
    //总价格计算结果
    public static Decimal sumPrice { get; set; }
    //自定义特价金额
    public static Decimal bargainPrice { get; set; }
    //产品上下限
    public static String[] proLimitAndDate = new List<String>{};
    /*****************画面表示Bean******************/
    private static List<ConsumableorderdetailsInfo> consumableorderdetailsRecords = new List<ConsumableorderdetailsInfo>();
    public static List<ConsumableorderdetailsInfo> consumableorderdetailsRecordsview { get; set; }
    public static Integer ConsumableorderdetailsCount {
        get {
            return consumableorderdetailsRecords == null ? 0 : consumableorderdetailsRecords.size();
        }
    }
    public static Integer ConsumableorderdetailsviewCount {
        get {
            return consumableorderdetailsRecordsview == null ? 0 : consumableorderdetailsRecordsview.size();
        }
    }
    public static List<String> lower = new List<String>();
    //附件
    public static List<ConsumableorderdetailsInfo> attachmentRecoeds { get; set; }
    public static List<String> DealerProductId { get; set; }
    public static Boolean editDelCommitBtnDisabled { get; private set; }
    public static Boolean saveBtnDisabled { get; private set; }
    public static Boolean sorderBtnDisabled { get; private set; }
    public static String decisionCode { get; set; }
    // 保存后动作: 1.检索 2.排序
    public static String baseUrl { get; private set; }
    public static String sortKey { get; set; }
    public static String preSortKey { get; private set; }
    public static Boolean sortOrderAsc { get; private set; }
    public static String[] sortOrder { get; private set; }
    private static List<String> contactDealer = new List<String>();
    private static String[] columus = new List<String>{
        'Consumable_Product__r.Name',
        'Consumable_Product__r.Asset_Model_No__c',
        'Consumable_Product__r.Intra_Trade_List_RMB__c',
        '',
        '',
        'Consumable_Product__r.Category3__c',
        'Consumable_Product__r.Category4__c',
        'Consumable_Product__r.Category5__c'
    };
    private static String[] columus_no = new List<String>{
        'Product2__c.Name',
        'Product2__c.Asset_Model_No__c',
        'Product2__c.Intra_Trade_List_RMB__c',
        '',
        '',
        'Category3__c',
        'Category4__c',
        'Category5__c'
    };
    // 已选择产品明细
    private static List<Attachment> attachmentinfo = new List<Attachment>();
    /*****************ソート時再検索条件(画面からの入力条件を無視するため)******************/
    private static String cate1ForSort = null;
    private static String accountid = null;
    private static String accountName = null;
    // 产品 ID
    public static String ESetId { get; set; }
    private static String userId = '';
    //private String[] ProidListAll = new String[]{};
    public static List<SelectOption> categoryOptionList { get; set; }
    public static List<SelectOption> category4OptionList { get; set; }
    public static List<SelectOption> category5OptionList { get; set; }
    public static List<CusOption> category3Option { get; set; }
    public static List<CusOption> category4Option { get; set; }
    public static List<CusOption> category5Option { get; set; }
    private static Map<Id, Dealer_Product__c> DealerProductMap = new Map<Id, Dealer_Product__c>();
    public static List<String> orderzaikuId = new List<String>();
    //分页功能
    public static Integer size { get; set; }
    public static Integer pageLimit { get; set; }
    public static Integer noOfRecords { get; set; }
    public static ApexPages.StandardSetController con { get; set; }
    public static String soql { get; set; }
    // 登录者工作地
    private static String userWorkLocation;
    public static String agencyProType { get; set; }
    public static String agencyProType1 { get; set; } //lt 20230526 安徽两票制 add
    private static Boolean OSHFLG; //lt 20230517 安徽两票制 add
    public static String methodType { get; set; }
    public static String hospitalName { get; set; }
    public static String hospitalId { get; set; }
    public static String tempidHp { get; set; }
    public static String tempidPp { get; set; }
    private static List<String> hpids = new List<String>();
    private static Boolean isfirst = false;
    //报错和警告信息
    public static List<String> errorMsgList = new List<String>();
    public static List<String> warningMsgList = new List<String>();
    //构造方法
    public LexConsumableController() {
        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
        consumableorderdetailsRecords = new List<ConsumableorderdetailsInfo>();
        DealerProductId = new List<String>();
        attachmentRecoeds = new List<ConsumableorderdetailsInfo>();
        consumableorderdetailsRecordsview = new List<ConsumableorderdetailsInfo>();
        editAble = false;
        edoffersPrice = false;
        returnOrder = false;
        categoryOptionList = new List<SelectOption>();
        category4OptionList = new List<SelectOption>();
        category5OptionList = new List<SelectOption>();
        size = Integer.valueOf(System.Label.orderdetLimitsize);
        pageLimit = Integer.valueOf(System.Label.orderdetPageLimitsize);
    }
 
    private static void initStandardController() {
        con = new ApexPages.StandardSetController(Database.getQueryLocator(soql));
        con.setPageSize(size);
        noOfRecords = con.getResultSize();
    }
 
    public static List<Product2__c> product2s() {
        return (List<Product2__c>) con.getRecords();
    }
 
    private static List<ConsumableorderdetailsInfo> getPageInfo() {
        List<ConsumableorderdetailsInfo> reSet = new List<ConsumableorderdetailsInfo>();
        Map<String, String> selectedIdMap = new Map<String, String>();
 
        for (ConsumableorderdetailsInfo ass : consumableorderdetailsRecordsview) {
            if (ass.check == true) {
                selectedIdMap.put(ass.Prod.id, ass.Prod.id);
                reSet.add(ass);
            }
        }
 
        consumableorderdetailsRecordsview = new List<ConsumableorderdetailsInfo>();
        if (editAble) {
            consumableorderdetailsRecordsview = reSet;
        }
        Integer pagestartNo = (con.getPageNumber() * size) - size;
        Integer pageendNo = (con.getPageNumber() * size) > noOfRecords ? noOfRecords : (con.getPageNumber() * size - 1);
        Integer addNo = 0;
        for (Integer i = pagestartNo; i < consumableorderdetailsRecords.size(); i++) {
            Consumable_Orderdetails__c orderdetails1 = new Consumable_Orderdetails__c();
            if (selectedIdMap.containsKey(consumableorderdetailsRecords[i].Prod.Id)) {
                addNo++;
                //continue;
            }
            // else if (consumableorderdetailsRecordsview.size() >= pageLimit + size) {
            //     break;
            // }
            else {
                if (consumableorderdetailsRecords[i].check == false) {
                    consumableorderdetailsRecords[i].esd = orderdetails1;
                }
                //consumableorderdetailsRecords[i].esd.Dealer_Custom_Price__c = consumableorderdetailsRecords[i].Prod.Intra_Trade_List_RMB__c * disCount / 100;
                consumableorderdetailsRecordsview.add(consumableorderdetailsRecords[i]);
                addNo++;
            }
            // if (addNo >= size)
            //     break;
        }
        return consumableorderdetailsRecordsview;
    }
 
    @AuraEnabled
    public static Results init(String type, String esetId, String keywordStr) {
        Results results = new Results();
        results.isNoteStay = LexUtility.getIsNoteStay();
        errorMsgList = new List<String>();
        warningMsgList = new List<String>();
        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
        consumableorderdetailsRecords = new List<ConsumableorderdetailsInfo>();
        DealerProductId = new List<String>();
        attachmentRecoeds = new List<ConsumableorderdetailsInfo>();
        consumableorderdetailsRecordsview = new List<ConsumableorderdetailsInfo>();
        editAble = false;
        edoffersPrice = false;
        returnOrder = false;
        categoryOptionList = new List<SelectOption>();
        category4OptionList = new List<SelectOption>();
        category5OptionList = new List<SelectOption>();
        size = Integer.valueOf(System.Label.orderdetLimitsize);
        pageLimit = Integer.valueOf(System.Label.orderdetPageLimitsize);
        ESetId = esetId;
        methodType = type;
        if (String.isBlank(methodType) && String.isNotBlank(ESetId)) {
<<<<<<< HEAD
            List<Consumable_order__c> oclist = [
                SELECT orderPattern__c
                FROM Consumable_order__c
                WHERE id = :ESetid
            ];
=======
            List<Consumable_order__c> oclist = [SELECT orderPattern__c FROM Consumable_order__c WHERE id = :ESetid];
>>>>>>> LEXCommunityLiJun
            methodType = oclist.get(0).orderPattern__c;
        }
        statusEdit = keywordStr;
        System.debug('Param:' + ESetId + '---' + methodType + '---' + statusEdit);
        try {
            sortKey = '1';
            preSortKey = '1';
            sortOrderAsc = false;
            sortOrder = new String[8];
            sortOrder = new List<String>{ ' ', ' ', ' ', ' ', '↓', '', '', '' };
            cate1ForSort = '';
            decisionCode = '';
            sumPrice = 0;
            specialCampaign = false;
            if (ESetId != null && ESetId != '' && statusEdit == '' && statusEdit == null) {
                editAble = false;
            } else if ((ESetId == null || ESetId == '') && (statusEdit == '' || statusEdit == null)) {
                editAble = true;
            } else if (ESetId != null && ESetId != '' && statusEdit != '' && statusEdit != null) {
                editAble = true;
            }
            userId = UserInfo.getUserId();
            List<user> Useracc = new List<user>();
            //lt 20230517 安徽两票制 add ,OSHFLG__c
<<<<<<< HEAD
            Useracc = [
                SELECT accountid, Work_Location__c, UserPro_Type__c, OSHFLG__c
                FROM user
                WHERE id = :userId
            ];
=======
            Useracc = [SELECT accountid, Work_Location__c, UserPro_Type__c, OSHFLG__c FROM user WHERE id = :userId];
>>>>>>> LEXCommunityLiJun
            accountid = Useracc[0].accountid;
            userWorkLocation = Useracc[0].Work_Location__c;
            agencyProType = Useracc[0].UserPro_Type__c;
            agencyProType1 = Useracc[0].UserPro_Type__c; //lt 20230526 安徽两票制 add
            //lt 20230526 安徽两票制 start
            OSHFLG = Useracc[0].OSHFLG__c; //lt 20230517 安徽两票制 add
            if (OSHFLG) {
                agencyProType1 = 'OSH';
            } else if (String.isBlank(Useracc[0].UserPro_Type__c)) {
                agencyProType1 = 'ET';
            }
            //lt 20230526 安徽两票制 end
            if (String.isBlank(Useracc[0].UserPro_Type__c)) {
                agencyProType = 'ET';
            }
            //错误信息提示
            if (String.isNotBlank(methodType) && methodType.equals('hospitalorder') && agencyProType == 'ET') {
                // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '您没有订货医院特价产品的权限!'));
                errorMsgList.add('您没有订货医院特价产品的权限!');
            }
            contactDealer = new List<String>();
            Date dateToday = Date.today();
            //查该经销商下所有有效合同
            List<Account> contractList = [
                SELECT Id, Name, RecordType.DeveloperName
                FROM Account
                WHERE
                    RecordType.DeveloperName = 'AgencyContract'
                    AND Contract_Decide_Start_Date__c <= :dateToday
                    AND Contract_Decide_End_Date__c >= :dateToday
                    AND Contact_Type__c LIKE :agencyProType1 //lt 20230517 安徽两票制 add 1
                    AND Agent_Ref__c = :accountid
                    AND OSH_Dealer__c = :OSHFLG //lt 20230517 安徽两票制 add
            ];
            for (Account contract : contractList) {
                contactDealer.add(contract.Id);
            }
            DealerProductMap = new Map<Id, Dealer_Product__c>();
            DealerProductId = getDealerProductId();
            Account accountInfo = [
                SELECT Name, Dealer_discount__c, Product_Limit_Date__c, Product_Limit_DateENG__c
                FROM account
                WHERE id = :accountid
            ];
            accountName = accountInfo.Name;
            String product_Limit;
            if (agencyProType == 'ET') {
                product_Limit = accountInfo.Product_Limit_Date__c;
            } else {
                product_Limit = accountInfo.Product_Limit_DateENG__c;
            }
            if (product_Limit != null && product_Limit != '') {
                proLimitAndDate = product_Limit.split(',');
            }
            saveBtnDisabled = false;
            sorderBtnDisabled = false;
            coc = new Consumable_order__c();
            consumableorderdetailsRecords = new List<ConsumableorderdetailsInfo>();
            if (String.isBlank(agencyProType)) {
                //return ;
            }
            List<Product2__c> Product2Selected = new List<Product2__c>();
            Map<String, ConsumableorderdetailsInfo> MidMap = new Map<String, ConsumableorderdetailsInfo>();
            //经销商在库数据
            List<Consumable_order_details2__c> countDel = [
                SELECT
                    Id,
                    Bar_Code__c,
                    Name,
                    Inventory_date__c,
                    Consumable_Product__c,
                    Consumable_Product__r.Asset_Model_No__c,
                    Recordtypeid,
                    Box_Piece__c,
                    hospitalSpecialOffer__c,
                    promotionorder__c
                FROM Consumable_order_details2__c
                WHERE
                    Dealer_Arrive__c = TRUE
                    AND Dealer_Shipment__c = FALSE
                    AND Dealer_Saled__c = FALSE
                    AND Dealer_Returned__c = FALSE
                    AND Lose_Flag__c = FALSE
                    AND Cancellation_Flag__c = FALSE
                    AND Bar_Code__c != NULL
                    AND Isoverdue__c = 1
                    AND Arrive_Owner_Work_Location__c = :userWorkLocation
                    AND Dealer_Info_text__c = :accountName
            ];
            if (ESetId == null || ESetId == '') {
                //获取经销商默认的一个合同
                List<Account> contract = [
                    SELECT id, Name, State_Master__c, State_Master__r.Name
                    FROM Account
                    WHERE
                        ParentId = :accountid
                        AND Contact_Type__c LIKE :agencyProType1 //lt 20230517 安徽两票制 add 1
                        AND Contract_Decide_Start_Date__c <= :Date.Today()
                        AND Contract_Decide_End_Date__c >= :Date.Today()
                        AND OSH_Dealer__c = :OSHFLG //lt 20230517 安徽两票制 add
                ];
                if (contract.size() == 1) {
                    contractName = contract[0].Name;
                    contractId = contract[0].Id;
                }
                editDelCommitBtnDisabled = true;
                List<String> DealerProductId = new List<String>();
                soql = makeSoql('', '', '', '', '', false, DealerProductId);
                size = Integer.valueOf(System.Label.orderdetLimitsize);
                initStandardController();
                product2Selected = Database.query(soql);
 
                for (Integer i = 0; i < product2Selected.size(); i++) {
                    consumableorderdetailsRecords.add(new ConsumableorderdetailsInfo(product2Selected[i]));
                    MidMap.put(product2Selected[i].Id, new ConsumableorderdetailsInfo(product2Selected[i]));
                }
                //只有在协议订货时会走这个for循环 其他两种订货模式都走的searchorderdetails方法
                if (String.isBlank(methodType) || (!methodType.equals('promotionorder') && !methodType.equals('hospitalorder'))) {
                    for (Integer i = 0; i < countDel.size(); i++) {
                        if (countDel[i].promotionorder__c == false && countDel[i].hospitalSpecialOffer__c == false) {
                            if (MidMap.containsKey(countDel[i].Consumable_Product__c)) {
                                ConsumableorderdetailsInfo Jstage = MidMap.get(countDel[i].Consumable_Product__c);
                                if (countDel[i].Box_Piece__c == '盒') {
                                    Jstage.allnumber = Jstage.allnumber + 1;
                                } else {
                                    Jstage.allnumber_piece = Jstage.allnumber_piece + 1;
                                }
                                MidMap.put(countDel[i].Consumable_Product__c, Jstage);
                            }
                        }
                    }
                }
                consumableorderdetailsRecords = new List<ConsumableorderdetailsInfo>();
                //经销商定价 计算
                for (ConsumableorderdetailsInfo bss : MidMap.values()) {
                    bss.sortBy = sortOrderAsc;
                    bss.packing_list = Integer.valueOf(bss.Prod.Product2__r.Packing_list_manual__c);
                    bss.approbation_No = bss.Prod.Product2__r.SFDA_Approbation_No__c;
                    bss.expiration_Date = bss.Prod.Product2__r.SFDA_Expiration_Date__c;
                    if (DealerProductMap.containsKey(bss.Prod.Id)) {
                        bss.SpecialCampaignPrice = DealerProductMap.get(bss.Prod.Id).Special_Campaign_Price__c;
                        bss.Campaign_EndDate = DealerProductMap.get(bss.Prod.Id).Campaign_EndDate__c;
                        bss.orderGoods_Limit = DealerProductMap.get(bss.Prod.Id).OrderGoods_Limit__c;
                    }
                    consumableorderdetailsRecords.add(bss);
                }
                consumableorderdetailsRecords.sort();
                if (methodType != null && methodType != '' && (methodType.equals('hospitalorder') || methodType.equals('promotionorder'))) {
                    searchorderdetails(
                        methodType,
                        accountid,
                        hospitalId,
                        contractId,
                        userWorkLocation,
                        accountName,
                        proLimitAndDate,
                        editAble
                    );
                    isfirst = true;
                }
                getPageInfo();
            } else {
                if (methodType != null && methodType.equals('hospitalorder')) {
                    List<Consumable_order__c> oclist = [
                        SELECT orderPattern__c, Order_ForHospital__c, Order_ForHospital__r.Name
                        FROM Consumable_order__c
                        WHERE id = :ESetid
                    ];
                    if (oclist.get(0).orderPattern__c.equals('hospitalorder')) {
                        hospitalName = oclist.get(0).Order_ForHospital__r.Name;
                        hospitalId = oclist.get(0).Order_ForHospital__c;
                    }
                }
                List<Consumable_Orderdetails__c> ConsumableorderdetailsSelected = new List<Consumable_Orderdetails__c>();
                //修改
                List<Consumable_order__c> qs = new List<Consumable_order__c>();
                qs = [
                    SELECT
                        Id,
                        Name,
                        Order_status__c,
                        Consumable_pdf_insert_day__c,
                        Dealer_Info__c,
                        Deliver_date__c,
                        Order_Reason__c,
                        Order_date__c,
                        Contract_application_decision__c,
                        Total_amount__c,
                        Offers_Price__c,
                        Order_effective_contact__c,
                        Order_effective_contact__r.Name
                    FROM Consumable_order__c
                    WHERE Id = :ESetId AND Order_Owner_WorkLocal__c = :userWorkLocation
                ];
                if (qs.size() > 0) {
                    coc = qs[0];
                    decisionCode = coc.Contract_application_decision__c;
                    contractName = coc.Order_effective_contact__r.Name;
                    contractId = coc.Order_effective_contact__r.Id;
                }
                if (qs[0].Order_status__c == '已提交' || qs[0].Order_status__c == '批准' || qs[0].Order_status__c == '附件上传完成') {
                    saveBtnDisabled = true;
                    sorderBtnDisabled = true;
                    editDelCommitBtnDisabled = false;
                }
                // 選択済みの明细を取得
                ConsumableorderdetailsSelected = [
                    SELECT
                        Id,
                        Name,
                        Consumable_order__c,
                        Consumable_Product__r.Name__c,
                        Consumable_Product__c,
                        Consumable_Product__r.Name,
                        Consumable_Count__c,
                        Consumable_Product__r.Category3__c,
                        Consumable_Product__r.Category4__c,
                        Consumable_Product__r.Category5__c,
                        Consumable_Product__r.Intra_Trade_List_RMB__c,
                        Consumable_Product__r.Asset_Model_No__c,
                        Sum_of_money__c,
                        Consumable_Product__r.SFDA_Status__c,
                        Consumable_Product__r.Product2__r.Packing_list_manual__c,
                        Consumable_Product__r.Product2__r.SFDA_Approbation_No__c,
                        Consumable_Product__r.Product2__r.SFDA_Expiration_Date__c
                    FROM Consumable_Orderdetails__c
                    WHERE
                        recordtypeid = :System.Label.RT_ConOrderDetail1_Order
                        AND Consumable_order__c = :ESetId
                        AND Order_Owner_WorkLocal__c = :userWorkLocation
                        AND Consumable_order__r.Dealer_Info__c = :accountid
                ];
                for (Consumable_Orderdetails__c cdc1 : ConsumableorderdetailsSelected) {
                    if (cdc1.Consumable_Product__c != null) {
                        orderzaikuId.add(cdc1.Consumable_Product__c);
                    }
                }
                soql = makeSoqlorderdet();
                System.debug('soql:' + soql);
                size = orderzaikuId.size();
                initStandardController();
                product2Selected = Database.query(soql);
                for (Integer i = 0; i < product2Selected.size(); i++) {
                    MidMap.put(product2Selected[i].Id, new ConsumableorderdetailsInfo(product2Selected[i]));
                }
                for (Integer i = 0; i < countDel.size(); i++) {
                    //add by rentx 2020-12-09
                    if (String.isNotBlank(methodType) && methodType.equals('hospitalorder')) {
                        if (countDel[i].hospitalSpecialOffer__c == true) {
                            //然后循环CountDel去修改map里的allnumber
                            if (MidMap.containsKey(countDel[i].Consumable_Product__c)) {
                                ConsumableorderdetailsInfo Jstage = MidMap.get(countDel[i].Consumable_Product__c);
                                if (countDel[i].Box_Piece__c == '盒') {
                                    Jstage.allnumber = Jstage.allnumber + 1;
                                } else {
                                    Jstage.allnumber_piece = Jstage.allnumber_piece + 1;
                                }
                                MidMap.put(countDel[i].Consumable_Product__c, Jstage);
                            }
                        }
                    } else if (String.isBlank(methodType) || methodType.equals('promotionorder')) {
                        if (countDel[i].promotionorder__c == true) {
                            if (MidMap.containsKey(countDel[i].Consumable_Product__c)) {
                                ConsumableorderdetailsInfo Jstage = MidMap.get(countDel[i].Consumable_Product__c);
                                if (countDel[i].Box_Piece__c == '盒') {
                                    Jstage.allnumber = Jstage.allnumber + 1;
                                } else {
                                    Jstage.allnumber_piece = Jstage.allnumber_piece + 1;
                                }
                                MidMap.put(countDel[i].Consumable_Product__c, Jstage);
                            }
                        }
                    } else if (
                        String.isBlank(methodType) || (!methodType.equals('promotionorder') && !methodType.equals('hospitalorder'))
                    ) {
                        if (countDel[i].promotionorder__c == false && countDel[i].hospitalSpecialOffer__c == false) {
                            if (MidMap.containsKey(countDel[i].Consumable_Product__c)) {
                                ConsumableorderdetailsInfo Jstage = MidMap.get(countDel[i].Consumable_Product__c);
                                if (countDel[i].Box_Piece__c == '盒') {
                                    Jstage.allnumber = Jstage.allnumber + 1;
                                } else {
                                    Jstage.allnumber_piece = Jstage.allnumber_piece + 1;
                                }
                                MidMap.put(countDel[i].Consumable_Product__c, Jstage);
                            }
                        }
                    }
                }
                consumableorderdetailsRecords = new List<ConsumableorderdetailsInfo>();
                //再把map里的值从新赋给ConsumableorderdetailsRecords
                for (ConsumableorderdetailsInfo bss : MidMap.values()) {
                    bss.packing_list = Integer.valueOf(bss.Prod.Product2__r.Packing_list_manual__c);
                    bss.approbation_No = bss.Prod.Product2__r.SFDA_Approbation_No__c;
                    bss.expiration_Date = bss.Prod.Product2__r.SFDA_Expiration_Date__c;
                    if (DealerProductMap.containsKey(bss.Prod.Id)) {
                        bss.SpecialCampaignPrice = DealerProductMap.get(bss.Prod.Id).Special_Campaign_Price__c;
                        bss.Campaign_EndDate = DealerProductMap.get(bss.Prod.Id).Campaign_EndDate__c;
                        bss.orderGoods_Limit = DealerProductMap.get(bss.Prod.Id).OrderGoods_Limit__c;
                    }
                    consumableorderdetailsRecords.add(bss);
                }
                for (ConsumableorderdetailsInfo ass : consumableorderdetailsRecords) {
                    ass.sortBy = sortOrderAsc;
                    for (Consumable_Orderdetails__c cdc1 : ConsumableorderdetailsSelected) {
                        sumPrice += cdc1.Sum_of_money__c;
                        if (ass.prod.Id == cdc1.Consumable_Product__c) {
                            ass.check = true;
                            ass.esd = cdc1;
                        }
                    }
                }
                //附件
                // attachmentinfo = [SELECT Id, Name, OwnerId, Owner.Name FROM Attachment WHERE parentid = :ESetId];
                // if (attachmentinfo.size() > 0) {
                //     for (Integer i = 0; i < attachmentinfo.size(); i++) {
                //         attachmentRecoeds.add(new ConsumableorderdetailsInfo(attachmentinfo[i]));
                //     }
                // }
<<<<<<< HEAD
                List<ContentDocumentLink> links = [
                    SELECT Id, ContentDocumentId
                    FROM ContentDocumentLink
                    WHERE LinkedEntityId = :ESetId
                ];
=======
                List<ContentDocumentLink> links = [SELECT Id, ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId = :ESetId];
>>>>>>> LEXCommunityLiJun
                if (links != null && links.size() > 0) {
                    List<String> documentIds = new List<String>();
                    for (ContentDocumentLink link : links) {
                        documentIds.add(link.ContentDocumentId);
                    }
                    List<ContentVersion> cvInfo = [
                        SELECT Id, Title, OwnerId, Owner.Name, CreatedDate, ContentDocumentId
                        FROM ContentVersion
                        WHERE ContentDocumentId IN :documentIds
                    ];
                    if (cvInfo.size() > 0) {
                        for (Integer i = 0; i < cvInfo.size(); i++) {
                            attachmentRecoeds.add(new ConsumableorderdetailsInfo(cvInfo[i]));
                        }
                    }
                }
                //
                consumableorderdetailsRecords.sort();
                getPageInfo();
            }
            //计算库存上、下限
            productLimtAndDate();
            lowerRecord();
            //明细排序
            List<String> upper = new List<String>();
            if (String.isNotBlank(ESetid)) {
                for (ConsumableorderdetailsInfo bss : consumableorderdetailsRecords) {
                    if (bss.esd.Consumable_count__c != null && bss.allnumber != null && bss.upperlimit != null) {
                        if (bss.esd.Consumable_count__c + bss.allnumber > bss.upperlimit) {
                            upper.add(bss.esd.Consumable_Product__r.Name__c);
                        }
                    }
                }
            }
            if (upper.size() > 0) {
                // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '存在以下产品订货数量超出库存上限!'));
                warningMsgList.add('存在以下产品订货数量超出库存上限!');
                for (Integer i = 0; i < upper.size(); i++) {
                    // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, upper[i]));
                    warningMsgList.add(upper[i]);
                }
            }
            if (lower.size() > 0) {
                // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '存在以下产品订货数量低于库存下限!'));
                warningMsgList.add('存在以下产品订货数量低于库存下限!');
                for (Integer i = 0; i < lower.size(); i++) {
                    // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, lower[i]));
                    warningMsgList.add(lower[i]);
                }
            }
            //价格查看权限
            Schema.DescribeFieldResult dfr = Product2__c.Intra_Trade_List_RMB__c.getDescribe();
            cansee = dfr.isAccessible();
            AggregateResult[] categoryList = [
                SELECT Count(id), Category3_text__c c3c
                FROM Product2__c
                WHERE Estimation_Entry_Possibility__c = '○' AND Product_Type__c LIKE :agencyProType AND Category3_text__c != NULL
                GROUP BY Category3_text__c
            ];
            //categoty3
            // categoryOptionList = new List<SelectOption>();
            category3Option = new List<CusOption>();
            // categoryOptionList.add(new SelectOption('', '-无-'));
            category3Option.add(new CusOption('-无-', ''));
            for (AggregateResult category3Search : categoryList) {
                String deliverycnt = String.valueOf(category3Search.get('c3c'));
                // categoryOptionList.add(new SelectOption(deliverycnt, deliverycnt));
                category3Option.add(new CusOption(deliverycnt, deliverycnt));
            }
            //categoty4
            // category4OptionList = new List<SelectOption>();
            category4Option = new List<CusOption>();
            // category4OptionList.add(new SelectOption('', '-无-'));
            category4Option.add(new CusOption('-无-', ''));
            //categoty5
            // category5OptionList = new List<SelectOption>();
            category5Option = new List<CusOption>();
            // category5OptionList.add(new SelectOption('', '-无-'));
            category5Option.add(new CusOption('-无-', ''));
            //return msg
            consumableorderdetailsRecordsview = consumableorderdetailsRecords;
            getConsumableShowTableFieldValue();
            results.result = 'Success';
            results.coc = coc;
            results.editAble = editAble;
            results.edoffersPrice = edoffersPrice;
            results.editDelCommitBtnDisabled = EditDelCommitBtnDisabled;
            results.category3Option = category3Option;
            results.category4Option = category4Option;
            results.category5Option = category5Option;
            results.hospitalName = hospitalName;
            results.contractName = contractName;
            results.consumableorderdetailsRecordsview = consumableorderdetailsRecordsview;
            results.attachmentRecoeds = attachmentRecoeds;
            results.cansee = cansee;
            results.agencyProType = agencyProType;
            results.agencyProType1 = agencyProType1;
            results.OSHFLG = OSHFLG;
            results.userWorkLocation = userWorkLocation;
            results.accountName = accountName;
            results.category_Goods = category_Goods;
            results.specialCampaign = specialCampaign;
            results.dealerProductId = DealerProductId;
            results.accountid = accountid;
            results.hospitalId = hospitalId;
            results.contractId = contractId;
            results.contactDealer = contactDealer;
            results.errorMsgList = errorMsgList;
            results.warningMsgList = warningMsgList;
            results.methodType = methodType;
            results.proLimitAndDate = proLimitAndDate;
        } catch (Exception e) {
            results.result = 'Fail';
            results.errorMsg = e.getLineNumber() + '---' + e.getMessage();
        }
        return results;
    }
 
    @AuraEnabled
    public static Results categoryAllload(String agencyProTypeStr, String category3Str) {
        Results results = new Results();
        agencyProType = agencyProTypeStr;
        category3 = category3Str;
        try {
            AggregateResult[] category4List = [
                SELECT Count(id), Category4_text__c c4c
                FROM Product2__c
                WHERE
                    Estimation_Entry_Possibility__c = '○'
                    AND Product_Type__c LIKE :agencyProType
                    AND Category3_text__c = :category3
                    AND Category4_text__c != NULL
                    AND Category5_text__c != NULL
                GROUP BY Category4_text__c
            ];
            // category4OptionList = new List<SelectOption>();
            category4Option = new List<CusOption>();
            // category4OptionList.add(new SelectOption('', '-无-'));
            category4Option.add(new CusOption('-无-', ''));
            for (AggregateResult category4Search : category4List) {
                String deliverycnt4 = String.valueOf(category4Search.get('c4c'));
                // category4OptionList.add(new SelectOption(deliverycnt4, deliverycnt4));
                category4Option.add(new CusOption(deliverycnt4, deliverycnt4));
            }
            AggregateResult[] category5List = [
                SELECT Count(id), Category5_text__c c5c
                FROM Product2__c
                WHERE
                    Estimation_Entry_Possibility__c = '○'
                    AND Product_Type__c LIKE :agencyProType
                    AND Category3_text__c = :category3
                    AND Category4_text__c != NULL
                    AND Category5_text__c != NULL
                GROUP BY Category5_text__c
            ];
            // category5OptionList = new List<SelectOption>();
            category5Option = new List<CusOption>();
            // category5OptionList.add(new SelectOption('', '-无-'));
            category5Option.add(new CusOption('-无-', ''));
            for (AggregateResult category5Search : category5List) {
                String deliverycnt5 = String.valueOf(category5Search.get('c5c'));
                // category5OptionList.add(new SelectOption(deliverycnt5, deliverycnt5));
                category5Option.add(new CusOption(deliverycnt5, deliverycnt5));
            }
            results.category4Option = category4Option;
            results.category5Option = category5Option;
            results.result = 'Success';
        } catch (Exception e) {
            results.result = 'Fail';
            results.errorMsg = e.getLineNumber() + '---' + e.getMessage();
        }
        return results;
    }
 
    @AuraEnabled
    public static Results categoryload(String agencyProTypeStr, String category3Str, String category4Str) {
        Results results = new Results();
        agencyProType = agencyProTypeStr;
        category3 = category3Str;
        category4 = category4Str;
        try {
            AggregateResult[] category4List = [
                SELECT Count(id), Category4_text__c c4c
                FROM Product2__c
                WHERE
                    Estimation_Entry_Possibility__c = '○'
                    AND Product_Type__c LIKE :agencyProType
                    AND Category3_text__c = :category3
                    AND Category4_text__c != NULL
                    AND Category5_text__c != NULL
                GROUP BY Category4_text__c
            ];
            // category4OptionList = new List<SelectOption>();
            category4Option = new List<CusOption>();
            // category4OptionList.add(new SelectOption('', '-无-'));
            category4Option.add(new CusOption('-无-', ''));
            for (AggregateResult category4Search : category4List) {
                String deliverycnt4 = String.valueOf(category4Search.get('c4c'));
                // category4OptionList.add(new SelectOption(deliverycnt4, deliverycnt4));
                category4Option.add(new CusOption(deliverycnt4, deliverycnt4));
            }
 
            AggregateResult[] category5List = [
                SELECT Count(id), Category5_text__c c5c
                FROM Product2__c
                WHERE
                    Estimation_Entry_Possibility__c = '○'
                    AND Product_Type__c LIKE :agencyProType
                    AND Category3_text__c = :category3
                    AND Category4_text__c = :category4
                    AND Category5_text__c != NULL
                GROUP BY Category5_text__c
            ];
            // category5OptionList = new List<SelectOption>();
            category5Option = new List<CusOption>();
            // category5OptionList.add(new SelectOption('', '-无-'));
            category5Option.add(new CusOption('-无-', ''));
            for (AggregateResult category5Search : category5List) {
                String deliverycnt5 = String.valueOf(category5Search.get('c5c'));
                // category5OptionList.add(new SelectOption(deliverycnt5, deliverycnt5));
                category5Option.add(new CusOption(deliverycnt5, deliverycnt5));
            }
            results.category4Option = category4Option;
            results.category5Option = category5Option;
            results.result = 'Success';
        } catch (Exception e) {
            results.result = 'Fail';
            results.errorMsg = e.getLineNumber() + '---' + e.getMessage();
        }
        return results;
    }
 
    // 画面初始化
    public static void lowerRecord() {
        List<ConsumableorderdetailsInfo> lowerRecord = new List<ConsumableorderdetailsInfo>();
        //库存明细取得
        Map<String, ConsumableorderdetailsInfo> midMaprecord = new Map<String, ConsumableorderdetailsInfo>();
        List<Product2__c> product2Selected = [
            SELECT Id, Name, Name__c, Intra_Trade_List_RMB__c, Asset_Model_No__c
            FROM Product2__c
            WHERE Pro2_Dealer_Object__c = TRUE AND Estimation_Entry_Possibility__c = '○'
        ];
        for (Integer i = 0; i < product2Selected.size(); i++) {
            lowerRecord.add(new ConsumableorderdetailsInfo(product2Selected[i]));
            //先把ConsumableorderdetailsRecords 做成map
            midMaprecord.put(product2Selected[i].Id, new ConsumableorderdetailsInfo(product2Selected[i]));
        }
        List<Consumable_order_details2__c> countDel = [
            SELECT
                Id,
                Bar_Code__c,
                Name,
                Inventory_date__c,
                Consumable_Product__c,
                Consumable_Product__r.Asset_Model_No__c,
                Recordtypeid,
                Guarantee_period_for_products__c,
                Isoverdue__c,
                Box_Piece__c,
                hospitalSpecialOffer__c,
                promotionorder__c
            FROM Consumable_order_details2__c
            WHERE
                Dealer_Arrive__c = TRUE
                AND Dealer_Shipment__c = FALSE
                AND Dealer_Saled__c = FALSE
                AND Dealer_Returned__c = FALSE
                AND Lose_Flag__c = FALSE
                AND Bar_Code__c != NULL
                AND Isoverdue__c = 1
                AND Arrive_Owner_Work_Location__c = :userWorkLocation
                //AND Consumable_order_minor__r.Dealer_Info__c = :accountid
                AND Dealer_Info_text__c = :accountName
        ];
        for (Integer i = 0; i < countDel.size(); i++) {
            //add by rentx 2020-12-09
            if (String.isNotBlank(methodType) && methodType.equals('hospitalorder')) {
                if (countDel[i].hospitalSpecialOffer__c == true) {
                    //然后循环CountDel去修改map里的allnumber
                    if (midMaprecord.containsKey(countDel[i].Consumable_Product__c)) {
                        ConsumableorderdetailsInfo Jstage = midMaprecord.get(countDel[i].Consumable_Product__c);
                        if (countDel[i].Box_Piece__c == '盒') {
                            Jstage.allnumber = Jstage.allnumber + 1;
                        } else {
                            Jstage.allnumber_piece = Jstage.allnumber_piece + 1;
                        }
                        //Jstage.BoxPiece = CountDel[i].Box_Piece__c;
                        midMaprecord.put(countDel[i].Consumable_Product__c, Jstage);
                    }
                }
            } else if (String.isBlank(methodType) || methodType.equals('promotionorder')) {
                if (countDel[i].promotionorder__c == true) {
                    if (midMaprecord.containsKey(countDel[i].Consumable_Product__c)) {
                        ConsumableorderdetailsInfo Jstage = midMaprecord.get(countDel[i].Consumable_Product__c);
                        if (countDel[i].Box_Piece__c == '盒') {
                            Jstage.allnumber = Jstage.allnumber + 1;
                        } else {
                            Jstage.allnumber_piece = Jstage.allnumber_piece + 1;
                        }
                        midMaprecord.put(countDel[i].Consumable_Product__c, Jstage);
                    }
                }
            } else if (String.isBlank(methodType) || (!methodType.equals('promotionorder') && !methodType.equals('hospitalorder'))) {
                if (countDel[i].promotionorder__c == false && countDel[i].hospitalSpecialOffer__c == false) {
                    if (midMaprecord.containsKey(countDel[i].Consumable_Product__c)) {
                        ConsumableorderdetailsInfo Jstage = midMaprecord.get(countDel[i].Consumable_Product__c);
                        if (countDel[i].Box_Piece__c == '盒') {
                            Jstage.allnumber = Jstage.allnumber + 1;
                        } else {
                            Jstage.allnumber_piece = Jstage.allnumber_piece + 1;
                        }
                        midMaprecord.put(countDel[i].Consumable_Product__c, Jstage);
                    }
                }
            }
        }
        lowerRecord = new List<ConsumableorderdetailsInfo>();
        //再把map里的值从新赋给ConsumableorderdetailsRecords
        for (ConsumableorderdetailsInfo bss : midMaprecord.values()) {
            lowerRecord.add(bss);
        }
        allProductLimt(lowerRecord);
        for (ConsumableorderdetailsInfo bss : lowerRecord) {
            if (bss.allnumber < bss.lowerlimit) {
                lower.add(bss.Prod.Name__c);
            }
        }
    }
 
    //库存上下限
    public static void productLimtAndDate() {
        String nowName = null, nowRightAsstModelNo = null;
        Map<String, String> productLimt = new Map<String, String>();
        for (Integer i = 0; i < proLimitAndDate.size(); i++) {
            nowName = proLimitAndDate[i];
            if (nowName.indexOf('|') >= 0) {
                nowRightAsstModelNo = nowName.subString(0, nowName.indexOf('|'));
                nowName = nowName.subString(nowName.indexOf('|') + 1);
            }
            productLimt.put(nowRightAsstModelNo, nowName);
        }
        for (ConsumableorderdetailsInfo ass : consumableorderdetailsRecords) {
            if (productLimt.containsKey(ass.Prod.Asset_Model_No__c)) {
                ass.lowerlimit = decimal.valueOf(
                    productLimt.get(ass.Prod.Asset_Model_No__c).subString(0, productLimt.get(ass.Prod.Asset_Model_No__c).indexOf('|'))
                );
                ass.upperlimit = decimal.valueOf(
                    productLimt.get(ass.Prod.Asset_Model_No__c).subString(productLimt.get(ass.Prod.Asset_Model_No__c).indexOf('|') + 1)
                );
            }
        }
    }
 
    //全部库存上下限
    private static void allProductLimt(List<ConsumableorderdetailsInfo> lowerRecord) {
        String nowName = null, nowRightAsstModelNo = null;
        Map<String, String> productLimt = new Map<String, String>();
        for (Integer i = 0; i < proLimitAndDate.size(); i++) {
            nowName = proLimitAndDate[i];
            if (nowName.indexOf('|') >= 0) {
                nowRightAsstModelNo = nowName.subString(0, nowName.indexOf('|'));
                nowName = nowName.subString(nowName.indexOf('|') + 1);
            }
            productLimt.put(nowRightAsstModelNo, nowName);
        }
        for (ConsumableorderdetailsInfo ass : lowerRecord) {
            if (productLimt.containsKey(ass.Prod.Asset_Model_No__c)) {
                ass.lowerlimit = decimal.valueOf(
                    productLimt.get(ass.Prod.Asset_Model_No__c).subString(0, productLimt.get(ass.Prod.Asset_Model_No__c).indexOf('|'))
                );
                ass.upperlimit = decimal.valueOf(
                    productLimt.get(ass.Prod.Asset_Model_No__c).subString(productLimt.get(ass.Prod.Asset_Model_No__c).indexOf('|') + 1)
                );
            }
        }
    }
 
    @AuraEnabled
    public static Results searchConsumableorderdetails(
        String userWorkLocationStr,
        String agencyProTypeStr,
        String accountNameStr,
        String accountIdStr,
        String hospitalIdStr,
        String contractIdStr,
        String category1Str,
        String category3Str,
        String category4Str,
        String category5Str,
        String category_GoodStr,
        Boolean specialCampaignStr,
        String dealerProductIdStr,
        String methodTypeStr,
        String consumableorderdetailsRecordsviewStr,
        Boolean editAbleStr,
        List<String> proLimitAndDateList
    ) {
        Results results = new Results();
        errorMsgList = new List<String>();
        warningMsgList = new List<String>();
        userWorkLocation = userWorkLocationStr;
        agencyProType = agencyProTypeStr;
        accountName = accountNameStr;
        accountid = accountIdStr;
        hospitalId = hospitalIdStr;
        contractId = contractIdStr;
        category1 = category1Str;
        category3 = category3Str;
        category4 = category4Str;
        category5 = category5Str;
        category_Goods = category_GoodStr;
        specialCampaign = specialCampaignStr;
        methodType = methodTypeStr;
        editAble = editAbleStr;
        proLimitAndDate = proLimitAndDateList;
        dealerProductId = (List<String>) JSON.deserialize(dealerProductIdStr, List<String>.class);
        consumableorderdetailsRecordsview = (List<ConsumableorderdetailsInfo>) JSON.deserialize(
            consumableorderdetailsRecordsviewStr,
            List<ConsumableorderdetailsInfo>.class
        );
        size = Integer.valueOf(System.Label.orderdetLimitsize);
        pageLimit = Integer.valueOf(System.Label.orderdetPageLimitsize);
        try {
            searchDone = 'searchDone';
            sortKey = '1';
            preSortKey = '1';
            sortOrderAsc = false;
            sortOrder = new String[7];
            sortOrder = new List<String>{ ' ', ' ', ' ', ' ', '↓', '', '', '' };
            Map<String, String> selectedIdMap = new Map<String, String>();
            List<ConsumableorderdetailsInfo> derdetailsRecords = new List<ConsumableorderdetailsInfo>();
            Map<String, ConsumableorderdetailsInfo> MidMap = new Map<String, ConsumableorderdetailsInfo>();
            List<ConsumableorderdetailsInfo> reSet = new List<ConsumableorderdetailsInfo>();
            List<Consumable_order_details2__c> countDel = [
                SELECT
                    Id,
                    Bar_Code__c,
                    Name,
                    Inventory_date__c,
                    Consumable_Product__c,
                    Consumable_Product__r.Asset_Model_No__c,
                    Recordtypeid,
                    Box_Piece__c,
                    //add by rentx 2020-12-09
                    hospitalSpecialOffer__c,
                    promotionorder__c
                //add by rentx 2020-12-09
                FROM Consumable_order_details2__c
                WHERE
                    Dealer_Arrive__c = TRUE
                    AND Dealer_Shipment__c = FALSE
                    AND Dealer_Saled__c = FALSE
                    AND Dealer_Returned__c = FALSE
                    AND Lose_Flag__c = FALSE
                    AND Bar_Code__c != NULL
                    AND Arrive_Owner_Work_Location__c = :userWorkLocation
                    AND Dealer_Info_text__c = :accountName
            ];
            List<Product2__c> product2Selected = new List<Product2__c>();
            consumableorderdetailsRecords = new List<ConsumableorderdetailsInfo>();
            soql = makeSoql(category1, category_Goods, category3, category4, category5, specialCampaign, DealerProductId);
            size = Integer.valueOf(System.Label.orderdetLimitsize);
            initStandardController();
            System.debug('soql:' + soql);
            product2Selected = Database.query(soql);
            for (Integer i = 0; i < product2Selected.size(); i++) {
                MidMap.put(product2Selected[i].Id, new ConsumableorderdetailsInfo(product2Selected[i]));
            }
            for (Integer i = 0; i < countDel.size(); i++) {
                //然后循环CountDel去修改map里的allnumber
                if (String.isNotBlank(methodType) && methodType.equals('hospitalorder')) {
                    if (countDel[i].hospitalSpecialOffer__c == true) {
                        if (MidMap.containsKey(countDel[i].Consumable_Product__c)) {
                            ConsumableorderdetailsInfo Jstage = MidMap.get(countDel[i].Consumable_Product__c);
                            if (countDel[i].Box_Piece__c == '盒') {
                                Jstage.allnumber = Jstage.allnumber + 1;
                            } else {
                                Jstage.allnumber_piece = Jstage.allnumber_piece + 1;
                            }
                            MidMap.put(countDel[i].Consumable_Product__c, Jstage);
                        }
                    }
                } else if (String.isBlank(methodType) || methodType.equals('promotionorder')) {
                    if (countDel[i].promotionorder__c == true) {
                        if (MidMap.containsKey(countDel[i].Consumable_Product__c)) {
                            ConsumableorderdetailsInfo Jstage = MidMap.get(countDel[i].Consumable_Product__c);
                            if (countDel[i].Box_Piece__c == '盒') {
                                Jstage.allnumber = Jstage.allnumber + 1;
                            } else {
                                Jstage.allnumber_piece = Jstage.allnumber_piece + 1;
                            }
                            MidMap.put(countDel[i].Consumable_Product__c, Jstage);
                        }
                    }
                } else if (String.isBlank(methodType) || (!methodType.equals('promotionorder') && !methodType.equals('hospitalorder'))) {
                    if (countDel[i].promotionorder__c == false && countDel[i].hospitalSpecialOffer__c == false) {
                        if (MidMap.containsKey(countDel[i].Consumable_Product__c)) {
                            ConsumableorderdetailsInfo Jstage = MidMap.get(countDel[i].Consumable_Product__c);
                            if (countDel[i].Box_Piece__c == '盒') {
                                Jstage.allnumber = Jstage.allnumber + 1;
                            } else {
                                Jstage.allnumber_piece = Jstage.allnumber_piece + 1;
                            }
                            MidMap.put(countDel[i].Consumable_Product__c, Jstage);
                        }
                    }
                }
            }
            //再把map里的值从新赋给ConsumableorderdetailsRecordsa0l0l0000000byXAAQ
            for (ConsumableorderdetailsInfo bss : MidMap.values()) {
                if (selectedIdMap.containsKey(bss.Prod.id)) {
                    continue;
                } else {
                    if (DealerProductMap.containsKey(bss.Prod.Id)) {
                        bss.SpecialCampaignPrice = DealerProductMap.get(bss.Prod.Id).Special_Campaign_Price__c;
                        bss.Campaign_EndDate = DealerProductMap.get(bss.Prod.Id).Campaign_EndDate__c;
                        bss.orderGoods_Limit = DealerProductMap.get(bss.Prod.Id).OrderGoods_Limit__c;
                    }
                    bss.sortBy = sortOrderAsc;
                    bss.packing_list = Integer.valueOf(bss.Prod.Product2__r.Packing_list_manual__c);
                    bss.approbation_No = bss.Prod.Product2__r.SFDA_Approbation_No__c;
                    bss.expiration_Date = bss.Prod.Product2__r.SFDA_Expiration_Date__c;
                    consumableorderdetailsRecords.add(bss);
                }
            }
            consumableorderdetailsRecords.sort();
            productLimtAndDate();
            getPageInfo();
            sortKey = '1';
            preSortKey = '1';
            sortOrderAsc = false;
            sortOrder = new String[7];
            sortOrder = new List<String>{ '  ', '  ', ' ', '', '', '', '', '' };
            cate1ForSort = category1;
            // 显示数据条数信息
            // makeMessage();
            results.errorMsgList = errorMsgList;
            results.warningMsgList = warningMsgList;
            if (consumableorderdetailsRecords.size() > 0) {
                getConsumableShowTableFieldValue();
                results.result = 'Success';
                results.consumableorderdetailsRecordsview = consumableorderdetailsRecordsview;
                results.errorMsg = '搜索到' + consumableorderdetailsRecords.size() + '件产品';
            } else {
                getConsumableShowTableFieldValue();
                results.result = 'Fail';
                results.consumableorderdetailsRecordsview = consumableorderdetailsRecordsview;
                results.errorMsg = '没有搜索到相关数据';
            }
        } catch (Exception e) {
            results.result = 'Fail';
            results.errorMsg = e.getLineNumber() + '---' + e.getMessage();
        }
        return results;
    }
 
    //医院--检索
    @AuraEnabled
    public static Results searchorderdetails(
        String methodTypeStr,
        String accountIdStr,
        String hospitalIdStr,
        String contractIdStr,
        String userWorkLocationStr,
        String accountNameStr,
        List<String> proLimitAndDateList,
        Boolean editAbleStr
    ) {
        Results results = new Results();
        methodType = methodTypeStr;
        accountId = accountIdStr;
        hospitalId = hospitalIdStr;
        contractId = contractIdStr;
        userWorkLocation = userWorkLocationStr;
        accountName = accountNameStr;
        proLimitAndDate = proLimitAndDateList;
        editAble = editAbleStr;
        size = Integer.valueOf(System.Label.orderdetLimitsize);
        pageLimit = Integer.valueOf(System.Label.orderdetPageLimitsize);
        try {
            soql = 'SELECT Id, Name,Name__c,Intra_Trade_List_RMB__c,Asset_Model_No__c,SFDA_Status__c,Product2__r.SFDA_Approbation_No__c,Product2__r.SFDA_Expiration_Date__c,Product2__r.Packing_list_manual__c,Category3__c,Category4__c,Category5__c FROM Product2__c WHERE Estimation_Entry_Possibility__c = \'○\' ';
            if (methodType.equals('hospitalorder')) {
                //医院id 有值
                List<hospitalprice__c> hplist = [
                    SELECT id, product__c
                    FROM hospitalprice__c
                    WHERE account__c = :accountid AND hospital__c = :hospitalId
                ];
                if (hplist != null && hplist.size() > 0) {
                    List<String> hpids = new List<String>();
                    for (hospitalprice__c hc : hplist) {
                        hpids.add(hc.product__c);
                    }
 
                    if (hpids != null && hpids.size() > 0) {
                        soql += ' AND Id in : hpids ';
                    }
                } else {
                    //该医院下没有符合医院特价的产品
                    soql += ' AND Id = null ';
                }
            } else if (methodType.equals('promotionorder')) {
                List<Dealer_Product__c> dpclist = [
                    SELECT Id, Dealer_Product2__c
                    FROM Dealer_Product__c
                    WHERE Dealer_Contact__c = :contractId AND (Special_Discount__c != NULL OR Special_Campaign_Price__c != NULL)
                ];
                if (dpclist != null && dpclist.size() > 0) {
                    String ids = '(';
                    for (Dealer_Product__c hc : dpclist) {
                        hpids.add(hc.Dealer_Product2__c);
                        ids += '\'' + hc.Dealer_Product2__c + '\',';
                    }
                    ids = ids.substring(0, ids.length() - 1) + ')';
                    if (hpids != null && hpids.size() > 0) {
                        // soql += ' AND Id in : hpids ';
                        soql += ' AND Id in ' + ids;
                    }
                } else {
                    //该经销商下没有促销价格的产品
                    soql += ' AND Id = null ';
                }
            }
            size = Integer.valueOf(System.Label.orderdetLimitsize);
            initStandardController();
            List<Product2__c> product2Selected = new List<Product2__c>();
            Map<String, ConsumableorderdetailsInfo> MidMap = new Map<String, ConsumableorderdetailsInfo>();
            Map<String, String> selectedIdMap = new Map<String, String>();
            consumableorderdetailsRecords = new List<ConsumableorderdetailsInfo>();
            product2Selected = Database.query(soql);
            for (Integer i = 0; i < product2Selected.size(); i++) {
                MidMap.put(product2Selected[i].Id, new ConsumableorderdetailsInfo(product2Selected[i]));
            }
            List<Consumable_order_details2__c> countDel = [
                SELECT
                    Id,
                    Bar_Code__c,
                    Name,
                    Inventory_date__c,
                    Consumable_Product__c,
                    Consumable_Product__r.Asset_Model_No__c,
                    Recordtypeid,
                    Box_Piece__c,
                    hospitalSpecialOffer__c,
                    promotionorder__c
                FROM Consumable_order_details2__c
                WHERE
                    Dealer_Arrive__c = TRUE
                    AND Dealer_Shipment__c = FALSE
                    AND Dealer_Saled__c = FALSE
                    AND Dealer_Returned__c = FALSE
                    AND Lose_Flag__c = FALSE
                    AND Bar_Code__c != NULL
                    AND Arrive_Owner_Work_Location__c = :userWorkLocation
                    //AND Consumable_order_minor__r.Dealer_Info__c = :accountid
                    AND Dealer_Info_text__c = :accountName
            ];
            for (Integer i = 0; i < countDel.size(); i++) {
                if (methodType.equals('hospitalorder')) {
                    if (countDel[i].hospitalSpecialOffer__c == true) {
                        //然后循环CountDel去修改map里的allnumber
                        if (MidMap.containsKey(countDel[i].Consumable_Product__c)) {
                            ConsumableorderdetailsInfo Jstage = MidMap.get(countDel[i].Consumable_Product__c);
                            if (countDel[i].Box_Piece__c == '盒') {
                                Jstage.allnumber = Jstage.allnumber + 1;
                            } else {
                                Jstage.allnumber_piece = Jstage.allnumber_piece + 1;
                            }
                            //Jstage.BoxPiece = CountDel[i].Box_Piece__c;
                            MidMap.put(countDel[i].Consumable_Product__c, Jstage);
                        }
                    }
                } else if (methodType.equals('promotionorder')) {
                    if (countDel[i].promotionorder__c == true) {
                        //然后循环CountDel去修改map里的allnumber
                        if (MidMap.containsKey(countDel[i].Consumable_Product__c)) {
                            ConsumableorderdetailsInfo Jstage = MidMap.get(countDel[i].Consumable_Product__c);
                            if (countDel[i].Box_Piece__c == '盒') {
                                Jstage.allnumber = Jstage.allnumber + 1;
                            } else {
                                Jstage.allnumber_piece = Jstage.allnumber_piece + 1;
                            }
                            //Jstage.BoxPiece = CountDel[i].Box_Piece__c;
                            MidMap.put(countDel[i].Consumable_Product__c, Jstage);
                        }
                    }
                }
            }
            //再把map里的值从新赋给ConsumableorderdetailsRecordsa0l0l0000000byXAAQ
            for (ConsumableorderdetailsInfo bss : MidMap.values()) {
                if (selectedIdMap.containsKey(bss.Prod.id)) {
                    continue;
                } else {
                    if (DealerProductMap.containsKey(bss.Prod.Id)) {
                        bss.SpecialCampaignPrice = DealerProductMap.get(bss.Prod.Id).Special_Campaign_Price__c;
                        bss.Campaign_EndDate = DealerProductMap.get(bss.Prod.Id).Campaign_EndDate__c;
                        bss.orderGoods_Limit = DealerProductMap.get(bss.Prod.Id).OrderGoods_Limit__c;
                    }
                    bss.sortBy = sortOrderAsc;
                    bss.packing_list = Integer.valueOf(bss.Prod.Product2__r.Packing_list_manual__c);
                    bss.approbation_No = bss.Prod.Product2__r.SFDA_Approbation_No__c;
                    bss.expiration_Date = bss.Prod.Product2__r.SFDA_Expiration_Date__c;
                    consumableorderdetailsRecords.add(bss);
                }
            }
            consumableorderdetailsRecords.sort();
            productLimtAndDate();
            getPageInfoForHos();
            sortKey = '1';
            preSortKey = '1';
            sortOrderAsc = false;
            sortOrder = new String[7];
            sortOrder = new List<String>{ '  ', '  ', ' ', '', '', '', '', '' };
            cate1ForSort = category1;
            // 显示数据条数信息
            noOfRecords = consumableorderdetailsRecords.size();
            getConsumableShowTableFieldValue();
            results.consumableorderdetailsRecordsview = consumableorderdetailsRecordsview;
            if (consumableorderdetailsRecordsview.size() > 0) {
                results.result = 'Success';
                results.errorMsg = '共搜索到' + consumableorderdetailsRecordsview.size() + '条数据';
            } else {
                results.result = 'Fail';
                results.errorMsg = '没有搜索到相关数据';
            }
        } catch (Exception e) {
            results.result = 'Fail';
            results.errorMsg = e.getLineNumber() + '---' + e.getMessage();
        }
        return results;
    }
 
    //用户切换医院时取消选中的产品
    private static List<ConsumableorderdetailsInfo> getPageInfoForHos() {
        List<ConsumableorderdetailsInfo> reSet = new List<ConsumableorderdetailsInfo>();
        Map<String, String> selectedIdMap = new Map<String, String>();
        consumableorderdetailsRecordsview = new List<ConsumableorderdetailsInfo>();
        if (editAble) {
            consumableorderdetailsRecordsview = reSet;
        }
        Integer pagestartNo = (con.getPageNumber() * size) - size;
        Integer pageendNo = (con.getPageNumber() * size) > noOfRecords ? noOfRecords : (con.getPageNumber() * size - 1);
        Integer addNo = 0;
        for (Integer i = pagestartNo; i < consumableorderdetailsRecords.size(); i++) {
            Consumable_Orderdetails__c orderdetails1 = new Consumable_Orderdetails__c();
            if (selectedIdMap.containsKey(consumableorderdetailsRecords[i].Prod.Id)) {
                addNo++;
                //continue;
            }
            // else if (consumableorderdetailsRecordsview.size() >= pageLimit + size) {
            //     break;
            // }
            else {
                if (consumableorderdetailsRecords[i].check == false) {
                    consumableorderdetailsRecords[i].esd = orderdetails1;
                }
                consumableorderdetailsRecordsview.add(consumableorderdetailsRecords[i]);
                addNo++;
            }
            // if (addNo >= size){
            //     break;
            // }
        }
        return consumableorderdetailsRecordsview;
    }
    //add by rentx 2020-12-03 end =====================================================================================================================
    //特价
    public static void OffersPrice() {
        edoffersPrice = true;
    }
 
    //得到促销产品Id
    private static List<String> getDealerProductId() {
        List<String> ProductId = new List<String>();
        Map<String, String> DealerProductIdMap = new Map<String, String>();
        Date dateToday = Date.today();
        List<Dealer_Product__c> DealerProductList = [
            SELECT
                Id,
                Name,
                Dealer_Product2__c,
                Special_Campaign_Price__c,
                Campaign_StartDate__c,
                Campaign_EndDate__c,
                Dealer_Contact__c,
                OrderGoods_Limit__c
            FROM Dealer_Product__c
            WHERE
                Dealer_Contact__c IN :contactDealer
                AND Campaign_StartDate__c <= :dateToday
                AND Campaign_EndDate__c >= :dateToday
                AND Special_Campaign_Price__c != NULL
        ];
        for (Dealer_Product__c dealerProduct : DealerProductList) {
            if (DealerProductIdMap.containsKey(dealerProduct.Dealer_Product2__c)) {
                continue;
            } else {
                ProductId.add(dealerProduct.Dealer_Product2__c);
                DealerProductIdMap.put(dealerProduct.Dealer_Product2__c, dealerProduct.Dealer_Product2__c);
            }
        }
        return ProductId;
    }
 
    private static String makeSoql(
        String CateName,
        String CateCode,
        String Category3,
        String Category4,
        String Category5,
        Boolean specialCampaign,
        List<String> DealerProductId
    ) {
        String soql = 'SELECT Id, Name,Name__c,Intra_Trade_List_RMB__c,Asset_Model_No__c,SFDA_Status__c,Product2__r.SFDA_Approbation_No__c,Product2__r.SFDA_Expiration_Date__c,Product2__r.Packing_list_manual__c,Category3__c,Category4__c,Category5__c FROM Product2__c WHERE Estimation_Entry_Possibility__c = \'○\' ';
        // add begin ================================================================================================
        if (methodType != null && methodType.equals('hospitalorder')) {
            //如果是医院特价
            //1.判断 医院id是否有值 如果有值 则根据医院id去 医院特价表中获取产品id
            //医院id 有值
            if (hospitalId == null || hospitalId == '') {
                soql += ' and id = null ';
                // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '请选择医院'));
                warningMsgList.add('请选择医院');
            } else {
                List<hospitalprice__c> hplist = [
                    SELECT id, product__c
                    FROM hospitalprice__c
                    WHERE account__c = :accountid AND hospital__c = :hospitalId
                ];
                if (hplist != null && hplist.size() > 0) {
                    hpids = new List<String>();
                    for (hospitalprice__c hc : hplist) {
                        hpids.add(hc.product__c);
                    }
                    if (hpids != null && hpids.size() > 0) {
                        soql += ' AND Id in : hpids ';
                    }
                } else {
                    //该医院下没有符合医院特价的产品
                    soql += ' AND Id = null ';
                    return soql;
                }
            }
        }
        //促销订货
        if (methodType != null && methodType.equals('promotionorder')) {
            if (contractId == null || contractId == '') {
                soql += ' and id = null ';
                // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '请选择合同'));
                warningMsgList.add('请选择合同');
            } else {
                //1.查询所有经销商产品
                List<Dealer_Product__c> dpclist = [
                    SELECT Id, Dealer_Product2__c
                    FROM Dealer_Product__c
                    WHERE Dealer_Contact__c = :contractId AND (Special_Discount__c != NULL OR Special_Campaign_Price__c != NULL)
                ];
 
                if (dpclist != null && dpclist.size() > 0) {
                    hpids = new List<String>();
                    for (Dealer_Product__c hc : dpclist) {
                        hpids.add(hc.Dealer_Product2__c);
                    }
                    if (hpids != null && hpids.size() > 0) {
                        soql += ' AND Id in : hpids ';
                    }
                } else {
                    //该经销商下没有促销价格的产品
                    soql += ' AND Id = null ';
                    return soql;
                }
            }
        }
        //add end ===================================================================================================
        if (!String.isBlank(CateName)) {
            soql +=
                ' AND (Name__c like \'%' +
                String.escapeSingleQuotes(CateName.replaceAll('%', '\\%')) +
                '%\' or Asset_Model_No__c like \'%' +
                String.escapeSingleQuotes(CateName.replaceAll('%', '\\%')) +
                '%\')';
        }
        if (!String.isBlank(Category3)) {
            soql += ' AND Category3__c = \'' + Category3 + '\'';
        }
        if (!String.isBlank(Category4)) {
            soql += ' AND Category4__c = \'' + Category4 + '\'';
        }
        if (!String.isBlank(Category5)) {
            soql += ' AND Category5__c = \'' + Category5 + '\'';
        }
        if (agencyProType == 'ET') {
            soql += ' AND Pro2_Dealer_Object__c = true';
        }
        if (agencyProType == 'ENG') {
            soql += ' AND Pro2_Dealer_ENG__c = true';
        }
        soql += ' AND Intra_Trade_List_RMB__c > 0 ';
        System.debug('soql +++++++++++  ' + soql);
        return soql;
    }
 
    private static String makeSoqlorderdet() {
        String sqlTail = '(\'';
        for (Integer i = 0; i < orderzaikuId.size(); i++) {
            if (i < orderzaikuId.size() - 1) {
                sqlTail += orderzaikuId[i] + '\',\'';
            } else {
                sqlTail += orderzaikuId[i] + '\')';
            }
        }
        String soql = 'SELECT Id, Name,Name__c,Intra_Trade_List_RMB__c,Asset_Model_No__c,SFDA_Status__c,Product2__r.SFDA_Approbation_No__c,Product2__r.SFDA_Expiration_Date__c,Product2__r.Packing_list_manual__c,Category3__c,Category4__c,Category5__c FROM Product2__c WHERE Estimation_Entry_Possibility__c = \'○\' ';
        System.debug('sqlTail:' + sqlTail);
        System.debug('orderzaikuId:' + orderzaikuId);
        if (orderzaikuId.size() > 0) {
            soql += ' AND Id in' + sqlTail;
        }
        return soql;
    }
 
    // 编辑按钮
    @AuraEnabled
    public static Results setEditAble(String eSetidStr) {
        Results results = new Results();
        ESetId = eSetidStr;
        try {
            statusEdit = 'Redirect';
<<<<<<< HEAD
            List<Consumable_order__c> oclist = [
                SELECT orderPattern__c
                FROM Consumable_order__c
                WHERE id = :ESetid
            ];
=======
            List<Consumable_order__c> oclist = [SELECT orderPattern__c FROM Consumable_order__c WHERE id = :ESetid];
>>>>>>> LEXCommunityLiJun
            String url = '/lexconsumable?ESetid=' + ESetid + '&KeyWords=' + statusEdit + '&type=' + oclist.get(0).orderPattern__c;
            results.result = 'Success';
            results.url = url;
        } catch (Exception e) {
            results.result = 'Fail';
            results.errorMsg = e.getLineNumber() + '---' + e.getMessage();
        }
        return results;
    }
 
    // 再申请
    @AuraEnabled
    public static Results backOrder(String eSetidStr) {
        Results results = new Results();
        ESetId = eSetidStr;
        statusEdit = 'Redirect';
        returnOrder = true;
        try {
            statusEdit = 'Redirect';
<<<<<<< HEAD
            List<Consumable_order__c> oclist = [
                SELECT orderPattern__c
                FROM Consumable_order__c
                WHERE id = :ESetid
            ];
=======
            List<Consumable_order__c> oclist = [SELECT orderPattern__c FROM Consumable_order__c WHERE id = :ESetid];
>>>>>>> LEXCommunityLiJun
            String url = '/lexconsumable?ESetid=' + ESetid + '&KeyWords=' + statusEdit + '&type=' + oclist.get(0).orderPattern__c;
            results.result = 'Success';
            results.url = url;
        } catch (Exception e) {
            results.result = 'Fail';
            results.errorMsg = e.getLineNumber() + '---' + e.getMessage();
        }
        return results;
    }
 
    //上传附件
    @AuraEnabled
    public static Results filesUpload(String pId, String fileName, String base64Data) {
        Results results = new Results();
        try {
            base64Data = EncodingUtil.urlDecode(base64Data, 'UTF-8');
            ContentVersion cv = new ContentVersion();
            cv.Title = fileName;
            cv.PathOnClient = '/' + fileName;
            cv.FirstPublishLocationId = pId;
            cv.VersionData = EncodingUtil.base64Decode(base64Data);
            cv.IsMajorVersion = true;
            insert cv;
<<<<<<< HEAD
            Consumable_order__c c = [
                SELECT Id
                FROM Consumable_order__c
                WHERE Id = :pId
            ];
=======
            Consumable_order__c c = [SELECT Id FROM Consumable_order__c WHERE Id = :pId];
>>>>>>> LEXCommunityLiJun
            c.Consumable_pdf_insert_day__c = Date.today();
            update c;
            results.result = 'Success';
        } catch (Exception e) {
            results.result = 'Fail';
            results.errorMsg = e.getLineNumber() + '---' + e.getMessage();
        }
        return results;
    }
 
    //删除按钮
    @AuraEnabled
    public static Results delConsumable(String eSetidStr) {
        Results results = new Results();
        ESetId = eSetidStr;
        try {
            Consumable_order__c cord = new Consumable_order__c(Id = ESetId);
            List<Consumable_Orderdetails__c> orderdetails1 = [
                SELECT Id
                FROM Consumable_Orderdetails__c
                WHERE Consumable_order__c = :EsetId
            ];
            delete orderdetails1;
            delete cord;
            results.result = 'Success';
            results.url = '/lexconsumableordermanage';
        } catch (Exception e) {
            results.result = 'Fail';
            results.errorMsg = e.getLineNumber() + '---' + e.getMessage();
        }
        return results;
    }
 
    // 提交按钮
    @AuraEnabled
    public static Results sorder(String eSetidStr, String accountidStr) {
        Results results = new Results();
        errorMsgList = new List<String>();
        warningMsgList = new List<String>();
        ESetId = eSetidStr;
        accountid = accountidStr;
        Savepoint sp = Database.setSavepoint();
        try {
            Map<Id, String> prodMap = new Map<Id, String>();
            Consumable_order__c P = new Consumable_order__c();
            P = new Consumable_order__c();
            p.Id = ESetId;
            p.Order_date__c = Date.today();
            p.Order_status__c = '附件上传完成';
            for (Consumable_Orderdetails__c cod1 : [
                SELECT Consumable_product__r.Product2__c, Consumable_product__r.Name__c
                FROM Consumable_Orderdetails__c
                WHERE Consumable_order__c = :ESetId
            ]) {
                prodMap.put(cod1.Consumable_product__r.Product2__c, cod1.Consumable_product__r.Name__c);
            }
            // GZW 提交产品无效 出错误消息
            System.debug(prodMap);
            Map<String, String> chkMap = OpportunityWebService.MapCheckProRegisterDecide(prodMap, accountid, '');
            System.debug(chkMap);
            if (chkMap.size() > 0) {
                if (chkMap.containsKey('agency')) {
                    // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '第一经销商没有有效的医疗器械经营许可证。'));
                    errorMsgList.add('第一经销商没有有效的医疗器械经营许可证。');
                }
                for (String proId : prodMap.keySet()) {
                    if (chkMap.containsKey(proId)) {
                        if (chkMap.get(proId) == '1') {
                            // ApexPages.addmessage(
                            //     new ApexPages.message(ApexPages.severity.Error, '产品 ' + prodMap.get(proId) + ' 没有有效的注册证。')
                            // );
                            errorMsgList.add('产品 ' + prodMap.get(proId) + ' 没有有效的注册证。');
                        } else if (chkMap.get(proId) == '2') {
                            // ApexPages.addmessage(
                            //     new ApexPages.message(ApexPages.severity.Error, '产品 ' + prodMap.get(proId) + ' 超过经销商经营范围。')
                            // );
                            errorMsgList.add('产品 ' + prodMap.get(proId) + ' 超过经销商经营范围。');
                        }
                    }
                }
                results.result = 'Fail';
                results.errorMsg = '';
                results.errorMsgList = errorMsgList;
                results.warningMsgList = warningMsgList;
                return results;
            }
            update p;
            Approval.ProcessSubmitRequest psr = new Approval.ProcessSubmitRequest();
            psr.setObjectId(ESetId);
            Approval.ProcessResult submitResult = Approval.process(psr);
            results.result = 'Success';
            results.url = '/lexconsumableordermanage';
        } catch (Exception e) {
            Database.rollback(sp);
            results.result = 'Fail';
            results.errorMsg = e.getLineNumber() + '---' + e.getMessage();
        }
        return results;
    }
 
    // 驳回订单copy
    @AuraEnabled
    public static Results ordrCopy(
        String contractNameStr,
        String cocStr,
        String agencyProTypeStr,
        String accountidStr,
        String consumableorderdetailsRecordsviewStr,
        String contactDealerStr,
        String methodTypeStr,
        String hospitalIdStr,
        String contractIdStr,
        String agencyProType1Str,
        Boolean OSHFLGStr
    ) {
        ESetId = '';
        return save(
            contractNameStr,
            cocStr,
            agencyProTypeStr,
            accountidStr,
            consumableorderdetailsRecordsviewStr,
            contactDealerStr,
            methodTypeStr,
            ESetId,
            hospitalIdStr,
            contractIdStr,
            agencyProType1Str,
            OSHFLGStr
        );
    }
 
    //保存按钮
    @AuraEnabled
    public static Results save(
        String contractNameStr,
        String cocStr,
        String agencyProTypeStr,
        String accountidStr,
        String consumableorderdetailsRecordsviewStr,
        String contactDealerStr,
        String methodTypeStr,
        String eSetIdStr,
        String hospitalIdStr,
        String contractIdStr,
        String agencyProType1Str,
        Boolean OSHFLGStr
    ) {
        Results results = new Results();
        errorMsgList = new List<String>();
        warningMsgList = new List<String>();
        contractName = contractNameStr;
        agencyProType = agencyProTypeStr;
        accountid = accountidStr;
        methodType = methodTypeStr;
        ESetId = eSetIdStr;
        hospitalId = hospitalIdStr;
        contractId = contractIdStr;
        agencyProType1 = agencyProType1Str;
        OSHFLG = OSHFLGStr;
        coc = (Consumable_order__c) JSON.deserialize(cocStr, Consumable_order__c.class);
        contactDealer = (List<String>) JSON.deserialize(contactDealerStr, List<String>.class);
        System.debug('consumableorderdetailsRecordsviewStr:' + consumableorderdetailsRecordsviewStr);
        consumableorderdetailsRecordsview = (List<ConsumableorderdetailsInfo>) JSON.deserialize(
            consumableorderdetailsRecordsviewStr,
            List<ConsumableorderdetailsInfo>.class
        );
        if (coc.Offers_Price__c != null) {
            String offerStr = String.valueOf(coc.Offers_Price__c);
            bargainPrice = Decimal.valueOf(offerStr.replace(',', ''));
        }
        Savepoint sp = Database.setSavepoint();
        try {
            if (String.isEmpty(contractName)) {
                // coc.Order_effective_contact__c.addError('请选择合同');
                results.result = 'Fail';
                results.errorMsg = '请选择合同';
                return results;
            }
            List<Account> contract = [
                SELECT Id, Name, Contract_Department_Class__c, Contract_Quote_Decide_Flag__c
                FROM account
                WHERE
                    Name = :contractName
                    AND Id = :contractId //lt 20230517 安徽两票制 add
                    AND Contract_Decide_Start_Date__c <= :Date.Today()
                    AND Contract_Decide_End_Date__c >= :Date.Today()
                    AND Contact_Type__c LIKE :agencyProType1 //lt 20230517 安徽两票制 add 1
                    AND Agent_Ref__c = :accountid
                    AND OSH_Dealer__c = :OSHFLG //lt 20230517 安徽两票制 add
            ];
            if (contract.size() <= 0) {
                // coc.Order_effective_contact__c.addError('不存在的合同,请重新确认。');
                results.result = 'Fail';
                results.errorMsg = '不存在的合同,请重新确认。';
                return results;
            } else {
                if (String.isEmpty(contract[0].Contract_Quote_Decide_Flag__c)) {
                    // coc.Order_effective_contact__c.addError('合同无效,请重新确认。');
                    results.result = 'Fail';
                    results.errorMsg = '合同无效,请重新确认。';
                    return results;
                }
            }
            Integer FLG = 0;
            Integer Count = 0;
            //add by rentx 2020-11-25
            List<String> tpids = new List<String>();
            //add by rentx 2020-11-25
            for (ConsumableorderdetailsInfo CheckCount : consumableorderdetailsRecordsview) {
                FLG = FLG + 1;
                if (CheckCount.check == false) {
                    Count = Count + 1;
                }
                if (CheckCount.check == true) {
                    //add by rentx 2020-11-25
                    tpids.add(CheckCount.Prod.Id);
                    //add by rentx 2020-11-25
                    if (CheckCount.esd.Consumable_Count__c == null || CheckCount.esd.Consumable_Count__c == 0) {
                        // CheckCount.esd.Consumable_Count__c.addError('请输入采购数量');
                        results.result = 'Fail';
                        results.errorMsg = '请输入采购数量';
                        return results;
                    }
                    if (
                        CheckCount.orderGoods_Limit > 0 &&
                        math.mod(Integer.valueOf(CheckCount.esd.Consumable_Count__c), Integer.valueOf(CheckCount.orderGoods_Limit)) > 0
                    ) {
                        // CheckCount.esd.Consumable_Count__c.addError('请输入促销数量的倍数');
                        results.result = 'Fail';
                        results.errorMsg = '请输入促销数量的倍数';
                        return results;
                    }
                }
            }
            if (Count == FLG) {
                results.result = 'Fail';
                results.errorMsg = '请选择所需消耗品';
                return results;
            }
            //=======================================医院特价,有金额的话取金额
            Map<String, Decimal> dealerHospitalmMap = new Map<String, Decimal>();
            List<hospitalprice__c> hplist = [
                SELECT Id, hospital__c, mPrice__c, pPrice__c, product__c, account__c
                FROM hospitalprice__c
                WHERE product__c IN :tpids AND mPrice__c != NULL AND account__c = :accountid
            ];
            for (hospitalprice__c dealerProduct : hplist) {
                if (dealerProduct.mPrice__c != null) {
                    dealerHospitalmMap.put('' + dealerProduct.hospital__c + dealerProduct.product__c, dealerProduct.mPrice__c);
                }
            }
            //促销订货 根据经销商产品中的数据计算金额
            //=======================================产品特殊折扣
            Map<String, Decimal> dealerPDiscountMap = new Map<String, Decimal>();
            Map<String, Decimal> dealerMPDiscountMap = new Map<String, Decimal>();
            //1.获取有开始结束日的产品
            Date dateToday = Date.today();
            List<Dealer_Product__c> haveDateList = [
                SELECT
                    Id,
                    Name,
                    Dealer_Product2__c,
                    Special_Campaign_Price__c,
                    Campaign_StartDate__c,
                    Campaign_EndDate__c,
                    Dealer_Contact__c,
                    OrderGoods_Limit__c,
                    Special_Discount__c
                FROM Dealer_Product__c
                WHERE
                    Dealer_Contact__c IN :contactDealer
                    AND Campaign_StartDate__c <= :dateToday
                    AND Campaign_EndDate__c >= :dateToday
                    AND (Special_Discount__c != NULL
                    OR Special_Campaign_Price__c != NULL)
            ];
            //2.获取没有开始结束日的产品
            List<Dealer_Product__c> DealerProductList = [
                SELECT
                    Id,
                    Name,
                    Dealer_Product2__c,
                    Special_Campaign_Price__c,
                    Campaign_StartDate__c,
                    Campaign_EndDate__c,
                    Dealer_Contact__c,
                    Special_Discount__c,
                    OrderGoods_Limit__c
                FROM Dealer_Product__c
                WHERE Dealer_Contact__c IN :contactDealer AND (Special_Discount__c != NULL OR Special_Campaign_Price__c != NULL)
            ];
            for (Dealer_Product__c dealerProduct : DealerProductList) {
                //如果促销价格为null 则设置特殊折扣(百分比)到集合
                if (dealerProduct.Special_Campaign_Price__c == null) {
                    dealerPDiscountMap.put(
                        '' + dealerProduct.Dealer_Contact__c + dealerProduct.Dealer_Product2__c,
                        dealerProduct.Special_Discount__c
                    );
                } else {
                    dealerMPDiscountMap.put(
                        '' + dealerProduct.Dealer_Contact__c + dealerProduct.Dealer_Product2__c,
                        dealerProduct.Special_Campaign_Price__c
                    );
                }
            }
            //这样做是为了计算促销价格时 优先计算促销开始结束日不为空的产品
            //如果该集合有值 则说明需要根据当前的金额或者折扣来计算
            if (haveDateList != null && haveDateList.size() > 0) {
                for (Dealer_Product__c dealerProduct : haveDateList) {
                    if (dealerProduct.Special_Campaign_Price__c == null) {
                        dealerPDiscountMap.put(
                            '' + dealerProduct.Dealer_Contact__c + dealerProduct.Dealer_Product2__c,
                            dealerProduct.Special_Discount__c
                        );
                        dealerMPDiscountMap.remove('' + dealerProduct.Dealer_Contact__c + dealerProduct.Dealer_Product2__c);
                    } else {
                        dealerMPDiscountMap.put(
                            '' + dealerProduct.Dealer_Contact__c + dealerProduct.Dealer_Product2__c,
                            dealerProduct.Special_Campaign_Price__c
                        );
                        dealerPDiscountMap.remove('' + dealerProduct.Dealer_Contact__c + dealerProduct.Dealer_Product2__c);
                    }
                }
            }
            //=======================================经销商合同折扣
            List<Account> at = [
                SELECT id, Name, State_Master__c, State_Master__r.Name, Sales_Section__c, Dealer_discount__c
                FROM Account
                WHERE
                    Name = :contractName
                    AND Id = :contractId //lt 20230517 安徽两票制 add
                    AND Contact_Type__c LIKE :agencyProType1 //lt 20230517 安徽两票制 add  1
                    AND Contact_Type__c LIKE :agencyProType
                    AND Contract_Decide_Start_Date__c <= :Date.Today()
                    AND Contract_Decide_End_Date__c >= :Date.Today()
                    AND Contract_Decide_End_Date__c >= :Date.Today()
                    AND OSH_Dealer__c = :OSHFLG //lt 20230517 安徽两票制 add
            ];
            if (at.size() > 0 && at[0].Dealer_discount__c != null) {
                disCount = at[0].Dealer_discount__c;
            } else {
                disCount = 100;
            }
            Consumable_order__c P = new Consumable_order__c();
            List<Consumable_Orderdetails__c> Ins = new List<Consumable_Orderdetails__c>();
            //新建订单时
            if (String.isBlank(ESetId)) {
                Integer i = 1;
                Integer Roll = 0;
                p.Name = '*';
                p.Order_status__c = '草案中';
                p.Dealer_Info__c = accountid;
                p.Order_ProType__c = agencyProType;
                p.Offers_Price__c = coc.Offers_Price__c;
                p.Order_date__c = coc.Order_date__c;
                p.Order_effective_contact__c = contract[0].Id;
                p.Order_Reason__c = coc.Order_Reason__c;
                p.RecordTypeid = System.Label.RT_ConOrder_Order;
                p.Overrule_order__c = coc.Id;
                if (String.isNotBlank(methodType)) {
                    p.orderPattern__c = methodType;
                }
                insert p;
<<<<<<< HEAD
                List<Consumable_order__c> Consumable_order = [
                    SELECT Name, orderPattern__c
                    FROM Consumable_order__c
                    WHERE id = :p.id
                ];
=======
                List<Consumable_order__c> Consumable_order = [SELECT Name, orderPattern__c FROM Consumable_order__c WHERE id = :p.id];
>>>>>>> LEXCommunityLiJun
                for (ConsumableorderdetailsInfo ass : consumableorderdetailsRecordsview) {
                    Roll = Roll + 1;
                    if (ass.check == true) {
                        if (ass.esd.Consumable_Count__c == null || ass.esd.Consumable_Count__c == 0) {
                            // ass.esd.Consumable_Count__c.addError('请输入采购数量');
                            results.result = 'Fail';
                            results.errorMsg = '请输入采购数量';
                            return results;
                        } else {
                            Consumable_Orderdetails__c InsAfterDel = new Consumable_Orderdetails__c();
                            String str = string.valueOf(i);
                            if (str.length() == 1) {
                                str = '0' + str;
                            }
                            InsAfterDel.Name = Consumable_order[0].Name + '-' + str;
                            InsAfterDel.Consumable_Count__c = ass.esd.Consumable_Count__c;
                            InsAfterDel.Consumable_order__c = p.id;
                            InsAfterDel.Consumable_Product__c = ass.Prod.id;
                            InsAfterDel.Box_Piece__c = '盒';
                            //协议订货
                            if (methodType.equals('agreementorder')) {
                                Consumable_order[0].orderPattern__c = 'agreementorder';
 
                                InsAfterDel.Intra_Trade_List_RMB__c = ass.Prod.Intra_Trade_List_RMB__c * disCount / 100;
                                //=====================================================================================update by rentx 2020-11-25
                            } else if (methodType.equals('promotionorder')) {
                                Consumable_order[0].orderPattern__c = 'promotionorder';
                                //促销订货
                                //如果促销价格不为null 则直接使用促销价格来计算金额
                                if (dealerMPDiscountMap.containsKey('' + contract[0].Id + ass.Prod.Id)) {
                                    InsAfterDel.Intra_Trade_List_RMB__c = dealerMPDiscountMap.get('' + contract[0].Id + ass.Prod.Id);
                                    system.debug('cai 0' + InsAfterDel.Intra_Trade_List_RMB__c);
                                } else if (dealerPDiscountMap.containsKey('' + contract[0].Id + ass.Prod.Id)) {
                                    InsAfterDel.Intra_Trade_List_RMB__c =
                                        ass.Prod.Intra_Trade_List_RMB__c *
                                        dealerPDiscountMap.get('' + contract[0].Id + ass.Prod.Id) /
                                        100;
                                    system.debug('cai 00' + InsAfterDel.Intra_Trade_List_RMB__c);
                                }
                                //=====================================================================================update by rentx 2020-11-25
                            } else if (methodType.equals('hospitalorder')) {
                                //医院特价
                                Consumable_order[0].Order_ForHospital__c = hospitalId;
                                Consumable_order[0].orderPattern__c = 'hospitalorder';
                                if (
                                    dealerHospitalmMap.containsKey(hospitalId + ass.Prod.Id) &&
                                    dealerHospitalmMap.get(hospitalId + ass.Prod.Id) != null
                                ) {
                                    //直接根据促销金额计算
                                    InsAfterDel.Intra_Trade_List_RMB__c = dealerHospitalmMap.get('' + hospitalId + ass.Prod.Id);
                                }
                            } else if (DealerProductMap.containsKey(ass.Prod.Id)) {
                                InsAfterDel.Intra_Trade_List_RMB__c = DealerProductMap.get(ass.Prod.Id).Special_Campaign_Price__c;
                                system.debug('cai 2' + InsAfterDel.Intra_Trade_List_RMB__c);
                                InsAfterDel.Purchase_Unitprtprice_From__c = '促销';
                                InsAfterDel.Special_Campaign_Price__c = DealerProductMap.get(ass.Prod.Id).Special_Campaign_Price__c;
                            }
                            InsAfterDel.RecordTypeId = System.Label.RT_ConOrderDetail1_Order;
                            i++;
                            Ins.add(InsAfterDel);
                        }
                    }
                }
                ESetId = p.id;
                if (Consumable_order.size() > 0) {
                    update Consumable_order;
                }
            }
            //修改之后 保存订单
            if (Ins.size() > 0) {
                insert Ins;
            } else {
                //修改,获取消耗品订单
                List<Consumable_order__c> cocinfo = new List<Consumable_order__c>();
                cocinfo = [
                    SELECT Id, Name, Order_status__c, Dealer_Info__c, Deliver_date__c, Order_Reason__c, Offers_Price__c
                    FROM Consumable_order__c
                    WHERE Id = :ESetId
                ];
                if (cocinfo.size() > 0) {
                    p = cocinfo[0];
                }
                p.Name = coc.Name;
                p.Dealer_Info__c = accountid;
                p.Order_ProType__c = agencyProType;
                p.Order_date__c = coc.Order_date__c;
                p.Order_effective_contact__c = contract[0].Id;
                p.Order_Reason__c = coc.Order_Reason__c;
                if (bargainPrice != null) {
                    p.Offers_Price__c = bargainPrice;
                }
                update p;
<<<<<<< HEAD
                List<Consumable_order__c> Consumable_order = [
                    SELECT Name, orderPattern__c
                    FROM Consumable_order__c
                    WHERE id = :p.id
                ];
=======
                List<Consumable_order__c> Consumable_order = [SELECT Name, orderPattern__c FROM Consumable_order__c WHERE id = :p.id];
>>>>>>> LEXCommunityLiJun
                List<Consumable_Orderdetails__c> qs = new List<Consumable_Orderdetails__c>();
                qs = [
                    SELECT Id
                    FROM Consumable_Orderdetails__c
                    WHERE Consumable_order__c = :ESetId AND Consumable_order__r.Dealer_Info__c = :accountid
                ];
                if (qs.size() > 0) {
                    delete qs;
                }
                Integer i = 1;
                for (ConsumableorderdetailsInfo ass : consumableorderdetailsRecordsview) {
                    if (ass.check == true) {
                        Consumable_Orderdetails__c InsAfterDel = new Consumable_Orderdetails__c();
                        if (ass.esd.Consumable_Count__c == null || ass.esd.Consumable_Count__c == 0) {
                            // ass.esd.Consumable_Count__c.addError('请输入采购数量');
                            results.result = 'Fail';
                            results.errorMsg = '请输入采购数量';
                            return results;
                        } else {
                            String str = string.valueOf(i);
                            if (str.length() == 1) {
                                str = '0' + str;
                            }
                            InsAfterDel.Name = Consumable_order[0].Name + '-' + str;
                            InsAfterDel.Consumable_Count__c = ass.esd.Consumable_Count__c;
                            InsAfterDel.Consumable_order__c = ESetId;
                            InsAfterDel.Consumable_Product__c = ass.Prod.id;
                            InsAfterDel.Box_Piece__c = '盒';
                            //协议订货
                            if (methodType.equals('agreementorder')) {
                                Consumable_order[0].orderPattern__c = 'agreementorder';
                                InsAfterDel.Intra_Trade_List_RMB__c = ass.Prod.Intra_Trade_List_RMB__c * disCount / 100;
                            } else if (methodType.equals('promotionorder')) {
                                Consumable_order[0].orderPattern__c = 'promotionorder';
                                //促销订货
                                if (dealerMPDiscountMap.containsKey('' + contract[0].Id + ass.Prod.Id)) {
                                    InsAfterDel.Intra_Trade_List_RMB__c = dealerMPDiscountMap.get('' + contract[0].Id + ass.Prod.Id);
                                } else if (dealerPDiscountMap.containsKey('' + contract[0].Id + ass.Prod.Id)) {
                                    InsAfterDel.Intra_Trade_List_RMB__c =
                                        ass.Prod.Intra_Trade_List_RMB__c *
                                        dealerPDiscountMap.get('' + contract[0].Id + ass.Prod.Id) /
                                        100;
                                }
                            } else if (methodType.equals('hospitalorder')) {
                                Consumable_order[0].orderPattern__c = 'hospitalorder';
                                //医院特价
                                Consumable_order[0].Order_ForHospital__c = hospitalId;
                                if (
                                    dealerHospitalmMap.containsKey(hospitalId + ass.Prod.Id) &&
                                    dealerHospitalmMap.get(hospitalId + ass.Prod.Id) != null
                                ) {
                                    //直接根据促销金额计算
                                    InsAfterDel.Intra_Trade_List_RMB__c = dealerHospitalmMap.get('' + hospitalId + ass.Prod.Id);
                                }
                            } else if (DealerProductMap.containsKey(ass.Prod.Id)) {
                                InsAfterDel.Intra_Trade_List_RMB__c = DealerProductMap.get(ass.Prod.Id).Special_Campaign_Price__c;
                                InsAfterDel.Purchase_Unitprtprice_From__c = '促销';
                                InsAfterDel.Special_Campaign_Price__c = DealerProductMap.get(ass.Prod.Id).Special_Campaign_Price__c;
                            }
                            // ==================================================之前的促销订货的逻辑
                            InsAfterDel.RecordTypeId = System.Label.RT_ConOrderDetail1_Order;
                            i++;
                            Ins.add(InsAfterDel);
                        }
                    }
                }
                if (Ins.size() > 0) {
                    insert Ins;
                }
            }
            results.result = 'Success';
            results.eSetId = ESetId;
        } catch (Exception e) {
            Database.rollback(sp);
            results.result = 'Fail';
            results.errorMsg = e.getLineNumber() + '---' + e.getMessage();
        }
        return results;
    }
 
    //删除附件
    @AuraEnabled
    public static Results deleteAtt(String contentVersionId, String cocId) {
        Results results = new Results();
        try {
<<<<<<< HEAD
            List<ContentVersion> cvInfo = [
                SELECT Id
                FROM ContentVersion
                WHERE FirstPublishLocationId = :cocId
            ];
            ContentVersion conVersion = [
                SELECT ContentDocumentId
                FROM ContentVersion
                WHERE Id = :contentVersionId
            ];
            String contentDocumentId = conVersion.ContentDocumentId;
            ContentDocument conDocument = [
                SELECT Id
                FROM ContentDocument
                WHERE Id = :contentDocumentId
            ];
            delete conDocument;
            if (cvInfo.size() <= 1) {
                Consumable_order__c c = [
                    SELECT Id
                    FROM Consumable_order__c
                    WHERE Id = :cocId
                ];
=======
            List<ContentVersion> cvInfo = [SELECT Id FROM ContentVersion WHERE FirstPublishLocationId = :cocId];
            ContentVersion conVersion = [SELECT ContentDocumentId FROM ContentVersion WHERE Id = :contentVersionId];
            String contentDocumentId = conVersion.ContentDocumentId;
            ContentDocument conDocument = [SELECT Id FROM ContentDocument WHERE Id = :contentDocumentId];
            delete conDocument;
            if (cvInfo.size() <= 1) {
                Consumable_order__c c = [SELECT Id FROM Consumable_order__c WHERE Id = :cocId];
>>>>>>> LEXCommunityLiJun
                c.Consumable_pdf_insert_day__c = null;
                update c;
            }
            results.result = 'Success';
        } catch (Exception e) {
            results.result = 'Fail';
            results.errorMsg = e.getLineNumber() + '---' + e.getMessage();
        }
        return results;
    }
 
    public static void getConsumableShowTableFieldValue() {
        for (ConsumableorderdetailsInfo con : consumableorderdetailsRecordsview) {
            if (con.Prod != null) {
                con.recordId = con.Prod.Id;
                if (!con.oldCheck) {
                    con.prodName = con.Prod.Name__c;
                    // System.debug('ProdName:'+con.Prod.Id+'---'+con.Prod.Name__c);
                }
                con.prodSFDAStatus = con.Prod.SFDA_Status__c;
                con.prodCategory3 = con.Prod.Category3__c;
                con.prodCategory4 = con.Prod.Category4__c;
                con.prodCategory5 = con.Prod.Category5__c;
                con.prodIntraTradeList = con.Prod.Intra_Trade_List_RMB__c;
            }
            if (con.esd != null) {
                // if(con.oldCheck){
                // con.prodName = con.esd.Consumable_Product__r.Name__c;
                // }
                con.consumableCount = con.esd.Consumable_count__c;
            }
        }
    }
 
    public class ConsumableorderdetailsInfo implements Comparable {
        @AuraEnabled
        public Boolean check { get; set; }
        @AuraEnabled
        public Boolean oldCheck { get; set; }
        @AuraEnabled
        public Consumable_Orderdetails__c esd { get; set; }
        @AuraEnabled
        public Product2__c Prod { get; set; }
        @AuraEnabled
        public Integer packing_list { get; set; }
        @AuraEnabled
        public Date expiration_Date { get; set; }
        @AuraEnabled
        public String approbation_No { get; set; }
        @AuraEnabled
        public Decimal allnumber { get; set; }
        @AuraEnabled
        public Decimal allnumber_piece { get; set; }
        @AuraEnabled
        public Decimal oldConsumableCount { get; set; }
        @AuraEnabled
        public Boolean canSelect { get; set; }
        @AuraEnabled
        public ContentVersion Concc { get; set; }
        @AuraEnabled
        public Boolean sortBy { get; set; }
        @AuraEnabled
        public Decimal upperlimit { get; set; }
        @AuraEnabled
        public Decimal lowerlimit { get; set; }
        @AuraEnabled
        public Decimal SpecialCampaignPrice { get; set; }
        @AuraEnabled
        public Decimal orderGoods_Limit { get; set; }
        @AuraEnabled
        public Date Campaign_EndDate { get; set; }
        @AuraEnabled
        public String recordId { get; set; }
        @AuraEnabled
        public String prodName { get; set; }
        @AuraEnabled
        public String prodSFDAStatus { get; set; }
        @AuraEnabled
        public String prodCategory3 { get; set; }
        @AuraEnabled
        public String prodCategory4 { get; set; }
        @AuraEnabled
        public String prodCategory5 { get; set; }
        @AuraEnabled
        public Decimal prodIntraTradeList { get; set; }
        @AuraEnabled
        public Decimal consumableCount { get; set; }
 
        // 已存产品明细
        public ConsumableorderdetailsInfo(Consumable_Orderdetails__c e) {
            check = true;
            oldCheck = true;
            esd = e;
            Prod = e.Consumable_Product__r;
            oldConsumableCount = e.Consumable_Count__c;
            canSelect = true;
            allnumber = 0;
            allnumber_piece = 0;
        }
 
        public ConsumableorderdetailsInfo(Product2__c e) {
            check = false;
            oldCheck = false;
            esd = new Consumable_Orderdetails__c();
            Prod = e;
            oldConsumableCount = null;
            canSelect = true;
            allnumber = 0;
            allnumber_piece = 0;
        }
        //附件
        public ConsumableorderdetailsInfo(ContentVersion e) {
            Concc = e;
        }
        // 排序Consumable_order__c
        public Integer compareTo(Object compareTo) {
            ConsumableorderdetailsInfo compareToesd = (ConsumableorderdetailsInfo) compareTo;
            Integer returnValue = 0;
            if (check == true) {
                if (sortBy == false) {
                    if (allnumber > compareToesd.allnumber) {
                        returnValue = -1;
                    } else if (allnumber < compareToesd.allnumber) {
                        returnValue = 1;
                    }
                    return returnValue;
                } else {
                    if (allnumber > compareToesd.allnumber) {
                        returnValue = 1;
                    } else if (allnumber < compareToesd.allnumber) {
                        returnValue = -1;
                    }
                    return returnValue;
                }
            } else {
                if (sortBy == false) {
                    if (allnumber > compareToesd.allnumber) {
                        returnValue = -1;
                    } else if (allnumber < compareToesd.allnumber) {
                        returnValue = 1;
                    }
                    return returnValue;
                } else {
                    if (allnumber > compareToesd.allnumber) {
                        returnValue = 1;
                    } else if (allnumber < compareToesd.allnumber) {
                        returnValue = -1;
                    }
                    return returnValue;
                }
            }
        }
    }
 
    public class Results {
        @AuraEnabled
        public String result;
        @AuraEnabled
        public String errorMsg;
        @AuraEnabled
        public String eSetId;
        @AuraEnabled
        public String agencyProType;
        @AuraEnabled
        public String userWorkLocation;
        @AuraEnabled
        public String accountName;
        @AuraEnabled
        public String accountid;
        @AuraEnabled
        public String hospitalId;
        @AuraEnabled
        public String contractId;
        @AuraEnabled
        public String category_Goods;
        @AuraEnabled
        public Consumable_order__c coc;
        @AuraEnabled
        public Boolean edoffersPrice;
        @AuraEnabled
        public Boolean editDelCommitBtnDisabled;
        @AuraEnabled
        public Boolean editAble;
        @AuraEnabled
        public String hospitalName;
        @AuraEnabled
        public String contractName;
        @AuraEnabled
        public List<CusOption> category3Option;
        @AuraEnabled
        public List<CusOption> category4Option;
        @AuraEnabled
        public List<CusOption> category5Option;
        @AuraEnabled
        public List<ConsumableorderdetailsInfo> consumableorderdetailsRecordsview;
        @AuraEnabled
        public List<ConsumableorderdetailsInfo> attachmentRecoeds;
        @AuraEnabled
        public Boolean cansee;
        @AuraEnabled
        public List<String> errorMsgList;
        @AuraEnabled
        public List<String> warningMsgList;
        @AuraEnabled
        public Boolean hasWarning;
        @AuraEnabled
        public Boolean hasError;
        @AuraEnabled
        public Boolean specialCampaign;
        @AuraEnabled
        public List<String> dealerProductId;
        @AuraEnabled
        public List<String> contactDealer;
        @AuraEnabled
        public String url;
        @AuraEnabled
        public String methodType;
        @AuraEnabled
        public List<String> proLimitAndDate;
        @AuraEnabled
        public Boolean isNoteStay;
        @AuraEnabled
        public Boolean OSHFLG;
        @AuraEnabled
        public String agencyProType1;
    }
 
    public class CusOption {
        CusOption(String label, String value) {
            this.label = label;
            this.value = value;
        }
 
        @AuraEnabled
        public String label;
        @AuraEnabled
        public String value;
    }
<<<<<<< HEAD
}
=======
}
>>>>>>> LEXCommunityLiJun