fuyu
2023-03-06 52f362a9efd067ba31e24b30754681aabe8f991e
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
// 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 String leadid;
    //SWAG-CKDATG【委托】【OBSAP-报价委托】报价委托项目改善1 fy start
    public String tenderid;
    //SWAG-CKDATG【委托】【OBSAP-报价委托】报价委托项目改善1 fy end
    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; }
    public Boolean is_changed_opp { get; set; }
    //lastbuy  2022/3/10 fy end
    //SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 start
    public String erroraxsdmodel { get; set; }
    //SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 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;
    //obsap 新增经销商1字段 fy satrt
    public Decimal Salesprofit1 { get; set; }
    public Decimal SalesCalculation1 { get; set; }
    public Boolean displayFlg { get; set; }
    //obsap 新增经销商1字段 fy end
 
    // 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
 
    // obsap对应 obsap人员检索 2022-04-27 ssm start
    public class UserSelect {
        public String user_name { get; set; }
        public User user { get; set; }
        public UserSelect(User u) {
            this.user_name = u.Alias;
            this.user = u;
        }
    } 
    public String obsap_mail { get; set; }
    //obsap obsap人员检索 fy satrt
    // public String selectObsapUsers { get; set; }
    public List<SelectOption> ObsapUsers { get; set; }
    public boolean obsflag { get; set; }
    //obsap obsap人员检索 fy end
    // obsap对应 obsap人员检索 2022-04-27 ssm 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==============');
        obsap_mail = System.Label.OBSAP_Group_Mail;
        errorflg = false;
        pdf_button = true;
        obsflag = false;
        //loginUser
        loginUser = [select Id, ProfileId, State_Hospital__c, Salesdepartment_text__c from User where Id = :UserInfo.getUserId()];
        if (loginUser.ProfileId == System.Label.ProfileId_SystemAdmin) {
            pdf_button = false;
        }
        String obsap_Login_area=System.Label.obsap_Login_area;
        List<String> obsaplogareaList =obsap_Login_area.split(',');
        if(obsaplogareaList.contains(loginUser.Salesdepartment_text__c)){
            obsflag = true;
        }
        // obsap对应 obsap人员检索 2022-04-27 ssm start
        // if (loginUser != null && String.isNotBlank(loginUser.Salesdepartment_text__c) && (loginUser.Salesdepartment_text__c == '5.华东' || loginUser.Salesdepartment_text__c == '6.华南')) {
        //fy 20220512
        if (loginUser != null && String.isNotBlank(loginUser.Salesdepartment_text__c) && obsflag) {
 
            // obsflag = true;
            // 这里做了个比较2的修改
            // 由于客户不想给公共小组的每个人都创建一个任务,只能用队列
            // 这样才能实现一个任务,小组成员都能看到,谁完成都算完成
            // 又由于需要发送邮件,工作流里发送邮件只能到公共小组,不能发给队列
            // 所以把公共小组当作队列成员扔进去
            // 这里只能取两次才能取到小组里的某一个人
            String obsap_group_id = System.Label.obsap_group_opp;
            List<GroupMember> queue =  [SELECT Id, GroupId, UserOrGroupId FROM GroupMember where GroupId = :obsap_group_id];
            system.debug('queue++'+queue);
            if (queue != null && queue.size() > 0) {
                List<GroupMember> members =  [SELECT Id, GroupId, UserOrGroupId FROM GroupMember where GroupId = :queue[0].UserOrGroupId];
                GroupMember member = members != null && members.size() > 0 ? members[0] : new GroupMember();
                User obsap_user = [SELECT Id, Name, Alias FROM User WHERE Id =: member.UserOrGroupId];
                ObsapUsers = new List<SelectOption>();
                // ObsapUsers.add(new SelectOption('',''));
                // for (User u : obsaps) {
                //     ObsapUsers.add(new SelectOption(u.Id,u.Alias));
                // }
                ObsapUsers.add(new SelectOption(obsap_user.Id, 'OBSAP小组'));
            }
        }
        // obsap对应 obsap人员检索 2022-04-27 ssm end
        //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');
        //SWAG-CF589P【委托】【P:OBSAP】报价委托相关新需求评估 fy start
        leadid = System.currentPageReference().getParameters().get('leadid');
        //SWAG-CF589P【委托】【P:OBSAP】报价委托相关新需求评估 fy end
        // 经销商询价报价委托 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
        // 招投标
        //SWAG-CKDATG【委托】【OBSAP-报价委托】报价委托项目改善1 fy start
        // String tenderid = System.currentPageReference().getParameters().get('tenderid');
        tenderid = System.currentPageReference().getParameters().get('tenderid');
        //SWAG-CKDATG【委托】【OBSAP-报价委托】报价委托项目改善1 fy end
 
        // 招投标报价委托 2021-06-21 update by gzw start
 
        // 询价id
        oppid = System.currentPageReference().getParameters().get('oppid');
        QuoteIrai__c quoteiraiobj = new QuoteIrai__c();
        //SWAG-CKDATG【委托】【OBSAP-报价委托】报价委托项目改善1 fy start
        if(oppid==null&&quoId!=null&&leadid==null&&agencyoppid==null){
            // if(oppid==null&&tenderid==null&&quoId!=null&&leadid==null&&agencyoppid==null){
        //SWAG-CKDATG【委托】【OBSAP-报价委托】报价委托项目改善1 fy end
            //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy  Noteplus__c
            quoteiraiobj = [select id,Note__c,Noteplus__c from QuoteIrai__c where id=:quoId];
            if(quoteiraiobj.Note__c!=null){
                String[] quosub=quoteiraiobj.Note__c.split('/');
                //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy start
                oppid=quosub[quosub.size()-1].substring(0,15);
                //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy end
                // oppid=quosub[quosub.size()-1];
            }
        }
        system.debug('oppid:++++'+oppid);
        system.debug('leadid:++++'+leadid);
        system.debug('tenderid:++++'+tenderid);
        // 报价id
        String oppquoid = System.currentPageReference().getParameters().get('oppquoid');
        //将报价委托的币种与外贸币种一致 防止后续外贸有需要用USD判断显示的地方 精琢技术 wql 2021/01/06 start
        List<Opportunity> oppList = [Select id,CurrencyIsoCode, If_Account_Change__c from Opportunity where id =:oppid];
        // lastbuy变更用户询价判断
        // 如果取得了询价,则取询价上的是否变更用户,否则false
        is_changed_opp = oppList != null && oppList.size() > 0 ? oppList[0].If_Account_Change__c : false;
        
        //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
            // SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy start
            // if (String.isNotBlank(tenderid)) {
            if (String.isNotBlank(tenderid)&&String.isBlank(leadid)) {
            // SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy start
                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;
            }
            //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy start
            quo.Noteplus__c = quo.Note__c;
            //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy end
            //新規リストコントローラの取得
            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)) {
                        //DB202302464682【报价委托】报价委托改善224 fy start
                        Quote quo2 = new Quote();
                        List<Quote> quote =  [select Id,Agency1__c,Agency2__c From Quote Where Id =:oppquoid];
                        if(quote.size()>0){
                            quo2=quote[0];
                        }
                        quo.Agency1_entrust__c = quo2.Agency1__c;
                        quo.Agency2_entrust__c = quo2.Agency2__c;
                        //DB202302464682【报价委托】报价委托改善224 fy end
                        // 报价商品取得
                        // 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
            //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy  Noteplus__c
            //SWAG-CF589P【委托】【P:OBSAP】报价委托相关新需求评估 fy Lead__c,Opportunity__c,
            List<QuoteIrai__c> quoList = //obsap 新增经销商1字段 fy satrt Agency1_entrust__c ,SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy start cancelMultiyearInsurance__c,
                [ SELECT Id,Name,Cancel_Decide__c,Agency_Hospital_Link__c,CreatedDate, PriceRefreshDate__c,Quote_Print_Date__c,Agency1_entrust__c,cancelMultiyearInsurance__c,
                        Quote_Date__c,QuoteToName__c,Quote_Expiration_Date__c,Quote_Comment__c,Tender_information__c,Noteplus__c,Lead__c,Opportunity__c,
                        TOTAL__c,Discount__c,Pricing__c,Preferential_Trading_Price__c,Contract__c,LastIraiUser__c,MultiYearWarrantyTotalPrice__c,QuoteTotal_Page__c,Estimation_List_Price__c,
                        Agency2_entrust__c,//DB202302464682【报价委托】报价委托改善224 fy
                        Print_HP_Name__c,Account__c,IraiUser__c,IraiSubject__c,CurrencyIsoCode,IraiName__c,QuoteIrai_Status__c,QuoteProportion__c,Note__c,IraiComment__c
                        , urgent__c  //20230104 lt DB202212427301
                        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 //SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 start Is_DangerousChemicals__c,CanNotCancelledGurantee__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.Is_DangerousChemicals__c,CanNotCancelledGurantee__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
        // SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy start
        this.Save_button=false;
        if(quo.QuoteIrai_Status__c != '草案中'&& String.isNotBlank(quo.QuoteIrai_Status__c)){
            this.Save_button=true;
        }
        // Save_button=true;
        // SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy end
        system.debug('===fff==='+quo.QuoteIrai_Status__c);
        system.debug('===ccc==='+this.Save_button);
        //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy start
        // if( quo.Note__c!=''){
        if(String.isNotBlank(quo.Note__c)){
            system.debug('===111==='+quo.Note__c.split('\r\n'));
            List<String> str=quo.Note__c.split('\r\n');
            if(str.size()==1){
                quo.Note__c=''; 
            }else{
                quo.Note__c=str[1]; 
            }
        }
        //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy end
        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);
                }
            }
        }
        // System.debug('---lt123---descriptions---'+descriptions);
        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 = '';
            //20230116 fy start
            String descriptionsendEmailp = '';
            String descriptionsendEmailbody = '';
            //20230116 fy end
            Integer i = 1;
            for (String d : descriptions) {
                if (i == 1) {
                    description += d;
                    //20230116 fy start
                    descriptionsendEmailp += d;
                    //20230116 fy end
                } else {
                    description += '\r\n' + d;
                    //20230116 fy start
                    descriptionsendEmailp += '\r\n' + d;
                    //20230116 fy end
                }
                i += 1;
            }
            // System.debug('---lt123---description---'+description);
            //obsap 新增经销商1字段 fy start
            if (!String.isBlank(quo.Agency1_entrust__c)) {
                Account  quoteAeName = [select Id,Name from Account where Id =:quo.Agency1_entrust__c];
                description += '\r\n' + '第一经销商名称' + ':' + quoteAeName.Name;
                //20230116 fy start
                descriptionsendEmailbody += '\r\n' + '第一经销商名称' + ':' + quoteAeName.Name;
                //20230116 fy end
            }
            //DB202302464682【报价委托】报价委托改善224 fy start
            if (!String.isBlank(quo.Agency2_entrust__c)) {
                Account  quoteAeName2 = [select Id,Name from Account where Id =:quo.Agency2_entrust__c];
                description += '\r\n' + '第二经销商名称' + ':' + quoteAeName2.Name;
                descriptionsendEmailbody += '\r\n' + '第二经销商名称' + ':' + quoteAeName2.Name;
            }
            //DB202302464682【报价委托】报价委托改善224 fy end
            if (quo.QuoteProportion__c!=null) {
                description += '\r\n' + '报价比例' + ':' + quo.QuoteProportion__c;
                //20230116 fy start
                descriptionsendEmailbody += '\r\n' + '报价比例' + ':' + quo.QuoteProportion__c;
                //20230116 fy end
            }
            if (!String.isBlank(quo.IraiComment__c)) {
                description += '\r\n' + '报价备注' + ':' + quo.IraiComment__c;
                //20230116 fy start
                descriptionsendEmailbody += '\r\n' + '报价备注' + ':' + quo.IraiComment__c;
                //20230116 fy end
            }
            //obsap 新增经销商1字段 fy end
            //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy start
            String node;
            if(!String.isBlank(quo.Note__c)){
                node=quo.Noteplus__c+'\r\n'+quo.Note__c;
            }else{
                node=quo.Noteplus__c;
            }
            //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy end
            if (!String.isBlank(node)) {
                //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy start
                description += '\r\n' + node;
                //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy end
                // description += '\r\n' + quo.Note__c;
                //20230116 fy start
                descriptionsendEmailbody += '\r\n' + node;
                //20230116 fy end
            }
            if (!String.isBlank(quo.Account__c)) {
                description += '\r\n' + Account.sObjectType.getDescribe().getLabel() + ':' + baseUrl + '/' + quo.Account__c;
                //20230116 fy start
                descriptionsendEmailbody += '\r\n' + Account.sObjectType.getDescribe().getLabel() + ':' + baseUrl + '/' + quo.Account__c;
                //20230116 fy end
            }
            // 经销商询价报价委托 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;
                //20230116 fy start
                descriptionsendEmailbody += '\r\n' + Agency_Hospital_Link__c.sObjectType.getDescribe().getLabel() + ':' + baseUrl + '/' + quo.Agency_Hospital_Link__c;
                //20230116 fy end
            }
            // 经销商询价报价委托 2020-02-28 update by vivek end
            //obsap 新增经销商1字段 fy start
            if (!String.isBlank(quo.Agency1_entrust__c)) {
                description += '\r\n' + '第一经销商' + ':' + baseUrl + '/' + quo.Agency1_entrust__c;
                //20230116 fy start
                descriptionsendEmailbody += '\r\n' + '第一经销商' + ':' + baseUrl + '/' + quo.Agency1_entrust__c;
                //20230116 fy end
            }
            //DB202302464682【报价委托】报价委托改善224 fy start
            if (!String.isBlank(quo.Agency2_entrust__c)) {
                description += '\r\n' + '第二经销商' + ':' + baseUrl + '/' + quo.Agency2_entrust__c;
                descriptionsendEmailbody += '\r\n' + '第二经销商' + ':' + baseUrl + '/' + quo.Agency2_entrust__c;
            }
            //DB202302464682【报价委托】报价委托改善224 fy end
            //SWAG-CKDATG【委托】【OBSAP-报价委托】报价委托项目改善1 fy start
            if (!String.isBlank(tenderid)&&!description.contains('招标项目') ) {
                description += '\r\n' + '招标项目' + ':' + baseUrl + '/' + tenderid;
                //20230116 fy start
                descriptionsendEmailbody += '\r\n' + '招标项目' + ':' + baseUrl + '/' + tenderid;
                //20230116 fy end
            }
            //SWAG-CKDATG【委托】【OBSAP-报价委托】报价委托项目改善1 fy end
            //obsap 新增经销商1字段 fy 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
            // obsap 委托人按公共小组区分,检索数量增加 2022-05-09 ssm start
            List<String> irai_userids = new List<String>();
            // if (loginUser != null && String.isNotBlank(loginUser.Salesdepartment_text__c) && (loginUser.Salesdepartment_text__c == '5.华东' || loginUser.Salesdepartment_text__c == '6.华南')) {
            //fy 20220512
            if (loginUser != null && String.isNotBlank(loginUser.Salesdepartment_text__c) && obsflag) {
 
                // obsflag = true;
                // String obsap_group_id = System.Label.obsap_group_opp;
                // List<GroupMember> members =  [SELECT Id, GroupId, UserOrGroupId FROM GroupMember where GroupId = :obsap_group_id];
                // system.debug('members++'+members);
                // if (members != null && members.size() > 0) {
                //     for (GroupMember member : members) {
                        // irai_userids.add(member.UserOrGroupId);
                //     }
                // }
                irai_userids.add(System.Label.obsap_group_opp);
            }else{
                irai_userids.add(quo.IraiUser__c);
            }
            // 把委托上绑定的人加到list里
            //20220512 lt add
            // Map<String,String> iuMap = new Map<String,String>();
            // for(String iu : irai_userids){
            //     iuMap.put(iu,iu);
            // }
            // if(!iuMap.containsKey(quo.IraiUser__c)){
            //     irai_userids.add(quo.IraiUser__c);
            // } 
            //irai_userids.add(quo.IraiUser__c);
            // Task[] tasks = [select Id,Subject,OwnerId,Description,ActivityDate,QuoteIraiId__c
            //                 from Task
            //                 where QuoteIraiId__c = :quoId and OwnerId = :quo.IraiUser__c];
            Task[] tasks = [select Id,Subject,OwnerId,Description,ActivityDate,QuoteIraiId__c
                            from Task
                            where QuoteIraiId__c = :quoId and OwnerId in :irai_userids];
            //DB202301106714 【报价委托改善】OBSAP通知邮件发送邮箱修改 fy start      
            List<String>  HeadquartersArray= quo.Headquarters__c.split('\\.');
            String Headquarters = '';
            if(HeadquartersArray.size()>0){
                Headquarters = HeadquartersArray.size()>=2 ? HeadquartersArray[1]:HeadquartersArray[0];
            }
            // String todoSubject = '报价委托:' + quo.IraiSubject__c;
            String todoSubject = Headquarters+'报价委托:' + quo.IraiSubject__c;
            //DB202301106714 【报价委托改善】OBSAP通知邮件发送邮箱修改 fy end
            // 20230104 lt DB202212427301 start
            if(quo.Urgent__c){
                todoSubject = '【紧急】' + todoSubject;
            }
            
            // 20230104 lt DB202212427301 end
            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 + '%';
            }
            // SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy start
            todoSubject += quo.cancelMultiyearInsurance__c=='不要' ?',取消多年保':',需要多年保';
            // if (quo.cancelMultiyearInsurance__c=='不要') {
            //     todoSubject += ',取消多年保';
            // }else{
            //     todoSubject += ',需要多年保';
            // }
            // SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy end
            // 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;
            // }
            List<String> new_task_users = new List<String>();
            //DB202301106714 【报价委托改善】OBSAP通知邮件发送邮箱修改 fy start
            List<String> taskIdL = new List<String>();
            //DB202301106714 【报价委托改善】OBSAP通知邮件发送邮箱修改 fy end
            if (tasks.size() > 0) {
                List<String> task_users = new List<String>();
                for (Task task : tasks) {
                    task_users.add(task.OwnerId);
                    //DB202301106714 【报价委托改善】OBSAP通知邮件发送邮箱修改 fy start
                    taskIdL.add(task.Id);
                    //DB202301106714 【报价委托改善】OBSAP通知邮件发送邮箱修改 fy end
                    task.Subject = todoSubject;
                    task.Description = description;
                    task.ActivityDate = Date.today();
                }
                //DB202301106714 【报价委托改善】OBSAP通知邮件发送邮箱修改 fy start
                // Database.DMLOptions dmlo = new Database.DMLOptions();
                // dmlo.EmailHeader.triggerUserEmail = true;
                // Database.update(tasks, dmlo);
                update tasks;
                if(taskIdL.size()>0){
                    sendEmail(todoSubject,descriptionsendEmailp,descriptionsendEmailbody,taskIdL[0],Headquarters);
                }
                //DB202301106714 【报价委托改善】OBSAP通知邮件发送邮箱修改 fy end
                for (String uid : irai_userids) {
                    if (!task_users.contains(uid)) {
                        new_task_users.add(uid);
                    }
                }
 
            } else {
                new_task_users = irai_userids;
            }
            if (new_task_users.size() > 0) {
                List<Task> new_tasks = new List<Task>();
                for (String uid : new_task_users) {
                    Task new_task = new Task();
                    new_task.Subject = todoSubject;
                    new_task.OwnerId = uid;
                    new_task.Description = description;
                    new_task.ActivityDate = Date.today();
                    new_task.QuoteIraiId__c = quoId;
                    // 20230109 lt DB202212427301 start
                    if(quo.Urgent__c){
                        new_task.Priority = '高';
                    }
                    // 20230109 lt DB202212427301 start
 
                    new_tasks.add(new_task);
                }
                system.debug('new_tasks++'+new_tasks);
                //DB202301106714 【报价委托改善】OBSAP通知邮件发送邮箱修改 fy start
                // Database.DMLOptions dmlo = new Database.DMLOptions();
                // dmlo.EmailHeader.triggerUserEmail = true;
                // Database.insert(new_tasks, dmlo);
                insert new_tasks;
                sendEmail(todoSubject,descriptionsendEmailp,descriptionsendEmailbody,new_tasks[0].Id,Headquarters);
                //DB202301106714 【报价委托改善】OBSAP通知邮件发送邮箱修改 fy end
            }
            // obsap 委托人按公共小组区分,检索数量增加 2022-05-09 ssm end
            
            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.Urgent__c = quo.Urgent__c;     //20230104 lt DB202212427301 shart
            //报价委托状态更新  已经委托
            qi.QuoteIrai_Status__c = '已经委托';
            //DB202211607582 fy 【报价委托】报价委托页面需求 start
            qi.EntrustmentDate__c = Date.today();
            //DB202211607582 fy 【报价委托】报价委托页面需求 end
            update qi;
 
            if(String.isNotBlank(quoId)){
                // CHAN-BJQ4VZ 精琢技术 2019/12/11 Start
            //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy  Noteplus__c
            //SWAG-CF589P【委托】【P:OBSAP】报价委托相关新需求评估 fy Lead__c,Opportunity__c,
                quo =[ SELECT Id,Name,Cancel_Decide__c,CreatedDate, PriceRefreshDate__c,Quote_Print_Date__c,//obsap 新增经销商1字段 fy satrt Agency1_entrust__c,SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy start cancelMultiyearInsurance__c,
                        Quote_Date__c,QuoteToName__c,Quote_Expiration_Date__c,Quote_Comment__c,Tender_information__c,Agency1_entrust__c,Noteplus__c,Lead__c,Opportunity__c,cancelMultiyearInsurance__c,
                        TOTAL__c,Discount__c,Pricing__c,Preferential_Trading_Price__c,Contract__c,LastIraiUser__c,MultiYearWarrantyTotalPrice__c,QuoteTotal_Page__c,Estimation_List_Price__c,Agency2_entrust__c,//DB202302464682【报价委托】报价委托改善224 fy
                        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
                        , urgent__c  //20230104 lt DB202212427301
                        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 = '邮件发送完成。';
            // SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy start
            this.Save_button=true;
            //XLIU-CHY4KW 20220907 lt start  --- 报价委托发送邮件成功之后 反向更新意向  报价委托字段为1
            Lead lea = new Lead();
            if(String.isNotBlank(leadid)){
                lea.Id = leadid;
                lea.OfferToEntrust__c = 1;
                //20230227 lt DB202302251962 start
                List<Lead> leadlist = [select Id,Firsttime_Quote_Irai__c from Lead where Id = :leadid];
                System.debug('lt123日期1'+ leadlist[0].Firsttime_Quote_Irai__c);
                System.debug('lt123日期2'+ lea.Firsttime_Quote_Irai__c);
                if(leadlist.size() > 0){
                    if(leadlist[0].Firsttime_Quote_Irai__c == null){
                        lea.Firsttime_Quote_Irai__c = Date.today();
                    }
                }
                //20230227 lt DB202302251962 end
                update lea;
            }
            //XLIU-CHY4KW 20220907 lt end  
 
            pageArrange();
            //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy start
            // if(quo.Note__c!=''){
            if(String.isNotBlank(quo.Note__c)){
                system.debug('===555==='+quo.Note__c.split('\r\n'));
                List<String> str=quo.Note__c.split('\r\n');
                if(str.size()==1){
                    quo.Note__c=''; 
                }else{
                    quo.Note__c=str[1]; 
                }
            }
            //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy end
            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)){
            //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy  Noteplus__c
            //SWAG-CF589P【委托】【P:OBSAP】报价委托相关新需求评估 fy Lead__c,Opportunity__c,
            QuoteIrai__c getnote = [ SELECT Id,Name,Note__c,Noteplus__c,Lead__c,Opportunity__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 (String.isNotBlank(this.oppid) && !is_changed_opp){
            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
        //SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 start
        String resalt = assdproductCheck();
        if(resalt!='OK'){
            errorflg = true;
            errormessage = resalt ;
            return false;
        }
        //SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 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 //SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 start Product2__r.Is_DangerousChemicals__c
                        Select Id,Product2__r.SFDA_Status__c,Product2__r.Name,Product2__c,Product2__r.LastbuyProductFLG__c,Product2__r.Is_DangerousChemicals__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>();//obsap 新增经销商1字段 fy satrt Agency1_entrust__c,SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy start cancelMultiyearInsurance__c,
            //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy  Noteplus__c
            //SWAG-CF589P【委托】【P:OBSAP】报价委托相关新需求评估 fy Lead__c,Opportunity__c,
            qs = [select Id,Account__c,Agency_Hospital_Link__c,Name,IraiUser__c,IraiSubject__c,Tender_information__c,Agency1_entrust__c,Noteplus__c,Lead__c,Opportunity__c,cancelMultiyearInsurance__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,Agency2_entrust__c,//DB202302464682【报价委托】报价委托改善224 fy
                Contract__c,Print_HP_Name__c,Quote_Expiration_Date__c,Quote_Comment__c,IraiName__c,QuoteIrai_Status__c,QuoteProportion__c,Note__c,IraiComment__c
                , urgent__c  //20230104 lt DB202212427301
                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;
        //obsap 新增经销商1字段 fy staty
        q.Agency1_entrust__c = quo.Agency1_entrust__c;
        //obsap 新增经销商1字段 fy staty
        //DB202302464682【报价委托】报价委托改善224 fy start
        q.Agency2_entrust__c = quo.Agency2_entrust__c;
        //DB202302464682【报价委托】报价委托改善224 fy end
        // SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy start
        q.cancelMultiyearInsurance__c = quo.cancelMultiyearInsurance__c;
        // SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy end
        q.QuoteProportion__c = quo.QuoteProportion__c;
        q.CurrencyIsoCode = quo.CurrencyIsoCode;
        //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy start
        q.Noteplus__c=quo.Noteplus__c;
        if(!String.isBlank(quo.Note__c)){
            q.Note__c = quo.Noteplus__c+'\r\n'+quo.Note__c;
        }else {
            q.Note__c = quo.Noteplus__c;
        }
        
        System.debug('===222==='+quo.Noteplus__c+'  ===333===   '+q.Note__c);
        //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy end
        // 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;
        q.Urgent__c = quo.Urgent__c;   //20230104 lt DB202212427301 shart
        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
        //SWAG-CF589P【委托】【P:OBSAP】报价委托相关新需求评估 fy start
        q.Lead__c=leadid;
        q.Opportunity__c=oppid;
        //SWAG-CF589P【委托】【P:OBSAP】报价委托相关新需求评估 fy end
        if (quoId==null){
            insert q;
        }else{
            update q;
        }
        //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy  Noteplus__c
        //SWAG-CF589P【委托】【P:OBSAP】报价委托相关新需求评估 fy Lead__c,Opportunity__c,
        quo =[ SELECT Id,Name,Cancel_Decide__c,CreatedDate, PriceRefreshDate__c,Quote_Print_Date__c,//obsap 新增经销商1字段 fy satrt Agency1_entrust__c,SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy start cancelMultiyearInsurance__c,
                    Quote_Date__c,QuoteToName__c,Quote_Expiration_Date__c,Quote_Comment__c,Tender_information__c,Agency1_entrust__c,Noteplus__c,Lead__c,Opportunity__c,cancelMultiyearInsurance__c,Headquarters__c,//DB202301106714 【报价委托改善】OBSAP通知邮件发送邮箱修改 fy Headquarters__c
                    TOTAL__c,Discount__c,Pricing__c,Preferential_Trading_Price__c,Contract__c,LastIraiUser__c,MultiYearWarrantyTotalPrice__c,QuoteTotal_Page__c,Estimation_List_Price__c,Agency2_entrust__c,//DB202302464682【报价委托】报价委托改善224 fy
                    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
                    , urgent__c  //20230104 lt DB202212427301
                    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;
            
        }
        //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy start
        // if(quo.Note__c!=''){
        if(String.isNotBlank(quo.Note__c)){
            system.debug('===444==='+quo.Note__c.split('\r\n'));
            List<String> str=quo.Note__c.split('\r\n');
            if(str.size()==1){
                quo.Note__c=''; 
            }else{
                quo.Note__c=str[1]; 
            }
        }
        //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy end
        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;
  }
 //SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 start
  //阿西赛多验证
  public String assdproductCheck(){
    Boolean falg = false;
    String str = 'OK';
    List<Product2> axsdQuoteIItem = new List<Product2>();
    List<Product2> QuoteIItem = new List<Product2>();
    List<Id> Product2List = new List<Id>();
    System.debug('activities111111!!!'+activities);
    for(QELine aaa :activities){
     if(String.isNotBlank(aaa.pageObject.Product2__c)){
        Product2List.add(aaa.pageObject.Product2__c);
     }
    }
    List<Product2> productlist = [select id,Is_DangerousChemicals__c from Product2 where id in:Product2List];  
    for(Product2 pro :productlist){
        System.debug('Is_DangerousChemicals__c111111!!!'+pro.Is_DangerousChemicals__c);
        if(pro.Is_DangerousChemicals__c){
            falg = true;
            axsdQuoteIItem.add(pro);
        }else if(!pro.Is_DangerousChemicals__c){
            QuoteIItem.add(pro);
        }
    }
    if(QuoteIItem.size() > 0 && axsdQuoteIItem.size() > 0){
        str = '阿西赛多产品不能和其他产品一起报价';
    }else{
        if(falg){
            str = OpportunityWebService.checkDangerItem(quo.Agency1_entrust__c);
        }
    }
    return str;
  }
  //SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 end
  //DB202301106714 【报价委托改善】OBSAP通知邮件发送邮箱修改 fy start
  private static void sendEmail(String title , String bodyTextp , String bodyTextbody,String TaskId,String Headquarters) {
    system.debug('bodyText++'+bodyTextp+bodyTextbody);
    bodyTextbody = bodyTextbody.replaceFirst('\r\n', '');
    List<Task> TaskList = [select Id,Request_staff__c,ActivityDate,Priority from Task where Id =:TaskId];
    Task Taskobj = TaskList[0];
    //20230116 fy start
    String bodyTextbu ='新建任务';
    bodyTextbu += '\r\n\r\n'+'到:OBSAP成员';
    if(String.isNotBlank(Headquarters)){
        Headquarters='('+Headquarters+')';
    }
    bodyTextbu += '\r\n'+Taskobj.Request_staff__c +Headquarters+' 已分配给您以下新建任务:';
    bodyTextbu += '\r\n'+'主题: '+title;
    bodyTextbu += '\r\n'+'结束期限: '+Taskobj.ActivityDate;
    bodyTextbu += '\r\n'+'优先级: '+Taskobj.Priority;
    bodyTextbu += '\r\n' +'评论:<pre>'+bodyTextp+'</pre>';
    bodyTextbu += bodyTextbody;
    bodyTextbu += '\r\n\r\n' +'有关更多详细信息,请单击以下链接:'+'\r\n\r\n'+'https://ocsm.my.salesforce.com/'+Taskobj.Id;
    bodyTextbu = bodyTextbu.replace('\r\n', '<br/>');
    bodyTextbu = bodyTextbu.replaceFirst('<br/>', '');
    System.debug('bodyTextbu+++'+bodyTextbu);
    //20230116 fy end
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    List<String> toAddresses = new List<String>();
    toAddresses.add(System.Label.OBSAP_Group_Mail);
    // toAddresses.add('fuyu@prec-tech.com');
    //收件人地址
    mail.setToAddresses(toAddresses);
    String Detection = System.Label.OBSAP_QuoteIrai_Mail_Detection;
    if(!Detection.equals('invalid') && String.isNotBlank(Detection)){
        String[] toccAddresses = System.Label.OBSAP_QuoteIrai_Mail_Detection.split(',');
        //抄送人地址
        mail.setCcAddresses(toccAddresses);
    }
    //邮件主题
    mail.setSubject(title);
    //内容的编码
    mail.setCharset('UTF-8');
    //邮件内容
    mail.setHtmlBody(bodyTextbu);
    //使用电子邮件模板设置对象id
    // mail.setTargetObjectId(TaskId);
    //设置电子邮件模板id
    // EmailTemplate temp =  [
    //     SELECT Id, Name, Subject, HtmlValue, Body, BrandTemplateId
    //     FROM EmailTemplate
    //     WHERE DeveloperName = 'Task_To_Queue'
    //     LIMIT 1
    // ];
    // mail.setTemplateId(temp.Id);
    //发送邮件
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
//DB202301106714 【报价委托改善】OBSAP通知邮件发送邮箱修改 fy end
 
    // 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; }
    //obsap 新增经销商1字段 fy
    public Decimal SalesCalculation1 { 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
        
        // SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy start
        public String CanNotCancelledGurantee { get; set; }
        // SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy 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
            // SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy start
            this.CanNotCancelledGurantee = qli.CanNotCancelledGurantee__c?'true':'false';
            // SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy 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;
        }
    }
}