付煜
2022-03-25 8ea597d3c67631cd702415d43bc3d2961f6bc94d
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
// FIXME 見積もり商品の Asset_Model_No__c ですが、数式になっています。トランザクションデータとして、項目を持つべきかと思います。by katsu 20130216
// 商談商品のId__c を PricebookEntry.Product2Idに変更すべき
// 見積もり可否 ですが、保存時みていますが、Sales_Possibilityを見ないですか?いいえ、js側で見ています
public class NewQuoteIraiController {
    public Integer quoteEntryMaxLine {get; private set;}
    public Id quoId {get;set;}
    public String oppid;
    public Boolean productStatusUpdated {get;set;}               // 状態更新、{!$Label.Status_Update} を押下したかどうか
    public Boolean changedAfterPrint {get;set;}                  // true の場合、画面に confirm メッセージが表示します。quoIdを新しいinsert。判定はjsにて実施
 
    //lastbuy  2022/3/10 fy start
    public Boolean filg { get; set; }
    public Integer flglastbuy { get; set; }
    public String errorProductmodel { get; set; }
    //lastbuy  2022/3/10 fy end
 
    public String excel_text {get;set;}
    public Integer select_index {get;set;}                       // excelImport専用ですが、jsにて制御することになるので、TODO katsu 削除予定
    public String Product_text {get;set;}
    public String setProduct_text {get;set;}
 
    public List<QELine> activities {get;set;}
    private List<QELine> activitiesbk;
    public List<QELine> tmpactivities {get;set;}
 
    public QELine active_activity {get;set;}
    //画面制御判定用
    public Boolean displayCost {get;set;}
    //ボタン制御用
    public Boolean Save_button {get;set;}
    public Boolean pdf_button {get;set;}
    //見積
    public QuoteIrai__c quo {get;set;}
    public Decimal total_ListPrice {get;set;}
 
    public boolean errorflg {get;set;}
    public String errorMessage {get;set;}
    public String baseUrl {get;set;}
    public boolean Messageflg {get;set;}
    public String Message {get;set;}
    
    public User loginUser {get;set;}
    
    private Map<Id, Product2> prd2LatestValMap;
 
    // CHAN-BJQ4VZ 精琢技术 2019/12/11 Start
    public QuoteBean qb { get; set; }
    // CHAN-BJQ4VZ 精琢技术 2019/12/11 End
 
    // 经销商询价报价委托 2020-02-28 update by vivek start
    public Map<Id,Id> userProfileId;
    // 经销商询价报价委托 2020-02-28 update by vivek end
    
    public NewQuoteIraiController() {
        quoteEntryMaxLine = Integer.valueOf(System.Label.QuoteEntryMaxLine);
        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
        changedAfterPrint = false;
        productStatusUpdated = false;
    }
 
    public NewQuoteIraiController(ApexPages.StandardController controller) {
        this();
    }
    
    public PageReference checkIraiUser() {
        system.debug('============' + quo.IraiUser__c + '============');
        return null;
    }
 
    public PageReference init() {
        system.debug('============start init==============');
        errorflg = false;
        pdf_button = true;
        //loginUser
        loginUser = [select Id, ProfileId, State_Hospital__c from User where Id = :UserInfo.getUserId()];
        if (loginUser.ProfileId == System.Label.ProfileId_SystemAdmin) {
            pdf_button = false;
        }
        //Quote
        quo = new QuoteIrai__c();
        // CHAN-BJQ4VZ 精琢技术 2019/12/11 Start
        qb = new QuoteBean();
        // CHAN-BJQ4VZ 精琢技术 2019/12/11 End
 
        //quoid
        if (quoId==null){
            quoId = System.currentPageReference().getParameters().get('copyid');
            if (quoId==Null){
                quoId = System.currentPageReference().getParameters().get('id');
            }
        }
        
        // 潜在客户id
        String leadid = System.currentPageReference().getParameters().get('leadid');
        // 经销商询价报价委托 2020-02-28 update by vivek start
        // 经销商询价
        String agencyoppid = System.currentPageReference().getParameters().get('agencyoppid');
        // 经销商询价报价委托 2020-02-28 update by vivek start
 
        // 招投标报价委托 2021-06-21 update by gzw start
        // 招投标
        String tenderid = System.currentPageReference().getParameters().get('tenderid');
        // 招投标报价委托 2021-06-21 update by gzw start
 
        // 询价id
        oppid = System.currentPageReference().getParameters().get('oppid');
        QuoteIrai__c quoteiraiobj = new QuoteIrai__c();
        if(oppid==null&&tenderid==null&&quoId!=null&&leadid==null&&agencyoppid==null){
            quoteiraiobj = [select id,Note__c from QuoteIrai__c where id=:quoId];
            if(quoteiraiobj.Note__c!=null){
                String[] quosub=quoteiraiobj.Note__c.split('/');
                oppid=quosub[quosub.size()-1];
            }
        }
        system.debug('oppid:++++'+oppid);
        // 报价id
        String oppquoid = System.currentPageReference().getParameters().get('oppquoid');
        //将报价委托的币种与外贸币种一致 防止后续外贸有需要用USD判断显示的地方 精琢技术 wql 2021/01/06 start
        List<Opportunity> oppList = [Select id,CurrencyIsoCode from Opportunity where id =:oppid];
 
        //Quote
        Integer i;
        if (quoId==null){
            // System.debug('进到这里了---');
            // if(oppList.size()>0){
            //     quo.CurrencyIsoCode = oppList[0].CurrencyIsoCode;
            //     system.debug('币种1:'+quo.CurrencyIsoCode);
            // }
            //注释原逻辑 wql
            quo.CurrencyIsoCode = 'CNY';
            //将报价委托的币种与外贸币种一致 防止后续外贸有需要用USD判断显示的地方 精琢技术 wql 2021/01/06 end
            if (String.isNotBlank(leadid)) {
                quo.Note__c = Lead.sObjectType.getDescribe().getLabel() + ':' + baseUrl + '/' + leadid;
            }
            // 经销商询价报价委托 2020-02-28 update by vivek start
            if (String.isNotBlank(agencyoppid)) {
                quo.Note__c = Agency_Opportunity__c.sObjectType.getDescribe().getLabel() + ':' + baseUrl + '/' + agencyoppid;
            }
            // 经销商询价报价委托 2020-02-28 update by vivek end
            // 招投标报价委托 2021-06-21 update by gzw start
            if (String.isNotBlank(tenderid)) {
                quo.Note__c = Tender_information__c.sObjectType.getDescribe().getLabel() + ':' + baseUrl + '/' + tenderid;
            }
            // 招投标报价委托 2021-06-21 update by gzw end
            if (String.isNotBlank(oppid)) {
                quo.Note__c = Opportunity.sObjectType.getDescribe().getLabel() + ':' + baseUrl + '/' + oppid;
            }
            //新規リストコントローラの取得
            if (activities==null){
                activities = new List<QELine>();
                activitiesbk = new List<QELine>();
                for (i=0;i<quoteEntryMaxLine;i++){
                    QELine active_activity = new QELine(i);
                    activities.add(active_activity);
                }
            }
            
            if (String.isNotBlank(oppid)) {
                //将报价委托的币种与外贸币种一致 防止后续外贸有需要用USD判断显示的地方 精琢技术 wql 2021/01/06 start
                // 询价信息
                List<Opportunity> oppl = [select Id,AccountId,Account.Name,Name,CurrencyIsoCode from Opportunity where Id = :oppid];
                if (oppl.size() > 0) {
                    quo.IraiSubject__c = oppl[0].Account.Name;
                    quo.Account__c = oppl[0].AccountId;
                    quo.IraiName__c = oppl[0].Name ;
                    //更新币种相同 wql
                    //quo.CurrencyIsoCode = oppl[0].CurrencyIsoCode;
 
                }
                //将报价委托的币种与外贸币种一致 防止后续外贸有需要用USD判断显示的地方 精琢技术 wql 2021/01/06 end
                List<Quote> ql =  [select Id,OpportunityId From Quote Where OpportunityId =:oppId];
                // 不经存在报价
                if (ql.size() <= 0){
                    // CHAN-BHNBX6 2019/11/20 START
                    List<OpportunityLineItem> olis = [Select Id,Quantity,PricebookEntry.Product2Id,CurrencyIsoCode,GuaranteePeriod__c From OpportunityLineItem Where OpportunityId =:oppId Order by Item_Order__c, Id];
                    // CHAN-BHNBX6 2019/11/20 END
                    List<String> productids = new List<String>();
                    for (OpportunityLineItem oli : olis) {
                        productids.add(oli.PricebookEntry.Product2Id);
                    }
                    // 商品最新信息取得
                    Map<Id, Product2> items = new Map<Id, Product2>();
                    // CHAN-BHNBX6 2019/11/20 START
                    //2021/1/5 liying start NoDiscount_Foreign__c
                    List<Product2> products = [select Id,Name,ProductCode,
                            Foreign_Trade_Cost_US__c,Foreign_Trade_List_US__c,Intra_Trade_Cost_RMB__c,Intra_Trade_List_RMB__c,
                            Asset_Model_No__c,Sales_Possibility__c,Estimation_Entry_Possibility__c,NoDiscount_Foreign__c,
                            SFDA_Status__c,Qty_Unit__c,BSSCategory__c,Entend_gurantee_period_all__c,Intra_Trade_Service_RMB__c
                            FROM Product2 Where Id IN :productIds
                            And Manual_Entry__c = false];
                    //2021/1/5 liying END
                    // CHAN-BHNBX6 2019/11/20 END
                    for (Product2 product : products) {
                        items.put(product.Id, product);
                    }
                    
                    // 明细行做成
                    for (Integer j = 0; j < olis.size(); j++) {
                        OpportunityLineItem oli = olis[j];
                        Product2 p = items.get(oli.PricebookEntry.Product2Id);
                        Integer Quantity_c = oli.Quantity > 0 ? Integer.valueOf(oli.Quantity) : 1;
                        // CHAN-BHNBX6 2019/11/20 START
                        //将报价委托的币种与外贸币种一致 防止后续外贸有需要用USD判断显示的地方 精琢技术 wql 2021/01/06 start
                        //更新币种相同 wql
                        //quo.CurrencyIsoCode = oli.CurrencyIsoCode;
                        //将报价委托的币种与外贸币种一致 防止后续外贸有需要用USD判断显示的地方 精琢技术 wql 2021/01/06 end
                        //2021/1/5 liying start NoDiscount_Foreign__c
                        if (oli.CurrencyIsoCode == 'USD') {
                            activities[j] = new QELine(j, null, p.Asset_Model_No__c, p.ProductCode, p.Id, p.SFDA_Status__c, p.Sales_Possibility__c, p.Name, p.BSSCategory__c,
                                                       Quantity_c, p.Foreign_Trade_List_US__c, p.Foreign_Trade_List_US__c, p.Foreign_Trade_Cost_US__c,p.Entend_gurantee_period_all__c,p.NoDiscount_Foreign__c);
                        } else if (oli.CurrencyIsoCode == 'CNY') {
                            activities[j] = new QELine(j, null, p.Asset_Model_No__c, p.ProductCode, p.Id, p.SFDA_Status__c, p.Sales_Possibility__c, p.Name, p.BSSCategory__c,
                                                       Quantity_c, p.Intra_Trade_List_RMB__c, p.Intra_Trade_List_RMB__c, p.Intra_Trade_Cost_RMB__c,p.Entend_gurantee_period_all__c,p.Intra_Trade_Service_RMB__c);
                        } else {
                            activities[j] = new QELine(j, null, p.Asset_Model_No__c, p.ProductCode, p.Id, p.SFDA_Status__c, p.Sales_Possibility__c, p.Name, p.BSSCategory__c,
                                                       Quantity_c, 0, 0, 0,p.Entend_gurantee_period_all__c,0);
                        }
                        //2021/1/5 liying END
                        // CHAN-BHNBX6 2019/11/20 END
                    }
                } else {
                    // 已经存在报价
                    if (String.isNotBlank(oppquoid)) {
                        // 报价商品取得
                        // CHAN-BHNBX6 2019/11/20 START//fy lastbuy 20220310 PricebookEntry.Product2.LastbuyProductFLG__c
                        List<QuoteLineItem> qlis = [select id,PricebookEntry.Product2Id,PricebookEntry.Product2.LastbuyProductFLG__c,Quantity__c,CurrencyIsoCode,GuaranteePeriod__c from QuoteLineItem where QuoteId = :oppquoid];
                        // CHAN-BHNBX6 2019/11/20 END
                        List<String> productids = new List<String>();
                        for (QuoteLineItem qli : qlis) {
                            productids.add(qli.PricebookEntry.Product2Id);
                        }
                        // 商品最新信息取得
                        Map<Id, Product2> items = new Map<Id, Product2>();
                        // CHAN-BHNBX6 2019/11/20 START
                        //liying 2021/01/06 start
                        List<Product2> products = [select Id,Name,ProductCode,
                                Foreign_Trade_Cost_US__c,Foreign_Trade_List_US__c,Intra_Trade_Cost_RMB__c,Intra_Trade_List_RMB__c,
                                Asset_Model_No__c,Sales_Possibility__c,Estimation_Entry_Possibility__c,
                                SFDA_Status__c,Qty_Unit__c,BSSCategory__c,Entend_gurantee_period_all__c,Intra_Trade_Service_RMB__c,NoDiscount_Foreign__c
                                FROM Product2 Where Id IN :productIds
                                And Manual_Entry__c = false];
                                  //liying 2021/01/06 end
                        // CHAN-BHNBX6 2019/11/20 END
                        for (Product2 product : products) {
                            items.put(product.Id, product);
                        }
                        // 明细行做成
                        for (Integer j = 0; j < qlis.size(); j++) {
                            QuoteLineItem qli = qlis[j];
                            Product2 p = items.get(qli.PricebookEntry.Product2Id);
                            Integer Quantity_c = qli.Quantity__c > 0 ? Integer.valueOf(qli.Quantity__c) : 1;
                            // CHAN-BHNBX6 2019/11/20 START
                            //将报价委托的币种与外贸币种一致 防止后续外贸有需要用USD判断显示的地方 精琢技术 wql 2021/01/06 start
                            //更新币种相同 wql
                            //quo.CurrencyIsoCode = qli.CurrencyIsoCode;
                            //将报价委托的币种与外贸币种一致 防止后续外贸有需要用USD判断显示的地方 精琢技术 wql 2021/01/06 end
                             //2021/1/5 liying start NoDiscount_Foreign__c
                            if (qli.CurrencyIsoCode == 'USD') {
                                activities[j] = new QELine(j, qli.PricebookEntryId, p.Asset_Model_No__c, p.ProductCode, p.Id, p.SFDA_Status__c, p.Sales_Possibility__c, p.Name, p.BSSCategory__c,
                                                           Quantity_c, p.Foreign_Trade_List_US__c, p.Foreign_Trade_List_US__c, p.Foreign_Trade_Cost_US__c,p.Entend_gurantee_period_all__c,p.NoDiscount_Foreign__c);
                            } else if (qli.CurrencyIsoCode == 'CNY') {
                                activities[j] = new QELine(j, qli.PricebookEntryId, p.Asset_Model_No__c, p.ProductCode, p.Id, p.SFDA_Status__c, p.Sales_Possibility__c, p.Name, p.BSSCategory__c,
                                                           Quantity_c, p.Intra_Trade_List_RMB__c, p.Intra_Trade_List_RMB__c, p.Intra_Trade_Cost_RMB__c,p.Entend_gurantee_period_all__c,p.Intra_Trade_Service_RMB__c);
                            } else {
                                activities[j] = new QELine(j, qli.PricebookEntryId, p.Asset_Model_No__c, p.ProductCode, p.Id, p.SFDA_Status__c, p.Sales_Possibility__c, p.Name, p.BSSCategory__c,
                                                           Quantity_c, 0, 0, 0,p.Entend_gurantee_period_all__c,0);
                            }
                             //2021/1/5 liying end
                            // CHAN-BHNBX6 2019/11/20 END
                        }
                    }
                }
            } else if (String.isNotBlank(leadid)) {
                // 购买意向信息
                List<Lead> leadl = [select Id,Hospital_Name__c,Hospital_Name__r.Name from Lead where Id = :leadid];
                if (leadl.size() > 0) {
                    quo.IraiSubject__c = leadl[0].Hospital_Name__r.Name;
                    quo.Account__c = leadl[0].Hospital_Name__c;
                }
            }
            // 经销商询价报价委托 2020-02-28 update by vivek start 
            else if(String.isNotBlank(agencyoppid)) {
                // 经销商询价
                List<Agency_Opportunity__c> agencyOppL = [select id,Agency_Hospital__c,Agency_Hospital__r.Name,Department_Cateogy__c,Department_Name_Text__c from Agency_Opportunity__c where Id = :agencyoppid];
                if(agencyOppL.size() > 0){
                    String department = agencyOppL[0].Department_Cateogy__c;
                    String departmentE = '';
                    if(department == 'BF'){
                        departmentE = '呼吸科';
                    }
                    if(department == 'ENT'){
                        departmentE = '耳鼻喉科';
                    }
                    if(department == 'ET'){
                        departmentE = 'ET耗材';
                    }
                    if(department == 'GI'){
                        departmentE = '消化科';
                    }
                    if(department == 'GS'){
                        departmentE = '普外科';
                    }
                    if(department == 'GYN'){
                        departmentE = '妇科';
                    }
                    if(department == 'OTH'){
                        departmentE = '其他';
                    }
                    if(department == 'URO'){
                        departmentE = '泌尿科';
                    }
                    if(agencyOppL[0].Department_Name_Text__c == null){
                        agencyOppL[0].Department_Name_Text__c = '';
                    }
                    quo.IraiSubject__c = agencyOppL[0].Agency_Hospital__r.Name+' '+departmentE+' '+agencyOppL[0].Department_Name_Text__c;
                    quo.Agency_Hospital_Link__c = agencyOppL[0].Agency_Hospital__c;
                }
            }
            // 经销商询价报价委托 2020-02-28 update by vivek end
 
            // 招投标报价委托 2021-06-21 update by gzw start
            else if(String.isNotBlank(tenderid)) {
                // 经销商询价
                List<Tender_information__c> tenderL = [select id,Hospital__c,Hospital__r.Name from Tender_information__c where Id = :tenderid];
                if(tenderL.size() > 0){
                    quo.IraiSubject__c = tenderL[0].Hospital__r.Name;
                    quo.Tender_information__c = tenderL[0].Id;
                    quo.Account__c = tenderL[0].Hospital__c;
                }
            }
            // 招投标报价委托 2021-06-21 update by gzw end
        }else{
            // CHAN-BJQ4VZ 精琢技术 2019/12/11 Start
            List<QuoteIrai__c> quoList = 
                [ SELECT Id,Name,Cancel_Decide__c,Agency_Hospital_Link__c,CreatedDate, PriceRefreshDate__c,Quote_Print_Date__c,
                        Quote_Date__c,QuoteToName__c,Quote_Expiration_Date__c,Quote_Comment__c,Tender_information__c,
                        TOTAL__c,Discount__c,Pricing__c,Preferential_Trading_Price__c,Contract__c,LastIraiUser__c,MultiYearWarrantyTotalPrice__c,QuoteTotal_Page__c,Estimation_List_Price__c,
                        Print_HP_Name__c,Account__c,IraiUser__c,IraiSubject__c,CurrencyIsoCode,IraiName__c,QuoteIrai_Status__c,QuoteProportion__c,Note__c,IraiComment__c
                        FROM QuoteIrai__c Where Id =:quoId];
            // CHAN-BJQ4VZ 精琢技术 2019/12/11 End
            // CHAN-BHNBX6 2019/11/20 START
            List<QuoteIraiLineItem__c> items = //lastbuy  2022/3/10 fy start LastbuyProductFLG__c
                [Select Id,Asset_Model_No__c,SFDA_Status__c,Name__c,BSS_Category__c,QuoteIrai__r.Quote_Print_Date__c,
                    Qty_Unit__c,Quantity__c,Product2__r.SFDA_Status__c,ProductCode__c,ListPrice__c,Product2__r.LastbuyProductFLG__c,
                    Product2__r.Sales_Possibility__c,Product2__r.Name,Product2__c,ServicePrice__c,NoDiscountTotal__c,GuaranteePeriod__c
                    From QuoteIraiLineItem__c where QuoteIrai__c = :quoId Order by Item_Order__c, Id];
            // CHAN-BHNBX6 2019/11/20 END
            String copyQuoId = System.currentPageReference().getParameters().get('copyid');
            
            if (copyQuoId == null) {
            } else {
                // copyの場合、quoIdをnullに戻す
                quoId = null;
            }
            if (quoList.size() > 0){
                if (copyQuoId == null) {
                    //system.debug('进到这里了1----');
                    quo = quoList[0];
                    //将报价委托的币种与外贸币种一致 防止后续外贸有需要用USD判断显示的地方 精琢技术 wql 2021/01/06 start
                    // system.debug('进到这里了2----');
                    // if(oppList.size()>0){
                    //     quo.CurrencyIsoCode = oppList[0].CurrencyIsoCode;
                    // }
                    //注释原逻辑 wql
                    //quo.CurrencyIsoCode = 'CNY';
                    //将报价委托的币种与外贸币种一致 防止后续外贸有需要用USD判断显示的地方 精琢技术 wql 2021/01/06 end
                } else {
                    //将报价委托的币种与外贸币种一致 防止后续外贸有需要用USD判断显示的地方 精琢技术 wql 2021/01/06 start
                    // system.debug('进到这里了2----');
                    // if(oppList.size()>0){
                    //     quo.CurrencyIsoCode = oppList[0].CurrencyIsoCode;
                    // }
                    //注释原逻辑 wql
                    quo.CurrencyIsoCode = 'CNY';
                    //将报价委托的币种与外贸币种一致 防止后续外贸有需要用USD判断显示的地方 精琢技术 wql 2021/01/06 end
                    quo.Cancel_Decide__c = false;
                    quo.IraiSubject__c = '';
                    quo.Account__c = null;
                    quo.IraiName__c = '';
                    quo.QuoteProportion__c = 0;
                    quo.PriceRefreshDate__c = Date.today();
                    quo.Quote_Date__c = null;
                    quo.Quote_Print_Date__c = null;
                    quo.Note__c = '';
                    quo.IraiComment__c = '';
                }
                // CHAN-BJQ4VZ 精琢技术 2019/12/10 Start 
                system.debug('标准价格:'+quo.Estimation_List_Price__c);
                 qb.Estimation_List_Price = quo.Estimation_List_Price__c;
                 qb.QuoteTotal_Page = quo.QuoteTotal_Page__c;
                 qb.MultiYearWarrantyTotalPrice  = quoList[0].MultiYearWarrantyTotalPrice__c;
                // CHAN-BJQ4VZ 精琢技术 2019/12/10 End
 
            }
 
            activities = new List<QELine>();
            activitiesbk = new List<QELine>();
            i=0;
            QELine c = new QELine(i);
            QELine bk = new QELine(i);
            if(items.size()>0){
                for (QuoteIraiLineItem__c o:items){
                    c = new QELine(o,i,copyQuoId);
                    activities.add(c);
                    bk = new QELine(o,i,copyQuoId);
                    activitiesbk.add(bk);
                    i++;
                }
                for (integer j=i;j<quoteEntryMaxLine;j++){
                    c = new QELine(j);
                    activities.add(c);
                }
                //マスタ最新情報の取得
                settingProduct2();
            }else{
                activities = new List<QELine>();
                for (i=0;i<quoteEntryMaxLine;i++){
                    QELine active_activity = new QELine(i);
                    activities.add(active_activity);
                }
            }
        }
 
        if (quo.Quote_Expiration_Date__c==null){
            quo.Quote_Expiration_Date__c = Date.today() + 30;
        }
 
        //--Savebutton
        Save_button=true;
        system.debug('===000==='+quo);
        return null;
     }
 
 
    //Search Events============================================================
    // TODO ManualEntryと同様、jsにて解決できる、ここでwebserviceだけを実装、今後 by katsu
    public PageReference setProductEntry() {
System.debug('-----:start');
system.debug('○○○○○○○○○○○○○○○Welcome to setProductEntry!!');
system.debug('▼▼▼▼▼setProduct_text:' + setProduct_text);
        List<String> productIDLIST = new List<String>();
        //既存データ数の確認
        Integer currentDetailNumber = 0;
        system.debug('wwwwwwwww:'+activities);
        for (QELine s:activities){
            //データ判定にAsset_Model_Noを使用
            if ((s.Asset_Model==null) || (s.Asset_Model=='')){
                break;
            }
            currentDetailNumber++;
        }
 
        //既存データ数が150以上?
        if (currentDetailNumber >= quoteEntryMaxLine) {
            PageArrange();
System.debug('-----:強制終了:00');
            return null;
        }
 
        // SearchSetProductから、セット品コードは渡ってきたか?
        if (setProduct_text == null) {
            // セット品コードが渡ってこなかった場合
            // 終了
            PageArrange();
System.debug('-----:強制終了:01');
            return null;
        }else{
            productIDLIST = setProduct_text.split(',');
        }
 
        // セット品明細の ProductId一覧を格納する
        // pricebookEntry + product2へのクエリのWhere句で使用する
        List<Id> productIds = null;
 
        // ----------------------------------------------------------------------------------------
        // 該当するセット品明細のレコードを取得
        // ----------------------------------------------------------------------------------------
System.debug('-----:Product_Set_Detail__c select start');
        List<Product_Set_Detail__c> productSetDetails = [SELECT Id, Product__c, Quantity__c, Product_Set__r.Name FROM Product_Set_Detail__c Where Product_Set__c in :productIDLIST];
System.debug('-----:Product_Set_Detail__c select end');
        if (productSetDetails.size() == 0) {
            PageArrange();
            return null;
        }
        else {
            productIds = new List<Id>();
            for (Product_Set_Detail__c local : productSetDetails) {
                productIds.add(local.Product__c);
            }
        }
 
        //=======Temporary=====
        tmpactivities = activities;
 
        //=======Initialize=========
        activities = new List<QELine>();
 
        boolean lineflg = false;
 
        // ----------------------------------------------------------------------------------------
        // Product2へのクエリを実行
        // 一度Listで結果を受けた後に、Product2Idの Mapにする
        // ----------------------------------------------------------------------------------------
System.debug('-----:Product2 select start');
        Map<Id, Product2> items = new Map<Id, Product2>();
        List<Product2> products = [select Id,Name,ProductCode,
                Foreign_Trade_Cost_US__c,Foreign_Trade_List_US__c,Intra_Trade_Cost_RMB__c,Intra_Trade_List_RMB__c,
                Asset_Model_No__c,Sales_Possibility__c,Estimation_Entry_Possibility__c,NoDiscount_Foreign__c,
                SFDA_Status__c,Qty_Unit__c,BSSCategory__c,Entend_gurantee_period_all__c,Intra_Trade_Service_RMB__c
                FROM Product2 Where Id IN :productIds
                And Manual_Entry__c = false];
        for (Product2 product : products) {
            items.put(product.Id, product);
        }
System.debug('-----:Product2 select end');
System.debug('-----:PricebookEntry select start');
        Map<Id, PricebookEntry> entries = new Map<Id, PricebookEntry>();
        List<PricebookEntry> workEntries = [
                SELECT Id,Product2Id
                FROM PricebookEntry Where Product2Id IN :productIds
                AND CurrencyIsoCode = :quo.CurrencyIsoCode
                AND IsActive = true
        ];
        for (PricebookEntry workEntry : workEntries) {
            entries.put(workEntry.Product2Id, workEntry);
        }
System.debug('-----:PricebookEntry select end');
 
        // ----------------------------------------------------------------------------------------
        // 画面の明細行のループ
        // ----------------------------------------------------------------------------------------
        Integer i = 0;
        Integer rightcnt = 0; // 成功した数をカウント
        for (QELine t:tmpactivities){
 
            QELine a = New QELine(i);
 
System.debug('-----:i=' + i + ', currentDetailNumber=' + currentDetailNumber);
 
            if (i == currentDetailNumber) {
                // ----------------------------------------------------------------------------------------
                // 一回だけ実行されるコード
                // ----------------------------------------------------------------------------------------
System.debug('-----:items.size()=' + items.size());
                if (items.size() > 0) {
                    // ----------------------------------------------------------------------------------------
                    // セット品明細のループ
                    // ----------------------------------------------------------------------------------------
System.debug('-----:セット品明細のループスタート');
                    for (Integer l = 0; l < productSetDetails.size(); l++) {
                        Product_Set_Detail__c nowDetail = productSetDetails[l];
                        Product2 prd = items.get(nowDetail.product__c);
                        PricebookEntry pbe = entries.get(nowDetail.product__c);
 
                        Schema.DescribeFieldResult dfr = QuoteIraiLineItem__c.ListPrice__c.getDescribe();
                        Boolean cansee = dfr.isAccessible();
                        Decimal price = 0;
                        if (cansee) {
                            if (quo.CurrencyIsoCode == 'USD') {
                                price = prd.Foreign_Trade_List_US__c;
                            } else if (quo.CurrencyIsoCode == 'CNY') {
                                price = prd.Intra_Trade_List_RMB__c;
                            }
                        }
 
                        if (pbe == null) {
system.debug('This Productid(' + nowDetail.product__c +  ') is not exist PricebookEntry');
                            // ----------------------------------------------------------------------------------------
                            // 取得済みの Product2のリストの中に、セット品明細の情報がみつからない場合
                            // なにもしないでスルーする
                            // ----------------------------------------------------------------------------------------
                        }
                        else {
                            // ----------------------------------------------------------------------------------------
                            // 取得済みの Product2のリストの中に、セット品明細の情報がみつかった
                            // 明細のその Product2の情報をセットする?
                            // ----------------------------------------------------------------------------------------
                            QELine c = null;
                            Integer Quantity_c = nowDetail.Quantity__c > 0 ? Integer.valueOf(nowDetail.Quantity__c) : 1;
                            system.debug('quo.CurrencyIsoCode:+++++++++'+quo.CurrencyIsoCode);
                            // CHAN-BHNBX6 2019/11/20 START
                            //2021/01/08 liying start
                            if (quo.CurrencyIsoCode == 'USD') {
                                if (prd.Foreign_Trade_List_US__c > 0 && prd.Foreign_Trade_Cost_US__c > 0) {
                                    c = new QELine(i, pbe.Id, prd.Asset_Model_No__c, prd.ProductCode, nowDetail.product__c, prd.SFDA_Status__c, prd.Sales_Possibility__c, prd.Name, prd.BSSCategory__c,
                                            Quantity_c, price, price, prd.Foreign_Trade_Cost_US__c,prd.Entend_gurantee_period_all__c,prd.NoDiscount_Foreign__c);
                                } else {
                                    continue;
                                }
                            } else if (quo.CurrencyIsoCode == 'CNY') {
                                if (prd.Intra_Trade_List_RMB__c > 0 && prd.Intra_Trade_Cost_RMB__c > 0) {
                                    c = new QELine(i, pbe.Id, prd.Asset_Model_No__c, prd.ProductCode, nowDetail.product__c, prd.SFDA_Status__c, prd.Sales_Possibility__c, prd.Name, prd.BSSCategory__c,
                                            Quantity_c, price, price, prd.Intra_Trade_Cost_RMB__c,prd.Entend_gurantee_period_all__c,prd.Intra_Trade_Service_RMB__c);
                                } else {
                                    continue;
                                }
                            } else {
                                continue;
                                // c = new QELine(i, pbe.Id, prd.Asset_Model_No__c, prd.ProductCode, nowDetail.product__c, prd.SFDA_Status__c, prd.Sales_Possibility__c, prd.Name, prd.BSSCategory__c,
                                //        Quantity_c, 0, 0, 0);
                            }
                            //2021/01/08 liying end
 
                            // CHAN-BHNBX6 2019/11/20 END
                            activities.add(c);
 
                            if (i == 149) {
                                // 明細行の最大値に達したら、処理を終了する
                                PageArrange();
System.debug('-----:強制終了:98');
                                return null;
                            }
 
                            i++;
                            rightcnt++;
                            lineflg = true;
                        }
                    }
System.debug('-----:セット品明細のループ終了');
                    if (lineflg==true){
                        i--;
                    }
                }
                else {
                    // ----------------------------------------------------------------------------------------
                    // Product2へのクエリが結果を返さなかった時に実行されるコード
                    // ----------------------------------------------------------------------------------------
                    a = t;
                    a.lineNo = i;
                    activities.add(a);
                }
            }
            else {
                // ----------------------------------------------------------------------------------------
                // Product2へクエリを投げない時に実行されるコード
                // ----------------------------------------------------------------------------------------
                a = t;
                a.lineNo = i;
                activities.add(a);
            }
 
            i++;
            if (i > 149) {
                break;
            }
        }
 
        PageArrange();
        if (productSetDetails.size() > 0) {
            errorflg = true;
            errormessage = productSetDetails[0].Product_Set__r.Name + ' 导入结束,导入 ' + productSetDetails.size() + ' 件,成功' + rightcnt + ' 件';
        }
system.debug('-----:終了:' + errormessage);
        return null;
    }
    
    //excelImport
    public PageReference excelImport() {
        system.debug('○○○○○○○○○○○○○○○Welcome to excelImport!!');
        system.debug('▼▼▼▼▼excel_text:' + excel_text);
 
        errorflg = false;
        errormessage = null;
 
        //既存データ数の確認
        Integer j = 0;
        for (QELine s:activities){
            //データ判定にAsset_Model_Noを使用
            if ((s.Asset_Model==null) || (s.Asset_Model=='')){
                break;
            }
            j++;
        }
 
        //=======Temporary=====
        tmpactivities = activities;
 
        //=======Initialize=========
        activities = new List<QELine>();
        Integer i = 0;
        Integer xlscnt = 0;
        Integer rightcnt = 0; // 成功した数をカウント
 
        string[] xlslists = excel_text.split('\n',-1);
        List<string> xlslist = New List<string>();
        List<string> codelist = New List<string>();
        List<Integer> Quantitylist = New List<Integer>();
 
        Map<String, Integer> mp = new Map<String, Integer>();
        string xlscode;
        Integer xlsQuantity;
 
        try {
            for (string xls:xlslists){
                if(xls==null || xls==''){
                    //null
                }else{
                    xlscode = null;
                    xlsQuantity = null;
                    xlslist = xls.split('\t',-1);
                    for (String s:xlslist){
                        //odd number or even number
                        if (math.mod(i, 2) != 0){
                            //odd number
                            if (s=='' || s==null){
                                errorflg = true;
                                errormessage = System.Label.Error_Message31;
                                activities = tmpactivities;
                                pageArrange();
                                return null;
                            }else{
                                s = s.trim();
                                xlsQuantity = Integer.valueOf(s);
                                Quantitylist.add(xlsQuantity);
                            }
                        }else{
                            //even number
                            if (s=='' || s==null){
                                errorflg = true;
                                errormessage = System.Label.Error_Message31;
                                activities = tmpactivities;
                                pageArrange();
                                return null;
                            }else{
                                s = s.trim();
                                codelist.add(s);
                                xlscode = s;
                            }
                        }
                        i++;
                    }
                    //mp.put(xlscode, xlsQuantity);
                    xlscnt++;
                }
            }
        } catch(Exception ex) {
            activities = tmpactivities;
            errorflg = true;
            errormessage = System.Label.Error_Message31;
            pageArrange();
            return null;
        }
 
system.debug(j);
system.debug('xlscnt:::::' + xlscnt);
 
        if (codelist.size()==0 || Quantitylist.size()==0){
            activities = tmpactivities;
            errorflg = true;
            errormessage = System.Label.Error_Message31;
            pageArrange();
            return null;
        }
 
        xlscnt = j + xlscnt;
        if (xlscnt>quoteEntryMaxLine){
            activities = tmpactivities;
            errorflg = true;
            errormessage = System.Label.Error_Message32;
            pageArrange();
            return null;
        }
 
        i = 0;
        boolean lineflg = false;
        for (QELine t:tmpactivities){
            if(i==j){
                Map<String, Product2> mpProduct2 = new Map<String, Product2>();                     // keyがProductCodeです。
                //2021/01/07 liying start excel导入按钮
                List<Product2> items = [select Id,Name,ProductCode,
                        Foreign_Trade_Cost_US__c,Foreign_Trade_List_US__c,Intra_Trade_Cost_RMB__c,Intra_Trade_List_RMB__c,
                        Asset_Model_No__c,Sales_Possibility__c,Estimation_Entry_Possibility__c,NoDiscount_Foreign__c,
                        SFDA_Status__c,Qty_Unit__c,BSSCategory__c,Entend_gurantee_period_all__c,Intra_Trade_Service_RMB__c
                        FROM Product2 Where ProductCode In :codelist
                        And Manual_Entry__c = false];
                for (Product2 prd:items) {
system.debug('prd.ProductCode:::::' + prd.ProductCode);
                    mpProduct2.put(prd.ProductCode, prd);
                }
                Map<String, PricebookEntry> entries = new Map<String, PricebookEntry>();            // keyがProductCodeです。
                List<PricebookEntry> pbes = [
                    select Id, PricebookEntry.Product2.ProductCode
                    FROM PricebookEntry Where PricebookEntry.Product2.ProductCode IN :codelist
                    AND CurrencyIsoCode = :quo.CurrencyIsoCode
                    AND IsActive = true];
                for (PricebookEntry pbe:pbes) {
system.debug('pbe.Product2.ProductCode:::::' + pbe.Product2.ProductCode);
                    entries.put(pbe.Product2.ProductCode, pbe);
                }
 
                for (Integer l=0;l<codelist.size();l++){
system.debug('codelist[l]:::::' + codelist[l]);
                    Product2 prd = mpProduct2.get(codelist[l]);
                    if (prd != null){
                        PricebookEntry pbe = entries.get(codelist[l]);
                        
                        Schema.DescribeFieldResult dfr = QuoteIraiLineItem__c.ListPrice__c.getDescribe();
                        Boolean cansee = dfr.isAccessible();
                        Decimal price = 0;
                        if (cansee) {
                            if (quo.CurrencyIsoCode == 'USD') {
                                price = prd.Foreign_Trade_List_US__c;
                            } else if (quo.CurrencyIsoCode == 'CNY') {
                                price = prd.Intra_Trade_List_RMB__c;
                            }
                        }
                        
                        QELine c = null;
                        if (pbe != null && (quo.CurrencyIsoCode=='USD' || quo.CurrencyIsoCode=='CNY')) {
                            // CHAN-BHNBX6 2019/11/20 START
                            if (quo.CurrencyIsoCode == 'USD') {
                                if (prd.Foreign_Trade_List_US__c > 0 && prd.Foreign_Trade_Cost_US__c > 0) {
                                    c = new QELine(i, pbe.Id, prd.Asset_Model_No__c, prd.ProductCode, prd.Id, prd.SFDA_Status__c, prd.Sales_Possibility__c, prd.Name, prd.BSSCategory__c,
                                            Quantitylist[l], price, price, prd.Foreign_Trade_Cost_US__c,prd.Entend_gurantee_period_all__c,prd.NoDiscount_Foreign__c);
                                } else {
                                    continue;
                                }
                            } else {
                                if (prd.Intra_Trade_List_RMB__c > 0 && prd.Intra_Trade_Cost_RMB__c > 0) {
                                    c = new QELine(i, pbe.Id, prd.Asset_Model_No__c, prd.ProductCode, prd.Id, prd.SFDA_Status__c, prd.Sales_Possibility__c, prd.Name, prd.BSSCategory__c,
                                            Quantitylist[l], price, price, prd.Intra_Trade_Cost_RMB__c,prd.Entend_gurantee_period_all__c,prd.Intra_Trade_Service_RMB__c);
                                } else {
                                    continue;
                                }
                            }
                            // CHAN-BHNBX6 2019/11/20 END
                            //2021/01/07 liying end
                        } else {
                            continue;
                            // c = new QELine(i, pbe.Id, prd.Asset_Model_No__c, prd.ProductCode, prd.Id, prd.SFDA_Status__c, prd.Sales_Possibility__c, prd.Name, prd.BSSCategory__c,
                            //        Quantitylist[l], 0, 0, 0);              // pbe ない時も追加する、setProductEntry() のロジックと違います。
                        }
                        activities.add(c);
                        i++;
                        rightcnt++;
                        lineflg = true;
                    }
                }
                if (lineflg==true){
                    i--;
                }
            }else{
                QELine a = New QELine(t, i);
                activities.add(a);
            }
            i++;
            if (i>149){
                break;
            }
        }
        // messageを出す
        errorflg = true;
        errormessage = '数据导入结束,导入 ' + codelist.size() + ' 件,成功' + rightcnt + ' 件';
        pageArrange();
 
        return null;
 
    }
    
    //Button Ivents============================================================
 
    //irai button
    public PageReference quoteIrai(){
        List<String> productidList = new List<String>();
        Map<String,String> productCodeMap = new Map<String,String>();
        system.debug('○○○○○○○○○○○○○○○Welcome to QuoteIraiButton!!');
        
        System.debug('quo.Agency_Hospital_Link__c======'+quo.Agency_Hospital_Link__c);
        // System.debug('quo.IraiUser__c======'+quo.IraiUser__r.ProfileId);
        if (quo.IraiUser__c == null) {
            errorflg = true;
            errorMessage = '请选择委托人员。';
            pageArrange();
            return null;
        }
        // 经销商询价报价委托 2020-02-28 update by vivek start
        // 经销商询价报价委托验证委托人必须为营业助理
        if(!String.isBlank(quo.Agency_Hospital_Link__c)){
            userProfileId = new Map<Id,Id>();
            userProfileId.put('00e10000000xnpRAAQ', '00e10000000xnpRAAQ');
            userProfileId.put('00e10000000xyK6AAI', '00e10000000xyK6AAI');
            List<User> userProL = [select id,ProfileId from User where id = :quo.IraiUser__c];
            System.debug('userProL[0].ProfileId======'+userProL[0].ProfileId);
            if(!userProfileId.containsKey(userProL[0].ProfileId)){
                errorflg = true;
                errorMessage = '委托人员只能为营业助理';
                pageArrange();
                return null;
            }
        }
        
        // 经销商询价报价委托 2020-02-28 update by vivek end
        list<String> descriptions = new list<String>();
        if (activities.size()>0){
            for (QELine a:activities){
                String productid = a.PageObject.Product2__c;
                if (productid != null && productid.trim().length() > 0) {
                    productidList.add(productid);
                }
            }
        }
        Product2[] pro = [select Id,ProductCode from Product2 where Id in :productidList];
        for (Product2 p : pro) {
            productCodeMap.put(p.id,p.ProductCode);
        }
        if (activities.size()>0){
            for (QELine a:activities){
                String productid = a.PageObject.Product2__c;
                if (productid != null && productid.trim().length() > 0) {
                    descriptions.add(productCodeMap.get(productid) + '\t' + a.pageObject.Quantity__c);
                }
            }
        }
        if (descriptions.size() <= 0) {
            errorflg = true;
            errorMessage = '没有要委托的产品。';
            pageArrange();
            return null;
        }
        Savepoint sp = Database.setSavepoint();
        try {
            //データチェック
            if (dataCheck() ==false){
                return null;
            }
            if (dataEntry()==false){
                return null;
            }
            
            String description = '';
            Integer i = 1;
            for (String d : descriptions) {
                if (i == 1) {
                    description += d;
                } else {
                    description += '\r\n' + d;
                }
                i += 1;
            }
            if (!String.isBlank(quo.Note__c)) {
                description += '\r\n' + quo.Note__c;
            }
            if (!String.isBlank(quo.Account__c)) {
                description += '\r\n' + Account.sObjectType.getDescribe().getLabel() + ':' + baseUrl + '/' + quo.Account__c;
            }
            // 经销商询价报价委托 2020-02-28 update by vivek start
            if (!String.isBlank(quo.Agency_Hospital_Link__c)) {
                description += '\r\n' + Agency_Hospital_Link__c.sObjectType.getDescribe().getLabel() + ':' + baseUrl + '/' + quo.Agency_Hospital_Link__c;
            }
            // 经销商询价报价委托 2020-02-28 update by vivek end
 
            // 招投标报价委托 2020-06-21 update by gzw start
            // if (!String.isBlank(quo.Tender_information__c)) {
            //     description += '\r\n' + Tender_information__c.sObjectType.getDescribe().getLabel() + ':' + baseUrl + '/' + quo.Tender_information__c;
            // }
            // 招投标报价委托 2020-06-21 update by gzw end
            Task[] tasks = [select Id,Subject,OwnerId,Description,ActivityDate,QuoteIraiId__c
                            from Task
                            where QuoteIraiId__c = :quoId and OwnerId = :quo.IraiUser__c];
            String todoSubject = '报价委托:' + quo.IraiSubject__c;
            if (!String.isBlank(quo.IraiName__c)) {
                todoSubject += ', ' + quo.IraiName__c;
            }
            if (!String.isBlank(quo.IraiComment__c)) {
                todoSubject += ', ' + quo.IraiComment__c;
            }
            if (quo.QuoteProportion__c != null) {
                todoSubject += ', ' + quo.QuoteProportion__c + '%';
            }
            String taskid = '';
            if (tasks.size() > 0) {
                Task task = tasks[0];
                task.Subject = todoSubject;
                task.Description = description;
                task.ActivityDate = Date.today();
                
                Database.DMLOptions dmlo = new Database.DMLOptions();
                dmlo.EmailHeader.triggerUserEmail = true;
                Database.update(task, dmlo);
                taskid = task.Id;
            } else {
                Task task = new Task();
                task.Subject = todoSubject;
                task.OwnerId = quo.IraiUser__c;
                task.Description = description;
                task.ActivityDate = Date.today();
                task.QuoteIraiId__c = quoId;
                
                Database.DMLOptions dmlo = new Database.DMLOptions();
                dmlo.EmailHeader.triggerUserEmail = true;
                Database.insert(task, dmlo);
                taskid = task.Id;
            }
            
            User u = [select Id,Name from user where Id = :quo.IraiUser__c];
            quo.LastIraiUser__c = u.Name;
            QuoteIrai__c qi = new QuoteIrai__c(Id = quoId);
            qi.LastIraiUser__c = quo.LastIraiUser__c;
            //报价委托状态更新  已经委托
            qi.QuoteIrai_Status__c = '已经委托';
            update qi;
            if(String.isNotBlank(quoId)){
                // CHAN-BJQ4VZ 精琢技术 2019/12/11 Start
                quo =[ SELECT Id,Name,Cancel_Decide__c,CreatedDate, PriceRefreshDate__c,Quote_Print_Date__c,
                        Quote_Date__c,QuoteToName__c,Quote_Expiration_Date__c,Quote_Comment__c,Tender_information__c,
                        TOTAL__c,Discount__c,Pricing__c,Preferential_Trading_Price__c,Contract__c,LastIraiUser__c,MultiYearWarrantyTotalPrice__c,QuoteTotal_Page__c,Estimation_List_Price__c,
                        Print_HP_Name__c,Account__c,Agency_Hospital_Link__c,IraiUser__c,IraiSubject__c,CurrencyIsoCode,IraiName__c,QuoteIrai_Status__c,QuoteProportion__c,Note__c,IraiComment__c
                        FROM QuoteIrai__c Where Id =:quoId];
                // CHAN-BJQ4VZ 精琢技术 2019/12/11 End
            }
            // 招投标报价委托 2020-06-21 update by gzw start
            if (!String.isBlank(quo.Tender_information__c)) {
                Tender_information__c tender = new Tender_information__c(Id = quo.Tender_information__c);
                tender.QuoteIrai__c = quoId;
                update tender;
            }
            // 招投标报价委托 2020-06-21 update by gzw end
            errorflg = true;
            errorMessage = '邮件发送完成。';
            pageArrange();
            return null;
            //报价委托状态更新  已经委托
        } catch (DmlException de) {
            Database.rollback(sp);
            errorflg = true;
            errormessage = de.getDmlMessage(0);           // 1件目のエラーのみ表示
            System.debug(Logginglevel.ERROR, de.getMessage());
            System.debug(Logginglevel.ERROR, de.getStackTraceString());
        } catch (Exception e) {
            Database.rollback(sp);
            errorflg = true;
            errormessage = e.getMessage();
            System.debug(Logginglevel.ERROR, e.getMessage());
            System.debug(Logginglevel.ERROR, e.getStackTraceString());
        }
        
        return null;
    }
    public String getoppId(){
        String opptext = null;
        if(String.isNotBlank(quoId)){
            QuoteIrai__c getnote = [ SELECT Id,Name,Note__c FROM QuoteIrai__c Where Id =:quoId];
            if(String.isNotBlank(getnote.Note__c) && getnote.Note__c.indexOf( 'com/') > 0){
                opptext = getnote.Note__c.SubString(getnote.Note__c.LastIndexOf('/')+1,getnote.Note__c.LastIndexOf('/')+16);
            }
        }
        return opptext;
    }
    //Save button
    public PageReference Save(){
 
        errorflg = false;
        errormessage = null;
        Savepoint sp = Database.setSavepoint();
        try {
            //データチェック
            if (dataCheck() ==false){
                return null;
            }
            
            if (dataEntry()==false){
                //msg
                return null;
            }else{
                //msg
                errorflg = true;
                errorMessage = System.Label.Message_002;
                
                return null;
            }
        } catch (DmlException de) {
            Database.rollback(sp);
            errorflg = true;
            errormessage = de.getDmlMessage(0);           // 1件目のエラーのみ表示
            System.debug(Logginglevel.ERROR, de.getMessage());
            System.debug(Logginglevel.ERROR, de.getStackTraceString());
        } catch (Exception e) {
            Database.rollback(sp);
            errorflg = true;
            errormessage = e.getMessage();
            System.debug(Logginglevel.ERROR, e.getMessage());
            System.debug(Logginglevel.ERROR, e.getStackTraceString());
        }
        
        return null;
    }
 
    //OppReflection button
    public PageReference OppReflection(){
 
        Savepoint sp = Database.setSavepoint();
        try {
            errorflg = false;
            errormessage = null;
 
            //データチェック
            if (dataCheck() ==false){
                return null;
            }
            PageReference pageRef = new PageReference('/');
            if (dataEntry()==false){
                //msg
                return null;
            }else{
                //msg
                if(String.isBlank(oppid)){
                    oppid = getoppId();
                }
                if(String.isBlank(oppid)){
                    pageRef = new PageReference('/');
                    return pageRef;
                }else{
                    pageRef = new PageReference('/' +oppid);
                    return pageRef;
                }
            }
        } catch (DmlException de) {
            Database.rollback(sp);
            errorflg = true;
            errormessage = de.getDmlMessage(0);           // 1件目のエラーのみ表示
            System.debug(Logginglevel.ERROR, de.getMessage());
            System.debug(Logginglevel.ERROR, de.getStackTraceString());
        } catch (Exception e) {
            Database.rollback(sp);
            errorflg = true;
            errormessage = e.getMessage();
            System.debug(Logginglevel.ERROR, e.getMessage());
            System.debug(Logginglevel.ERROR, e.getStackTraceString());
        }
        
        return null;
    }
 
    //BackButton
    public PageReference Back(){
        if(String.isBlank(oppid)){
            oppid = getoppId();
        }
        if(String.isBlank(oppid)){
            PageReference pageRef = new PageReference('/');
            return pageRef;
        }else{
            PageReference pageRef = new PageReference('/' +oppid);
            return pageRef;
        }
        //return new Pagereference('/');
    }
 
    // TODO 削除する。商品最新状態は、sqlからすでにproductの最新状態を取得するして、コンストラクタで設定するようにします。このメソッドはいらない
    private void settingProduct2(){
        system.debug('○○○○○○○○○○○○Welcome to settingProduct2 class!!○○○○○○○○○○○○');
 
        pageArrange();
    }
    
    // 0表示 対策
    private void pageArrange(){
        if (activities.size()>0){
            for (QELine a:activities){
                if ((a.Asset_Model==null) || (a.Asset_Model=='')){
system.debug('○○○○○○○○○○○○Welcome to pageArrange Asset_Model is △');
                    a.ListPrice_Page = null;
                    a.ListPriceTotal_Page = null;
                    // CHAN-BHNBX6 2019/11/20 START
                    a.NoDiscount_Page = null;
                    a.NoDiscountTotal_Page = null;
                    a.pageObject.GuaranteePeriod__c = null;
                    // CHAN-BHNBX6 2019/11/20 END
                } else {
system.debug('○○○○○○○○○○○○Welcome to pageArrange Asset_Model=[' + a.Asset_Model + ']');
                }
            }
        }
    }
 
    public boolean dataCheck(){
         //20220310 fy lastbuy start 
         if (quoId!=null){
            if(!ReservedProductVerification()){
                if(flglastbuy==1){
                  errorflg = true;
                  errormessage =  '预留产品表中没有该询价,请通过本部窗口联系营业管理课' ;
                  return false;
                }else if(flglastbuy==2){
                  errorflg = true;
                  errormessage =  errorProductmodel+'产品数量不可超过产品预留数量' ;
                  return false;
                }else if(flglastbuy==3){
                  errorflg = true;
                  errormessage =  '预留产品'+errorProductmodel+'未录入预留产品表';
                  return false;
                }
                // else if(flglastbuy==4){
                //     errorflg = true;
                //     errormessage =  '该报价委托存在预留产品';
                //     return false;
                // }
              }
        }
      
      //20220310 fy lastbuy end
        system.debug('○○○○○○○○○○○○Welcome to dataCheck class!!○○○○○○○○○○○○');
        errorflg = false;
        errormessage = null;
        Boolean error = false;
        List<String> product2Ids = New List<String>();
        system.debug('wuwuwuwuwu:'+activities);
        if (activities.size()>0){
            for (QELine a:activities){
                if (String.isBlank(a.PageObject.Product2__c) == false) {
                    product2Ids.add(a.PageObject.Product2__c);
                }
            }
            system.debug('mmmmmmmm'+product2Ids);
            prd2LatestValMap = new Map<Id, Product2>();
            for (Product2 prd2: [Select Id, Estimation_Entry_Possibility__c, SFDA_Status__c,SFDA_Approbated_Status__c,StorageStatusNo__c,Entend_gurantee_period_all__c  From Product2 Where Id IN :product2Ids]) {
                if (prd2.Estimation_Entry_Possibility__c != '○') {
                    error = true;
                }
                prd2LatestValMap.put(prd2.Id, prd2);
                system.debug('qqqqqqqq:'+prd2LatestValMap);
            }
            if (error == true){
                if (quoId != null) {
                    Map<String,QuoteIraiLineItem__c> itemmap = new Map<String,QuoteIraiLineItem__c>();
                    for (QuoteIraiLineItem__c item : [//lastbuy  2022/3/10 fy start LastbuyProductFLG__c
                        Select Id,Product2__r.SFDA_Status__c,Product2__r.Name,Product2__c,Product2__r.LastbuyProductFLG__c
                        From QuoteIraiLineItem__c where QuoteIrai__c = :quoId Order by Item_Order__c, Id]) {
                        itemmap.put(item.Product2__c,item);
                    }
                    for (QELine a:activities){
                        if (a.PageObject.Product2__c != null) {
                            if (itemmap.containskey(a.PageObject.Product2__c)) {
                                a.pageObject.SFDA_Status__c = itemmap.get(a.PageObject.Product2__c).Product2__r.SFDA_Status__c;
                                a.pageObject.Name__c = itemmap.get(a.PageObject.Product2__c).Product2__r.Name;
                            }
                        }
                    }
                }
            }
        }
        
        if (error==true){
            PageArrange();
            errorflg = true;
            errorMessage = System.Label.Error_Message37 + System.Label.Error_Message48;
            return false;
        }
        
        PageArrange();
        errorflg = false;
        errorMessage = null;
        return true;
    }
 
    public boolean dataEntry(){
system.debug('○○○○○○○○○○○○Welcome to dataEntry class!!○○○○○○○○○○○○');
        Boolean error = false;
        if((quo.IraiSubject__c == null) || (quo.IraiSubject__c =='')){
            quo.IraiSubject__c.addError(System.Label.Error_Message3);
            error = true;
            errormessage = System.Label.Error_Message3;
        }
        if(quo.Quote_Expiration_Date__c == null) {
            quo.Quote_Expiration_Date__c.addError(System.Label.Error_Message3);
            error = true;
            errormessage = System.Label.Error_Message3;
        }
        for (QELine a : activities) {
            if ((a.Asset_Model!=null) && (a.Asset_Model!='')){
                if (a.PageObject.Quantity__c==null || a.PageObject.Quantity__c==0){
                    a.PageObject.Quantity__c.addError(System.Label.Error_Message3);
                    error = true;
                    errormessage = System.Label.Error_Message3;
                }
            }
        }
 
        if (error==true){
            PageArrange();
 
            errorflg = true;
            return false;
        }
 
        //Quote-------------------------------------------------------------
        //商談Id、価格表Id
        //見積名称、標準定価合計、見積金額合計(積上)、病院の契約金額、原価、
        //値引金額計算、値引き金額金額、見積調整金額計算、見積調整金額金額
        //第一販売店名称、金額、利益、%、第二販売店名称、金額、利益、%
        //优惠成交价、优惠折扣、优惠价格、单价、报价金额、Total
        //契約内訳、印刷病院名称、見積有効期限日、見積表記コメント
        QuoteIrai__c q = New QuoteIrai__c();
        
        List<QELine> acts = new List<QELine>();
        for (QELine act : activities) {
            if (act.Asset_Model != null && act.Asset_Model != ''){
                acts.add(act);
            }
        }
        if (acts.size() != activitiesbk.size()) {
            quo.LastIraiUser__c = '';
        } else {
            for (Integer i = 0; i < acts.size(); i++) {
                // CHAN-BHNBX6 2019/11/20 START
                if (activitiesbk[i].Asset_Model != acts[i].Asset_Model
                    || activitiesbk[i].pageObject.SFDA_Status__c != acts[i].pageObject.SFDA_Status__c
                    || activitiesbk[i].pageObject.Name__c != acts[i].pageObject.Name__c
                    || activitiesbk[i].pageObject.Quantity__c != acts[i].pageObject.Quantity__c
                    || activitiesbk[i].pageObject.Product2__c != acts[i].pageObject.Product2__c
                    || activitiesbk[i].ListPrice_Page != acts[i].ListPrice_Page
                    || activitiesbk[i].NoDiscount_Page != acts[i].NoDiscount_Page
                    || activitiesbk[i].pageObject.GuaranteePeriod__c != acts[i].pageObject.GuaranteePeriod__c
                ) {
                    // CHAN-BHNBX6 2019/11/20 END
                    quo.LastIraiUser__c = '';
                    break;
                }
            }
        }
        if (changedAfterPrint) {
            quoId = null;
        }
        if (quoId==null){
            q = New QuoteIrai__c();
        }else{
            // CHAN-BJQ4VZ 精琢技术 2019/12/11 Start
            List<QuoteIrai__c> qs = New List<QuoteIrai__c>();
            qs = [select Id,Account__c,Agency_Hospital_Link__c,Name,IraiUser__c,IraiSubject__c,Tender_information__c,
                Preferential_Trading_Price__c,Discount__c,Pricing__c,Unit_Price__c,Offer_Amount__c,TOTAL__c,MultiYearWarrantyTotalPrice__c,QuoteTotal_Page__c,Estimation_List_Price__c,
                Contract__c,Print_HP_Name__c,Quote_Expiration_Date__c,Quote_Comment__c,IraiName__c,QuoteIrai_Status__c,QuoteProportion__c,Note__c,IraiComment__c
                From QuoteIrai__c Where Id =:quoId];
            // CHAN-BJQ4VZ 精琢技术 2019/12/11 End
            if (qs.size()>0){
                q = qs[0];
            }
        }
 
        if (quoId==null){
            q.PriceRefreshDate__c = Date.today();
        }
        if (productStatusUpdated) {
            q.PriceRefreshDate__c = Date.today();
        }
        q.IraiSubject__c = quo.IraiSubject__c;
        q.Account__c = quo.Account__c;
        // 经销商询价报价委托 2020-02-28 update by vivek start
        q.Agency_Hospital_Link__c = quo.Agency_Hospital_Link__c;
        // 经销商询价报价委托 2020-02-28 update by vivek end
        // 招投标报价委托 2020-06-21 update by gzw start
        q.Tender_information__c = quo.Tender_information__c;
        // 招投标报价委托 2020-06-21 update by gzw end
        q.IraiUser__c = quo.IraiUser__c;
        q.IraiName__c = quo.IraiName__c;
        q.QuoteProportion__c = quo.QuoteProportion__c;
        q.CurrencyIsoCode = quo.CurrencyIsoCode;
        q.Note__c = quo.Note__c;
        q.IraiComment__c = quo.IraiComment__c;
        //----checkbox は印刷直前に保存
        q.Quote_Expiration_Date__c = quo.Quote_Expiration_Date__c;
        q.Quote_Comment__c = quo.Quote_Comment__c;
        q.LastIraiUser__c = quo.LastIraiUser__c;
        system.debug('标准价格2:'+qb.Estimation_List_Price);
        // CHAN-BJQ4VZ 精琢技术 2019/12/10 Start 
         q.Estimation_List_Price__c = qb.Estimation_List_Price;
         q.MultiYearWarrantyTotalPrice__c = qb.MultiYearWarrantyTotalPrice;
         q.QuoteTotal_Page__c = qb.QuoteTotal_Page;
        // CHAN-BJQ4VZ 精琢技术 2019/12/10 END
 
 
        if (quoId==null){
            insert q;
        }else{
            update q;
        }
        quo =[ SELECT Id,Name,Cancel_Decide__c,CreatedDate, PriceRefreshDate__c,Quote_Print_Date__c,
                    Quote_Date__c,QuoteToName__c,Quote_Expiration_Date__c,Quote_Comment__c,Tender_information__c,
                    TOTAL__c,Discount__c,Pricing__c,Preferential_Trading_Price__c,Contract__c,LastIraiUser__c,MultiYearWarrantyTotalPrice__c,QuoteTotal_Page__c,Estimation_List_Price__c,
                    Print_HP_Name__c,Account__c,Agency_Hospital_Link__c,IraiUser__c,IraiSubject__c,CurrencyIsoCode,IraiName__c,QuoteIrai_Status__c,QuoteProportion__c,Note__c,IraiComment__c
                    FROM QuoteIrai__c Where Id =:q.Id];
 
system.debug('○○○○○Save1○○○○○');
 
        //QuoteLineItem;
        List<QuoteIraiLineItem__c> qlist = New List<QuoteIraiLineItem__c>();
        qlist=[Select Id From QuoteIraiLineItem__c Where QuoteIrai__c =:quoId];
        system.debug('qqqqq'+qlist);
        if (qlist.size()>0){
            //delete
            delete qlist;
        }
 
        //QuoteLineItem--------------------------------------------
        //製品型番、品目コード、SFDAステータス、品目名、ListPrice、数量
        //価格、単位、小計、OCM売上予測金額(税抜)、価格表
        qlist = New List<QuoteIraiLineItem__c>();
        //Sap送信,Printに合わせて1~
        Integer i=1;
system.debug('○○○○○'+activities.size()+'○○○○○');
system.debug('xxxxxx'+activities+'xxxxxxx');
        activitiesbk = new List<QELine>();
        if (activities.size()>0){
            for (QELine s:activities){
                if (s.Asset_Model != null && s.Asset_Model != ''){
system.debug('○○○○○'+s.pageObject.Product2__c+'○○○○○');
                    if (s.pageObject.Product2__c != null){
                        // TODO katsu なぜclone()しますか?意味不明。
                        s.pageObject.GuaranteePeriod__c = prd2LatestValMap.get(s.pageObject.Product2__c).Entend_gurantee_period_all__c;
                        QuoteIraiLineItem__c ql = s.pageObject.clone();
                        ql.QuoteIrai__c = q.Id;
                        ql.ListPrice__c = s.ListPrice_Page;
                        // CHAN-BHNBX6 2019/11/20 START 
                        ql.ServicePrice__c = s.NoDiscount_Page;
                        ql.NoDiscountTotal__c = s.NoDiscountTotal_Page;
                        ql.GuaranteePeriod__c = prd2LatestValMap.get(s.pageObject.Product2__c).Entend_gurantee_period_all__c;
                        // CHAN-BHNBX6 2019/11/20 END
                        ql.SFDA_Status__c = prd2LatestValMap.get(s.pageObject.Product2__c).SFDA_Status__c;
                        //並び順
                        ql.Item_Order__c = i;
 
                        qlist.add(ql);
                        
                        activitiesbk.add(new QELine(ql, s.lineNo, null));
                    }
                }
                i++;
            }
 
            insert qlist;
 
        }
 
        //保存時引合Pageに戻らない処理とした為にQuoteIdをここでセット
        if (quoId==null){
            quoId = q.Id;
            
        }
 
        return true;
    }
     //lastbuy  2022/3/10 fy start
  public boolean ReservedProductVerification() {
    filg=true;
    Map<string,QuoteIraiLineItem__c> quotlinitMap = new Map<string,QuoteIraiLineItem__c>();
    List<Id> lastProductFLGListId = new List<Id>();
    List<QuoteIraiLineItem__c> lastProductFLGList = new List<QuoteIraiLineItem__c>();
    List<QuoteIraiLineItem__c> act = new List<QuoteIraiLineItem__c>();
    List<QuoteIraiLineItem__c> act2 = new List<QuoteIraiLineItem__c>();
    Map<string,string> actMap = new Map<string,string>();
    for(QELine aaa :activities){
        System.debug('131313131!!!'+aaa.pageObject.Product2__r.LastbuyProductFLG__c);
      if(aaa.pageObject.Product2__c!=null&&aaa.pageObject.Quantity__c!=null){
        actMap.put(aaa.pageObject.Product2__c,aaa.Asset_Model);
        act.add(aaa.pageObject);
      }
    }
    act2=act.deepClone();
    Map<String,QuoteIraiLineItem__c> map1 = new Map<String,QuoteIraiLineItem__c>();
    System.debug('activities1111111111112为所当为多多!!!'+activities);
    integer i =0;
    for(QuoteIraiLineItem__c pspsc :act2){
      if(pspsc.Product2__c!=null&&pspsc.Quantity__c!=null){
        if(map1.containsKey(pspsc.Product2__c)){
            QuoteIraiLineItem__c quoteLine = map1.get(pspsc.Product2__c);
          quoteLine.Quantity__c =quoteLine.Quantity__c+pspsc.Quantity__c;
          map1.put(pspsc.Product2__c,quoteLine);
          System.debug('2222222!!!'+quoteLine);
        }else{
          map1.put(pspsc.Product2__c,pspsc);
        }
        System.debug('5555555!!!'+pspsc);
        System.debug('34499879!!!'+activities);
      }
    }
    System.debug('3434343!!!'+activities);
    System.debug('5656565!!!'+map1);
    List<Product2> productlist = [select id,LastbuyProductFLG__c from Product2 where id in:map1.keySet()];   
    Map<String,boolean> productMap = new Map<String,boolean>();
    System.debug('9999999666!!!'+productlist);
    if(productlist!=null&&productlist.size()!=0){
        for(Product2 product : productlist){
            productMap.put(product.id,product.LastbuyProductFLG__c);
        } 
    }
    for (QuoteIraiLineItem__c value : map1.values()) {
      if(productMap.get(value.Product2__c)){
        lastProductFLGListId.add(value.Product2__c);
        quotlinitMap.put(value.Product2__c,value);
        lastProductFLGList.add(value);
      }
    } 
    System.debug('activities++++!!!'+activities);
    System.debug('activities!!!'+map1.values());
    System.debug('oppId!!!'+oppId);
    System.debug('lastProductFLGList!!!'+lastProductFLGListId);
    if(lastProductFLGListId!=null&&lastProductFLGListId.size()!=0){
        // if(oppid==null){
        //     flglastbuy=4;
        //     filg=false;
        //     return filg;
        // }
        List<LastbuyProduct__c> LastbuyObjList=[select id,LastbuyQuantity__c,InquiryCode__c,ProductName__c,effectiveFLG__c from LastbuyProduct__c where InquiryCode__c= : oppid and ProductName__c in :lastProductFLGListId and effectiveFLG__c = true];
        Map<string,LastbuyProduct__c> LastbuyObjMap = new Map<string,LastbuyProduct__c>();
        System.debug('LastbuyObjList+++++!!!'+LastbuyObjList);
        if(LastbuyObjList!=null&&LastbuyObjList.size()!=0){
          for(LastbuyProduct__c lastbuypr :LastbuyObjList){
            LastbuyObjMap.put(lastbuypr.ProductName__c,lastbuypr);
          }
        }else{
          flglastbuy=1;
          filg=false;
          return filg;
        }
        System.debug('LastbuyObjMap!!!'+LastbuyObjMap);
        System.debug('lastProductFLGList+++++++!!!'+lastProductFLGList);
        if(lastProductFLGList!=null&&lastProductFLGList.size()!=0){
          for(QuoteIraiLineItem__c lastbuypr :lastProductFLGList){
            Decimal quoteLItemNum=0;
            if(LastbuyObjMap.containsKey(lastbuypr.Product2__c)){
                quoteLItemNum=LastbuyObjMap.get(lastbuypr.Product2__c).LastbuyQuantity__c;
                System.debug('quoteLItemNum!!!'+quoteLItemNum);
                System.debug('lastbuypr.pageObject.Quantity__c+++!!!'+lastbuypr.Quantity__c);
                if(lastbuypr.Quantity__c>quoteLItemNum){actMap.get(lastbuypr.Product2__c);
                  errorProductmodel=actMap.get(lastbuypr.Product2__c);
                  flglastbuy=2;
                  filg=false;
                  break;
                }
            }else{
              errorProductmodel=actMap.get(lastbuypr.Product2__c);
              flglastbuy=3;
              filg=false;
              break;
            }
          }
        }
    }
    system.debug('filg====='+filg);
    return filg;
  }
 
    // CHAN-BJQ4VZ 精琢技术 2019/12/11 Start
    public class QuoteBean {
    // 产品标准定价总额
    public Decimal Estimation_List_Price { get; set; }
    //报价总额
    public Decimal QuoteTotal_Page { get; set; }
    //NoDiscount price 合计
    public Decimal MultiYearWarrantyTotalPrice { get; set; }
    
    }
    // CHAN-BJQ4VZ 精琢技术 2019/12/11 End
    
    public class QELine {
        public Integer lineNo { get; set; }                                // 画面の順序
        public String Asset_Model {get;set;}
        public String Sales_Possibility {get;set;}                         // 販売可否○×判断用、使ってないようです。TODO 削除
        public QuoteIraiLineItem__c pageObject { get; set; }                      // Id__cは空行判断用、SFDA_Status__c など、翻訳される項目表示するため使う必要があります
        public Decimal Cost_c { get; set; }
        public Decimal Cost_Subtotal_c { get; set; }
 
        public Decimal ListPrice_Page { get; set; }
        public Decimal ListPriceTotal_Page { get; set; }
 
        // CHAN-BHNBX6 2019/11/20 START
        public Decimal NoDiscount_Page { get; set; }
        public Decimal NoDiscountTotal_Page { get; set; }
        // CHAN-BHNBX6 2019/11/20 END
 
        // TODO ほんとうはいらない、使うところのロジックを修正しなければいけない、削除するようにしたいです。
        public QELine(Integer i) {
            pageObject = New QuoteIraiLineItem__c();
            this.lineNo = i;
        }
        // tmp 直接使う場合のパターン
        public QELine(QELine tmp, Integer i) {
            pageObject = tmp.pageObject;
            this.lineNo = i;
            this.Asset_Model = tmp.Asset_Model;
            this.Sales_Possibility = tmp.Sales_Possibility;
            this.Cost_Subtotal_c = tmp.Cost_Subtotal_c;
            this.Cost_c = tmp.Cost_c;
            this.ListPrice_Page = tmp.ListPrice_Page;
            this.ListPriceTotal_Page = tmp.ListPriceTotal_Page;
            // CHAN-BHNBX6 2019/11/20 START
            this.NoDiscount_Page =tmp.NoDiscount_Page;
            this.NoDiscountTotal_Page =tmp.NoDiscountTotal_Page;
            this.pageObject.GuaranteePeriod__c = pageObject.GuaranteePeriod__c;
            // CHAN-BHNBX6 2019/11/20 END
        }
        public QELine(QuoteIraiLineItem__c qli, Integer i, String copyQuoId) {
            pageObject = qli.clone();
            pageObject.Product2__c = qli.Product2__c;
            pageObject.Quantity__c = qli.Quantity__c;
            
            if(copyQuoId != null) {
                pageObject.SFDA_Status__c = qli.Product2__r.SFDA_Status__c;
                pageObject.Name__c = qli.Product2__r.Name;
            }
            this.lineNo = i;
            this.Asset_Model = qli.Asset_Model_No__c;
            this.ListPrice_Page = qli.ListPrice__c;
            this.ListPriceTotal_Page = qli.Quantity__c * qli.ListPrice__c;
            // CHAN-BHNBX6 2019/11/20 START
            pageObject.GuaranteePeriod__c =qli.GuaranteePeriod__c;
            this.NoDiscount_Page =qli.ServicePrice__c;
            if(qli.ServicePrice__c == null){
                this.NoDiscountTotal_Page =0;
            }else{
                this.NoDiscountTotal_Page =qli.Quantity__c * qli.ServicePrice__c;
            }
            
            // CHAN-BHNBX6 2019/11/20 END
        }
        
        // TODO Subtotal__c、以前のロジックを確認
        public QELine(Integer i, String PricebookEntryId, String Asset_Model, String ProductCode, String Id_c, String SFDA_Status_c, String Sales_Possibility_c, String Name_c, String BSS_Category_c, Integer Quantity, Decimal ListPrice_c, Decimal UnitPrice_c, Decimal Cost_c,Decimal GuaranteePeriod_c,Decimal ServicePrice_c) {
            pageObject = New QuoteIraiLineItem__c();
            pageObject.Quantity__c = Quantity;
            this.lineNo = i;
            this.Asset_Model = Asset_Model;
            this.Sales_Possibility = Sales_Possibility_c;
            pageObject.Product2__c = Id_c;
            pageObject.SFDA_Status__c = SFDA_Status_c;
            pageObject.Name__c = Name_c;
            pageObject.BSS_Category__c = BSS_Category_c;
 
            this.ListPrice_Page = ListPrice_c;
            this.ListPriceTotal_Page = Quantity * ListPrice_c;
            // CHAN-BHNBX6 2019/11/20 START
            pageObject.GuaranteePeriod__c =GuaranteePeriod_c;
            this.NoDiscount_Page =ServicePrice_c;
            if(ServicePrice_c == null){
                this.NoDiscountTotal_Page =0;
            }else{
                this.NoDiscountTotal_Page =Quantity * ServicePrice_c;
            }
            
            // CHAN-BHNBX6 2019/11/20 END
            this.Cost_c = Cost_c;
 
            // TODO katsu なぜここ > 0 の判断はいらない?
            this.Cost_Subtotal_c = Cost_c * Quantity;
        }
    }
}