liuyn
2024-03-11 a87f1c3df03078814ee97ad0c8ac200a232419e9
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
// FIXME 見積もり商品の Asset_Model_No__c ですが、数式になっています。トランザクションデータとして、項目を持つべきかと思います。by katsu 20130216
// 商談商品のId__c を PricebookEntry.Product2Idに変更すべき
// 見積もり可否 ですが、保存時みていますが、Sales_Possibilityを見ないですか?いいえ、js側で見ています
public class ConsumableSampleApplyController {
 
    public Id quoId {get;set;}
    public Boolean productStatusUpdated {get;set;}               // 状態更新、{!$Label.Status_Update} を押下したかどうか
    public Boolean changedAfterPrint {get;set;}                  // true の場合、画面に confirm メッセージが表示します。quoIdを新しいinsert。判定はjsにて実施
 
    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 ConsumableSample__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;
    
    public ConsumableSampleApplyController() {
        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
        changedAfterPrint = false;
        productStatusUpdated = false;
    }
 
    public ConsumableSampleApplyController(ApexPages.StandardController controller) {
    }
 
    public PageReference init() {
        system.debug('============start init==============');
        errorflg = false;
        
        if (String.isBlank(ApexPages.currentPage().getParameters().get('completion')) == false) {
            if (ApexPages.currentPage().getParameters().get('completion') == '1') {
                errorflg = true;
                errorMessage = System.Label.Message_002;
            } else if (ApexPages.currentPage().getParameters().get('completion') == '2') {
                errorflg = true;
                errorMessage = '审批提交成功。';
            }
        }
        
        loginUser = [select Id from User where Id = :Userinfo.getUserId()];
        
        //Quote
        quo = new ConsumableSample__c();
 
        //quoid
        if (quoId==null){
            quoId = System.currentPageReference().getParameters().get('copyid');
            if (quoId==Null){
                quoId = System.currentPageReference().getParameters().get('id');
            }
        }
 
        //Quote
        Integer i;
        if (quoId==null){
            quo.CurrencyIsoCode = 'CNY';
            quo.Process_Status__c = '草案中';
            quo.PIC__c = loginUser.Id;
            //新規リストコントローラの取得
            if (activities==null){
                activities = new List<QELine>();
                activitiesbk = new List<QELine>();
                for (i=0;i<150;i++){
                    QELine active_activity = new QELine(i);
                    activities.add(active_activity);
                }
            }
        }else{
            List<ConsumableSample__c> quoList = 
                [SELECT Id,Name,CurrencyIsoCode,Process_Status__c,Contact__c,Account__c,Expect_Arrive_Date__c,Expect_Use_Date__c,Purpose__c,Reason__c,
                        PIC__c,CreatedDate,Contact__r.Hospital_name__c,Contact__r.AccountId
                   FROM ConsumableSample__c 
                  Where Id =:quoId];
            List<ConsumableSampleLineItem__c> items = 
                [Select Id,Asset_Model_No__c,Serial_Lot__c,SFDA_Status__c,Name__c,
                        Qty_Unit__c,Quantity__c,Product2__r.SFDA_Status__c,ProductCode__c,ListPrice__c,
                        Product2__r.Sales_Possibility__c,Product2__r.Name,Product2__c,Product2__r.Asset_loaner_category__c,Product2__r.Packing_list_manual__c
                   From ConsumableSampleLineItem__c 
                  where ConsumableSample__c = :quoId 
                  Order by Item_Order__c, Id];
            String copyQuoId = System.currentPageReference().getParameters().get('copyid');
            
            if (copyQuoId == null) {
            } else {
                // copyの場合、quoIdをnullに戻す
                quoId = null;
            }
            if (quoList.size() > 0){
                if (copyQuoId == null) {
                    quo = quoList[0];
                } else {
                    quo.CurrencyIsoCode = 'CNY';
                    quo.Process_Status__c = '草案中';
                    quo.PIC__c = loginUser.Id;
                    quo.Contact__c = null;
                    quo.Account__c = null;
                    quo.Expect_Arrive_Date__c = null;
                    quo.Expect_Use_Date__c = null;
                    quo.Purpose__c = '';
                    quo.Reason__c = '';
                }
            }
 
            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 (ConsumableSampleLineItem__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<150;j++){
                    c = new QELine(j);
                    activities.add(c);
                }
                //マスタ最新情報の取得
                settingProduct2();
            }else{
                activities = new List<QELine>();
                for (i=0;i<150;i++){
                    QELine active_activity = new QELine(i);
                    activities.add(active_activity);
                }
            }
        }
 
        //--Savebutton
        Save_button = true;
        pdf_button = true;
        if (quo.Process_Status__c == '草案中' || quo.Process_Status__c == '不批准') {
            Save_button = false;
        }
        if (quo.Process_Status__c == '批准') {
            pdf_button = false;
        }
 
        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>150){
            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です。
                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,Serial_Lot_No__c,Asset_loaner_category__c,Sales_Possibility__c,Estimation_Entry_Possibility__c,
                        SFDA_Status__c,Qty_Unit__c,BSSCategory__c,Packing_list_manual__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 = ConsumableSampleLineItem__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')) {
                            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.Serial_Lot_No__c, prd.Asset_loaner_category__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.Packing_list_manual__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.Serial_Lot_No__c, prd.Asset_loaner_category__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.Packing_list_manual__c);
                                } else {
                                    continue;
                                }
                            }
                        } else {
                            continue;
                            // c = new QELine(i, pbe.Id, prd.Asset_Model_No__c, prd.Serial_Lot_No__c, prd.Asset_loaner_category__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============================================================
 
    //approval button
    public PageReference approvalBtn(){
        system.debug('○○○○○○○○○○○○○○○Welcome to approvalButton!!');
        
        List<String> productidList = 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);
                }
            }
        }
        if (productidList.size() <= 0) {
            errorflg = true;
            errorMessage = '没有选择产品。';
            pageArrange();
            return null;
        }
        
        Savepoint sp = Database.setSavepoint();
        try {
            //データチェック
            if (dataCheck() == false){
                return null;
            }
            if (dataEntry() == false){
                return null;
            }
            // 承認プロセス
            Approval.ProcessSubmitRequest psr = new Approval.ProcessSubmitRequest();
            psr.setObjectId(quoId);
            Approval.ProcessResult submitResult = Approval.process(psr);
            
            //msg
            errorflg = true;
            errorMessage = '审批提交成功。';
            //return null;
            PageReference pageRef = new PageReference('/apex/ConsumableSampleApply?id=' + this.quoId + '&completion=2');
            pageRef.setRedirect(true);
            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;
    }
 
    //Save button
    public PageReference Save(){
 
        errorflg = false;
        errormessage = null;
        Savepoint sp = Database.setSavepoint();
        try {
            //データチェック
            if (dataCheck() == false){
                return null;
            }
            if (dataEntry() == false){
                return null;
            }else{
                //msg
                errorflg = true;
                errorMessage = System.Label.Message_002;
                //return null;
                PageReference pageRef = new PageReference('/apex/ConsumableSampleApply?id=' + this.quoId + '&completion=1');
                pageRef.setRedirect(true);
                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;
    }
 
    //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){
                return null;
            }else{
                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(){
        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;
                } else {
system.debug('○○○○○○○○○○○○Welcome to pageArrange Asset_Model=[' + a.Asset_Model + ']');
                }
            }
        }
    }
 
    public boolean dataCheck(){
        system.debug('○○○○○○○○○○○○Welcome to dataCheck class!!○○○○○○○○○○○○');
        errorflg = false;
        errormessage = null;
        Boolean error = false;
        List<String> product2Ids = New List<String>();
        if (activities.size()>0){
            for (QELine a:activities){
                if (String.isBlank(a.PageObject.Product2__c) == false) {
                    product2Ids.add(a.PageObject.Product2__c);
                }
            }
            
            prd2LatestValMap = new Map<Id, Product2>();
            for (Product2 prd2: [Select Id, Estimation_Entry_Possibility__c, SFDA_Status__c From Product2 Where Id IN :product2Ids]) {
                if (prd2.Estimation_Entry_Possibility__c != '○') {
                    error = true;
                }
                prd2LatestValMap.put(prd2.Id, prd2);
            }
            
            if (error == true){
                if (quoId != null) {
                    Map<String,ConsumableSampleLineItem__c> itemmap = new Map<String,ConsumableSampleLineItem__c>();
                    for (ConsumableSampleLineItem__c item : [
                        Select Id,Product2__r.SFDA_Status__c,Product2__r.Name,Product2__c
                        From ConsumableSampleLineItem__c where ConsumableSample__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.Contact__c == null){
            quo.Contact__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
        //契約内訳、印刷病院名称、見積有効期限日、見積表記コメント
        ConsumableSample__c q = New ConsumableSample__c();
        
        if (changedAfterPrint) {
            quoId = null;
        }
        if (quoId==null){
            q = New ConsumableSample__c();
        }else{
            List<ConsumableSample__c> qs = New List<ConsumableSample__c>();
            qs = [SELECT Id,Name,CurrencyIsoCode,Contact__c,Account__c,Expect_Arrive_Date__c,Expect_Use_Date__c,Purpose__c,Reason__c,
                         PIC__c,CreatedDate,Contact__r.Hospital_name__c
                    FROM ConsumableSample__c 
                   Where Id =:quoId];
            if (qs.size()>0){
                q = qs[0];
            }
        }
        
        List<Contact> cont = [select Id,AccountId from Contact where Id = :quo.Contact__c];
        String accid = null;
        if (cont.size() > 0) {
            accid = cont[0].AccountId;
        }
 
        q.CurrencyIsoCode = quo.CurrencyIsoCode;
        q.PIC__c = quo.PIC__c;
        if (quoId==null){
            q.Contact__c = quo.Contact__c;
        }
        q.Account__c = accid;
        q.Expect_Arrive_Date__c = quo.Expect_Arrive_Date__c;
        q.Expect_Use_Date__c = quo.Expect_Use_Date__c;
        q.Purpose__c = quo.Purpose__c;
        q.Reason__c = quo.Reason__c;
 
        if (quoId==null){
            insert q;
        }else{
            update q;
        }
 
system.debug('○○○○○Save1○○○○○');
 
        //QuoteLineItem;
        List<ConsumableSampleLineItem__c> qlist = New List<ConsumableSampleLineItem__c>();
        qlist=[Select Id From ConsumableSampleLineItem__c Where ConsumableSample__c =:quoId];
        if (qlist.size()>0){
            //delete
            delete qlist;
        }
 
        //QuoteLineItem--------------------------------------------
        //製品型番、品目コード、SFDAステータス、品目名、ListPrice、数量
        //価格、単位、小計、OCM売上予測金額(税抜)、価格表
        qlist = New List<ConsumableSampleLineItem__c>();
        //Sap送信,Printに合わせて1~
        Integer i=1;
system.debug('○○○○○'+activities.size()+'○○○○○');
        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()しますか?意味不明。
                        ConsumableSampleLineItem__c ql = s.pageObject.clone();
                        ql.ConsumableSample__c = q.Id;
                        ql.ListPrice__c = s.ListPrice_Page;
                        ql.SFDA_Status__c = prd2LatestValMap.get(s.pageObject.Product2__c).SFDA_Status__c;
                        //並び順
                        ql.Item_Order__c = i;
                        qlist.add(ql);
                        
                        activitiesbk.add(new QELine(ql, s.lineNo, null));
                    }
                }
                i++;
            }
            insert qlist;
 
        }
 
        //保存時引合Pageに戻らない処理とした為にQuoteIdをここでセット
        if (quoId==null){
            quoId = q.Id;
            
        }
 
        return true;
    }
    
    public class QELine {
        public Integer lineNo { get; set; }                                // 画面の順序
        public String Asset_Model {get;set;}
        public String Serial_Lot {get;set;}
        public String Asset_loaner_category {get;set;}
        public String Sales_Possibility {get;set;}                         // 販売可否○×判断用、使ってないようです。TODO 削除
        public ConsumableSampleLineItem__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; }
        public Decimal Packing_list_manual { get; set; }
 
        // TODO ほんとうはいらない、使うところのロジックを修正しなければいけない、削除するようにしたいです。
        public QELine(Integer i) {
            pageObject = New ConsumableSampleLineItem__c();
            this.lineNo = i;
        }
        // tmp 直接使う場合のパターン
        public QELine(QELine tmp, Integer i) {
            pageObject = tmp.pageObject;
            this.lineNo = i;
            this.Asset_Model = tmp.Asset_Model;
            this.Serial_Lot = tmp.Serial_Lot;
            this.Asset_loaner_category = tmp.Asset_loaner_category;
            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;
            this.Packing_list_manual = tmp.Packing_list_manual;
        }
        public QELine(ConsumableSampleLineItem__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.Serial_Lot = qli.Serial_Lot__c;
            this.Asset_loaner_category = qli.Product2__r.Asset_loaner_category__c;
            this.ListPrice_Page = qli.ListPrice__c;
            this.ListPriceTotal_Page = qli.Quantity__c * qli.ListPrice__c;
            this.Packing_list_manual = (qli.Product2__r.Packing_list_manual__c == null || qli.Product2__r.Packing_list_manual__c <= 0) ? 1 : qli.Product2__r.Packing_list_manual__c;
        }
        
        // TODO Subtotal__c、以前のロジックを確認
        public QELine(Integer i, String PricebookEntryId, String Asset_Model, String Serial_Lot, String Asset_loaner_category, 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 Packing_list_manual_c) {
            pageObject = New ConsumableSampleLineItem__c();
            pageObject.Quantity__c = Quantity;
            this.lineNo = i;
            this.Asset_Model = Asset_Model;
            this.Serial_Lot = Serial_Lot;
            this.Asset_loaner_category = Asset_loaner_category;
            this.Sales_Possibility = Sales_Possibility_c;
            pageObject.Product2__c = Id_c;
            pageObject.SFDA_Status__c = SFDA_Status_c;
            pageObject.Name__c = Name_c;
            this.ListPrice_Page = ListPrice_c;
            this.ListPriceTotal_Page = Quantity * ListPrice_c;
            //this.Cost_c = Cost_c;
            // TODO katsu なぜここ > 0 の判断はいらない?
            //this.Cost_Subtotal_c = Cost_c * Quantity;
            this.Packing_list_manual = (Packing_list_manual_c == null || Packing_list_manual_c <= 0) ? 1 : Packing_list_manual_c;
        }
    }
 
   
}