高章伟
2023-10-30 e48cd34b21a3841cac102402c15903e8e075ad02
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
import { LightningElement,api,track,wire } from 'lwc';
import { CurrentPageReference } from 'lightning/navigation';
import initData from '@salesforce/apex/LexNewAndEditRepairPIPLController.initData';
import getContactByAWSId from '@salesforce/apex/LexNewAndEditRepairPIPLController.getContactByAWSId';
import EncryptUpdate from '@salesforce/apex/LexNewAndEditRepairPIPLController.EncryptUpdate';
import { NavigationMixin } from 'lightning/navigation';
import { AWSService } from 'c/piUtils';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import { decodeDefaultFieldValues } from "lightning/pageReferenceUtils";
import lexPIPLCustomStyle from '@salesforce/resourceUrl/lexPIPLCustomStyle'
import { loadStyle } from 'lightning/platformResourceLoader';
import REPAIR from '@salesforce/schema/Repair__c';
import { conmentCancel } from "c/lexPIPLConmentMethods";
// Add By Li Jun 20231025 Start
import LexRecordNotCreateable  from '@salesforce/label/c.LexRecordNotCreateable';
import LexNotCreateNote  from '@salesforce/label/c.LexNotCreateNote';
const customLabel = {
    LexRecordNotCreateable,
    LexNotCreateNote
}
// Add By Li Jun 20231025 End
 
export default class LexNewAndEditRepairPIPL extends NavigationMixin(LightningElement) {
    sobjectType = 'Repair__c';
    modifyFieldArray = ['Incharge_Staff_Contact__c', 'Delivered_Product__c'];
    defaultValueArray = ['Hospital__c', 'Department_Class__c', 'Account__c', 'Dealer__c', 'Incharge_Staff_Contact__c', 'Incharge_Staff__c', 'RepairSubOrder__c', 'On_Call_ID__c', 'QIS_ID__c', 'InsReport__c', 'Rental_Apply_Equipment_Set_Detail__c'];
    cloneFieldArray = ['AWS_Data_Id__c', 'SAP_condition__c', 'DOJ_Status__c', 'DW_Sign__c', 'Incharge_Staff__r.Id', 'URF_Reapir__c', 'Recall_Correspondence__c', 'Day_later_30__c', 'Dealer__r.Id', 'Status__c', 'URFLimitSerial__c', 'Maintenance_Contract__r.Id', 'FSE_ApplyForRepair_time__c', 'Delivered_Product__r.Id', 'Asset_Owner__c', 'State_Hospital__c', 'is_aohui_product__c', 'Sales_Dept_HP__c', 'RCCD__c', 'Quick_Repair_Sign__c', 'RepairSource__c', 'FSE_State__c', 'VM_Maintenance_Contract__c', 'Maintenance_Contract__c', 'NewProductGuarante_Txt__c', 'Number_of_EffectiveContract__c', 'Detailed_Address__c', 'Status1__c', 'Rental_Apply_Equipment_Set_Detail__c', 'Rental_Apply_Equipment_Set_Detail_Id__c', 'Latest_Collect_Date_Priority__c', 'if_Rental_Apply__c', 'Offer_Rental_New__c', 'ProduceCompany_hand__c', 'CFDA_No_Hand__c', 'MBC_AwareDate__c', 'InsReport__c', 'QIS_ID__c', 'On_Call_ID__c', 'RepairSubOrder__c', 'ProductFailureRelated__c', 'Delay15Min__c', 'ProblemOccurredSelect__c', 'Repair_Source__c', 'Failure_Occurrence_Date__c', 'MaintenanceContractType__c', 'OperationOrExaminationName__c', 'WhatProject__c', 'FailureQInHospital__c', 'ReportAdverseEvents__c', 'InformationFrom__c', 'AfterFailureInformation__c', 'ProblemOccurred__c', 'SupportingProducts__c', 'ifDeadHurt__c', 'UseFailProductFinish__c', 'DelayReportReason__c', 'BreakORFallOff__c', 'DateReceiptQuestions__c', 'DeliveryLogisticsAnnotation__c', 'DeliveryLogisticsNo__c', 'engineerSendDate__c', 'DeliveryLogisticsMode__c', 'RepairApplicantDepartment__c', 'RepairApplicantHospital__c', 'RepairApplicant__c', 'Repair_Detail__c', 'Returns_Product_way__c', 'work_location_select__c', 'On_site_repair__c', 'SalesOfficeCode_selection__c', 'Incharge_Staff_Contact__c', 'Incharge_Staff__c', 'Dealer__c', 'RepairCostType__c', 'Account__c', 'Department_Class__c', 'Hospital__c', 'PaperRepairRequestNo__c', 'part_arrangement_complete__c', 'Repair_Shipped_Date__c', 'OCSMAdministrativeReportStatus__c', 'Incharge_Staff_Email__c', 'Name', 'HP_Name__c', 'Delivered_Product__c', 'Repair_Product_Serial_No__c', 'Service_Repair_No__c', 'Repair_Firstestimated_Date__c', 'Repair_Estimated_Date__c', 'RC_information__c', 'Id', 'OCSMAdministrativeReportNumber__c', 'OCSMAdministrativeReportDate__c', 'Aware_date__c', 'PAE_Determine__c', 'ETQ_UPLOAD_STATUS__c', 'AE_DetermineResult__c', 'PAE_DetermineAC__c', 'Repair_Inspection_Date__c', 'Contain_UseRSA__c']
    @track customLabel = customLabel;
    @api recordId;
    @wire(CurrentPageReference) pageRef;
    @track layout = [];
    @track labelMap = {};
 
    title;
    recordTypeId = '' 
    staticResource;
    staticResourceRepairSubOrder;
    AWSDataId = '';
    txId = '';
    contactId = '';
    contactAWSDataId = '';
    repairApplicantId = '';
    practitioner = '';
    hospitalId = '';
    accountId = '';
    retUrlId = '';
    searchType = '';
    isNewMode = false;
    isEditMode = false;
    isCloneMode = false;
    isClone = false;
    isLoading = false;
    isShowSearchAccount = false
    saveAndNew = false;
    sectionName = [];
    dataTypesMap = {};
    AWSToSobjectMap = {};
    recordData = {};
    AWSService;
    contactIdMap = {};
    pageStateMap = {};
    defaultValues = {};
    //特殊lookup字段处理
    searchFieldArray;
    searchWhere;
    searchField = 'Name';
    searchObjectType;
    @track iconName = "";
    fieldLabel = {};
    repairFields = {};
 
    @wire(getObjectInfo, { objectApiName: REPAIR })
    getRepairInfo({data,error}){
        if(data){
            this.fieldLabel = data.fields;
            this.labelMap ={
                'Incharge_Staff_Contact__c' : data.fields.Incharge_Staff_Contact__c.label,
                'Delivered_Product__c' : data.fields.Delivered_Product__c.label,
            };
            let fieldMap = Object.values(data.fields).map((fld) => {
                let { apiName, dataType } = fld;
                return { apiName, dataType };
            });
 
            fieldMap.forEach(field =>{
                this.dataTypesMap[field.apiName] = field.dataType;
            })
 
            let fields = data.fields;
            // 将字段的信息存储在 repairFields 对象中
            Object.keys(fields).forEach((fieldApiName) => {
                this.repairFields[fieldApiName] = {
                    label: fields[fieldApiName].label,
                    dataType: fields[fieldApiName].dataType
                    // 可以根据需要添加其他字段属性,如是否必填、是否唯一等
                };
            });
            console.log('repairFields = ' + JSON.stringify(this.repairFields))
        }
    }
 
    connectedCallback(){
        console.log('Repair ConnectedCallback');
        this.isLoading = true;
        loadStyle(this, lexPIPLCustomStyle);
        this.AWSService = new AWSService();
        if (this.pageRef && this.pageRef.state) {
            this.recordTypeId = this.pageRef.state.recordTypeId;
            this.isClone = this.pageRef.state.c__isClone;
            this.retUrlId = this.pageRef.state.retURL == null ? '' : this.pageRef.state.retURL;
            // let stateKeys = Object.keys(this.pageRef.state);
            // let states = this.pageRef.state;
            // stateKeys.forEach(state =>{
            //     if(state.includes('_lkid')){
            //         let newKey = state.replace('_lkid', '');
            //         newKey = newKey.substring(2);
            //         this.pageStateMap[newKey] = states[state];
            //     }
            // })
            console.log('this.recordTypeId = ' + this.recordTypeId);
            // 获取从其他页面带来的参数
            if (this.pageRef.state.defaultFieldValues) {
                this.defaultValues = decodeDefaultFieldValues(
                    this.pageRef.state.defaultFieldValues
                );
                console.log('this.contactAWSDataId = ' + this.contactAWSDataId);
            }
            console.log("defaultValues:", JSON.stringify(this.defaultValues));
        }
        if(this.recordId){
            this.isEditMode = true;
            this.title = '编辑修理';
        }else{
            this.title = '新建修理';
            if(this.isClone){
                this.title = '克隆修理';
                this.isCloneMode = true;
            }else{
                this.isNewMode = true;
            }
        }
 
 
        setTimeout(() => {
            this.init();
        }, 1000);
 
    }
 
    init(){
        let rid;
        if(this.isCloneMode){
            rid = this.pageRef.state.c__recordId;
        }else{
            rid = this.recordId
        }
        initData({
            'rid': rid,
            'recordTypeId': this.recordTypeId,
            'sobjectType': this.sobjectType,
            'RepairId' : this.retUrlId
        }).then((r) => {
            r = JSON.parse(JSON.stringify(r));
            if (r.status == 'Success') {
                let layout = JSON.parse(r.entity.layout);
                this.recordData = r.entity.data;
                this.AWSToSobjectMap = JSON.parse(JSON.stringify(r.entity.AWSToSobjectNonEncryptedMap));
                this.staticResource = JSON.parse(r.entity.staticResource);
                this.staticResourceV2 = JSON.parse(r.entity.staticResourceV2);
                this.staticResourceContact = JSON.parse(r.entity.staticResourceContact);
                this.staticResourceRepairSubOrder = JSON.parse(r.entity.staticResourceRepairSubOrder);
                if(r.entity.AWSDataId){
                    this.AWSDataId = r.entity.AWSDataId;
                }
                if(r.entity.recordTypeId){
                    this.recordTypeId = r.entity.recordTypeId;
                }
                this.sectionName = layout.map(s => s.label);
                layout = this.sortMetaLayouts(layout);
                layout.forEach(section =>{
                    section['showSection'] = false;
                    if(section['editHeading']){
                        section['showSection'] = true;
                    }
                    section['showLabel'] = false;
                    section.layoutColumns.forEach(column =>{
                        if(column.layoutItems.length != 0 && section['showLabel'] == false){
                            section['showLabel'] = true;
                        }
                        if(column.layoutItems){
                            column.layoutItems.forEach(item =>{
                                let filedName = item['field'];
                                item['isModify'] = false;
                                item['isDisable'] = item.behavior == 'Readonly' ? true : false;
                                item['isRequired'] = item.behavior == 'Required' ? true : false;
                                if(this.pageStateMap.hasOwnProperty(filedName)){
                                    let formatValue = this.assignValueFromUrl(filedName);
                                    if(formatValue){
                                        item['value'] = formatValue;
                                    }else{
                                        this.showToast('Error', '数据转换失败');
                                    }
                                }
                                if (this.isNewMode && this.defaultValues) {
                                    if(this.defaultValues[item['field']]){
                                        item["value"] = this.defaultValues[item["field"]];
                                    }
                                    if(filedName == 'Delivered_Product__c' ){
                                        item["value"] = this.defaultValues['AssetName'];
                                        this.contactIdMap[filedName] = this.defaultValues['Delivered_Product__c'];
                                    }
                                    if(filedName == 'RepairApplicant__c'){
                                        this.queryRepairApplicantName(this.defaultValues['AWSId']);
                                    }
                                    if(filedName == 'Exc_work_location__c'){
                                        item['value'] = this.defaultValues[filedName] == 'true'? true : false;
                                    }
                                    if(filedName == 'Offer_Rental_New__c'){
                                        item['value'] = this.defaultValues[filedName] == 'true'? true : false;
                                    }
                                    if(filedName == 'Hospital__c'){
                                        this.hospitalId = this.defaultValues[filedName];
                                    }
                                    if(this.defaultValues[filedName] && this.repairFields[filedName] && this.repairFields[filedName].dataType == 'Date'){
                                        item['value'] = new Date(new Date(this.defaultValues[filedName] + '').getTime() + (8 * 60 * 60 * 1000)).toISOString().substring(0,10);
                                    }
                                    if(this.defaultValues[filedName] && this.repairFields[filedName] && this.repairFields[filedName].dataType == 'DateTime'){
                                        item['value'] = new Date(new Date(this.defaultValues[filedName] + '').getTime() + (8 * 60 * 60 * 1000)).toISOString();
                                    }
                                }
                                // 与Contact或Asset关联,故采用自定义
                                if(this.modifyFieldArray.includes(item['field'])){
                                    item['isModify'] = true;
                                    item['isShowIcon'] = true;
                                    item['label'] = this.labelMap[filedName];
                                    let lookupName = filedName.slice(0, -1) + 'r';
                                    if(this.isEditMode || this.isCloneMode ){
                                        if(filedName == 'Delivered_Product__c'){
                                            item['value'] = this.recordData[lookupName] == null ? '' : this.recordData[lookupName].Name;
                                        }else{
                                            item['value'] = this.recordData[lookupName] == null ? '' : this.recordData[lookupName].LastName;
                                            this.contactAWSDataId = this.recordData[lookupName] == null ? '' : this.recordData[lookupName].AWS_Data_Id__c;
                                            //解密客户人员
                                            this.queryContactName(filedName);
                                        }
                                        //this.template.querySelector('[data-icon='+ filedName + ']').iconName = this.recordData[lookupName] == null ? 'utility:search' : 'utility:close';
                                        this.contactIdMap[filedName] = this.recordData[filedName] == null ? '' : this.recordData[filedName];
                                    }
                                }
                                //recordTypeId字段都应该是不可编辑的
                                if(item['field'] == 'RecordTypeId'){
                                    item['isDisable'] = true;
                                }
                                if((this.isEditMode || this.isCloneMode) && item['field'] == 'Hospital__c'){
                                    this.hospitalId = this.recordData[filedName] == null ? '' : this.recordData[filedName];
                                }
                                if((this.isEditMode || this.isCloneMode) && item['field'] == 'Account__c'){
                                    this.accountId = this.recordData[filedName] == null ? '' : this.recordData[filedName];
                                }
                                if(this.isCloneMode && filedName != 'Name' && filedName != 'Delivered_Product__c' && filedName != 'Status__c'){
                                    if(this.cloneFieldArray.includes(filedName)){
                                        item['value'] = this.recordData[filedName] == null ? '' : this.recordData[filedName];
                                    }
                                }
                            })
                        }
                        
                    })
                })
                this.layout = layout;
                //编辑
                if(this.isEditMode || this.isCloneMode){
                    //解密意向的加密字段
                    this.queryLeadFromAWSIFS();
                }
            } else {
                this.showToast('Error', r.Msg);
            }
            this.isLoading = false;
        })
    }
 
    // 重新排版layout
    sortMetaLayouts(layout){
        layout.forEach(s => {
            let c1 = (s.layoutColumns[0].layoutItems != null) ? s.layoutColumns[0].layoutItems : [];
            let c2 = [];
            if(s.layoutColumns.length > 1){
                c2 = (s.layoutColumns[1].layoutItems != null) ? s.layoutColumns[1].layoutItems : [];
            }
            else{
                s.layoutColumns.push({ "reserved": null, "layoutItems": [] });
            }
            let emptySpaceItem = {
                "width": null,
                "showScrollbars": null,
                "showLabel": null,
                "scontrol": null,
                "reportChartComponent": null,
                "page_x": null,
                "height": null,
                "field": null,
                "emptySpace": true,
                "customLink": null,
                "component": null,
                "canvas": null,
                "behavior": null,
                "analyticsCloudComponent": null
            }
            let maxSize = 0
            if(c1.length > c2.length){
                maxSize = c1.length;
                for(let i = 0; i < maxSize; i++){
                    if(c2.length == maxSize){
                        break;
                    }
                    c2.push(emptySpaceItem);
                }
            }else{
                maxSize = c2.length;
                for(let i = 0; i < maxSize; i++){
                    if(c1.length == maxSize){
                        break;
                    }
                    c1.push(emptySpaceItem);
                }
            }
            let tempList = [];
            let index = 0;
            for(let i = 0; i < maxSize; i++){
                tempList.push(c1[i]);
                if(tempList.length == maxSize){
                    s.layoutColumns[index].layoutItems = tempList;
                    tempList = [];
                    tempList.push(c2[i]);
                    index++;
                }else{
                    tempList.push(c2[i]);
                    if(tempList.length == maxSize){
                        s.layoutColumns[index].layoutItems = tempList;
                        tempList = [];
                        index++;
                    }
                }
            }
        })
        layout = [...layout];
        return layout;
    }
 
    //转换从URL带来的数据,作为参数填入对应字段
    assignValueFromUrl(filedName){
        let fieldType = this.dataTypesMap[filedName];
        let fieldValue = this.pageStateMap[filedName];
        let val
        // address, boolean, date, datetime, double, id, location, string, time
        if(string.isBlank(fieldValue)){
            val = null;
        }else if(fieldType == 'Boolean'){
            if(fieldValue == '1'){
                val = true;
            }else{
                val = boolean.valueOf(fieldValue);
            }
        }else if(fieldType == 'Date'){
            //注意时区问题
            if(date.parse(fieldValue) != NaN){
                val = date.parse(fieldValue);
            }else{
                val = date.valueOf(fieldValue);
            }
        }else if(fieldType == 'Datetime'){
            //注意时区问题
            if(datetime.parse(fieldValue) != NaN){
                val = datetime.parse(fieldValue);
            }else{
                val = datetime.valueOf(fieldValue);
            }
        }else if(fieldType == 'Double' || fieldType == 'Number'){
            val = decimal.valueOf(fieldValue.replace(',', ''));
        }else if(fieldType == 'Id' || fieldType == 'String'){
            val = fieldValue;
        }
        return val;
    }
 
    //解密客户人员
    queryContactName(filedName){
        let that = this;
        this.AWSService.query(this.staticResourceContact.queryUrl,this.contactAWSDataId,function(data){
            console.log('data = ' + JSON.stringify(data));
            if (data.object) {
                for (let s of that.layout) {
                    for (let lc of s.layoutColumns) {
                        if(lc.layoutItems){
                            for (let c of lc.layoutItems) {
                                if(c['field'] == filedName){
                                    c['value'] = data.object.lastName;
                                }
                            }
                        }
                    }
                }
            }
        },this.staticResourceContact.token)
    }
 
    //解密报修人
    queryRepairApplicantName(repairApplicantAwsId){
        console.log('queryRepairApplicantName repairApplicantAwsId = ' + repairApplicantAwsId)
        debugger
        let that = this;
        this.AWSService.query(this.staticResourceRepairSubOrder.queryUrl,repairApplicantAwsId,function(data){
            console.log('data = ' + JSON.stringify(data));
            if (data.object) {
                for (let s of that.layout) {
                    for (let lc of s.layoutColumns) {
                        if(lc.layoutItems){
                            for (let c of lc.layoutItems) {
                                if(c['field'] == 'RepairApplicant__c'){
                                    c['value'] = data.object.repairApplicantName;
                                }
                                //deloitte-zhj 20230922 报修子单带值 start 
                                if(c['field'] == 'address_Contacts__c'){
                                    c['value'] = data.object.returnedPersonName;
                                }
                                if(c['field'] == 'address_Telephone__c'){
                                    c['value'] = data.object.returnedPersonPhone;
                                }
                                if(c['field'] == 'address_Contacts_Name__c'){
                                    c['value'] = data.object.returnedCustomer;
                                }
                                if(c['field'] == 'address_City__c'){
                                    c['value'] = data.object.returnedCity;
                                }
                                if(c['field'] == 'Detailed_Address__c'){
                                    c['value'] = data.object.returnedAddress;
                                }
                                if(c['field'] == 'address_ZipCode__c'){
                                    c['value'] = data.object.returnedZipCode;
                                }
                                //deloitte-zhj 20230922 报修子单带值 end
                            }
                        }
                    }
                }
            }
        },this.staticResourceRepairSubOrder.token)
    }
 
    //解密加密字段
    queryLeadFromAWSIFS(){
        let that = this;
        debugger;
        this.AWSService.query(this.staticResource.queryUrl,this.AWSDataId,function(data){
            console.log('queryLeadFromAWSIFS data = ' + JSON.stringify(data));
            if (data.object) {
                for (let s of that.layout) {
                    for (let lc of s.layoutColumns) {
                        if(lc.layoutItems){
                            for (let c of lc.layoutItems) {
                                for (let f in that.AWSToSobjectMap) {
                                    if (data.object.hasOwnProperty(f) && c['field'] == that.AWSToSobjectMap[f] && data.object[f]) {
                                        c['value'] = data.object[f];
                                    }
                                }
                            }
                        }
                    }
                }
            }
        },this.staticResource.token)
    }
 
    //取消
    cancel() {
        if(this.isCloneMode){
            window.history.go(-4);
            return
        }
        conmentCancel(this.defaultValues);
    }
 
    //change事件
    dataChange(event) {
        let fieldName = event.target.getAttribute("data-field");
        let value = event.detail.value;
        console.log("fieldName = " + fieldName + " value = " + value);
        this.contactIdMap[fieldName] = value;
        if(fieldName == 'Account__c'){
            this.accountId = value[0];
        }
        if(fieldName == 'Hospital__c'){
            this.hospitalId = value[0];
        }
    }
 
    // 重写保存按钮
    clickSubmit(){
        const btn = this.template.querySelector( ".hidden" );
 
        if( btn ){ 
            btn.click();
        }
    }
 
    // 重写保存并 新建按钮
    clickSubmitAndNew(){
        console.log('clickSubmitAndNew');
        this.saveAndNew = true;
        const btn = this.template.querySelector(".hidden");
        if (btn) {
            btn.click();
        }
    }
 
    //提交保存
    handleSubmit(event) {
        this.isLoading = true;
        //1. Get Sobject Information from Form
        event.preventDefault();
        let fields = event.detail.fields;
        this.modifyFieldArray.forEach(fieldname =>{
            fields[fieldname] = this.contactIdMap[fieldname];
        })
 
        //2. select cannot actively select redaction option
        let validationResultMessage = this.validateFieldValueFormate(fields);
        console.log('validationResultMessage=' + validationResultMessage);
        if (validationResultMessage) {
            this.showMyToast(validationResultMessage , '' , 'error')
            this.isLoading = false;
            return;
        }
 
        //3. Check Required Field
        let checkRequiredFieldMsgResult = this.checkRequiredFieldMsg(fields);
        console.log('checkRequiredFieldMsgResult = ' + checkRequiredFieldMsgResult);
        if (checkRequiredFieldMsgResult != '') {
            this.showMyToast(checkRequiredFieldMsgResult + '需要进行填写' , '' , 'error')
            this.isLoading = false;
            return;
        }
 
        //4. Prepare the payload for New PI API To AWS - To Do
        let payloadForNewPI = this.getPIPayload(fields);
        console.log('payloadForNewPI = ' + payloadForNewPI);
 
        //5. PI To AWS
        //新建
        debugger
        if(this.isNewMode || this.isCloneMode || this.AWSDataId == ''){
            this.NewPIToAWS(payloadForNewPI,fields);
            return
        }
        //编辑
        if(this.isEditMode){
            this.UpdatePIToAWS(payloadForNewPI,fields);
        }
    }
 
    //新建保存ToAWS
    NewPIToAWS(payloadForNewPI,fields){
        let that = this;
        this.AWSService.post(this.staticResourceV2.newUrl, payloadForNewPI, (result) => {
            if (result && result.object) {
                console.log('result = ' + JSON.stringify(result));
                for (let f in this.AWSToSobjectMap) {
                    if (result.object[0].hasOwnProperty(f)) {
                        fields[this.AWSToSobjectMap[f]] = result.object[0][f];
                        console.log('this.AWSToSobjectMap[f] = ' + this.AWSToSobjectMap[f]);
                        console.log('fields[this.AWSToSobjectMap[f]] = ' + fields[this.AWSToSobjectMap[f]]);
                    }
                    else {
                        console.log(f + 'is not in result.object[0]');
                    }
                }
                fields['AWS_Data_Id__c'] = result.object[0].dataId;
                this.txId = result.txId;
                if(fields.RecordTypeId){
                    console.log('length = ' + JSON.stringify(fields.RecordTypeId.length));
                    fields['RecordTypeId'] = fields.RecordTypeId.substring(1, fields.RecordTypeId.length - 1);
                    console.log('RecordTypeId = ' + JSON.stringify(fields['RecordTypeId']));
                }
                //保存到后端
                that.template.querySelector('lightning-record-edit-form').submit(fields);
            } else {
                console.log('result = ' + JSON.stringify(result));
            }
        }, this.staticResource.token);
    }
 
    //编辑保存ToAWS
    UpdatePIToAWS(payloadForNewPI, fields) {
        let obj = JSON.parse(payloadForNewPI);
        if(this.AWSDataId){
            obj[0].dataId = this.AWSDataId;
        }else{
            this.showMyToast("Error", '未找到该记录的AWS Id,请确认记录完整性', 'error');
            return;
        }
        let payloadForNewPIJson = JSON.stringify(obj);
        this.AWSService.post(this.staticResourceV2.updateUrl, payloadForNewPIJson, (result) => {
            if (result && result.object) {
                console.log('result = ' + JSON.stringify(result));
                for (let f in this.AWSToSobjectMap) {
                    if (result.object[0].hasOwnProperty(f)) {
                        fields[this.AWSToSobjectMap[f]] = result.object[0][f];
                        console.log('this.AWSToSobjectMap[f] = ' + this.AWSToSobjectMap[f]);
                        console.log('fields[this.AWSToSobjectMap[f]] = ' + fields[this.AWSToSobjectMap[f]]);
                    }
                    else {
                        console.log(f + 'is not in result.object[0]');
                    }
                }
                if (this.isNewMode || this.isCloneMode) {
                    fields['AWS_Data_Id__c'] = result.object[0].dataId;
                } else {
                    //更新
                    fields['AWS_Data_Id__c'] = this.AWSDataId;
                }
                this.txId = result.txId;
                if (fields.RecordTypeId) {
                    console.log('length = ' + JSON.stringify(fields.RecordTypeId.length));
                    fields['RecordTypeId'] = fields.RecordTypeId.substring(1, fields.RecordTypeId.length - 1);
                    console.log('RecordTypeId = ' + JSON.stringify(fields['RecordTypeId']));
                }
                //保存到后端
                console.log('update submit = ' + JSON.stringify(fields));
                this.template.querySelector('lightning-record-edit-form').submit(fields);
            } else {
                console.log('result = ' + JSON.stringify(result));
            }
        }, this.staticResource.token);
    }
 
    //提交保存成功
    handleSuccess(event) {
        let updatedRecord = event.detail.id;
        console.log('onsuccess: ', updatedRecord);
        console.log('confirmTrans');
        let that = this;
        this.AWSService.confirm(true, updatedRecord, this.txId, this.staticResource.token, this.staticResource.transactionUrl, function (result) {
            console.log('result = ' + JSON.stringify(result))
            that.showToast('Success', '保存成功');
            console.log('updatedRecord = ' + updatedRecord)
            that.confirmAndNavigate(updatedRecord);
        });
    }
 
    // 保存成功后处理相关的收货地址数据并跳转页面
    confirmAndNavigate(updatedRecord){
        this.isLoading = true;
        EncryptUpdate({'rid': updatedRecord})
        .then(result =>{
            if(result.message){
                console.log('EncryptUpdate Error:'+result.message);
                this.showToast("Error", result.message);
            }
            if(this.saveAndNew){
                this[NavigationMixin.Navigate]({
                    type: "standard__objectPage",
                    attributes: {
                        objectApiName: this.sobjectType,
                        actionName: "new",
                    },
                    state: {
                        recordTypeId: this.recordTypeId,
                    },
                });
            }else{
                let url = "/" + updatedRecord;
                parent.location.href = url
                // this[NavigationMixin.Navigate]({
                //     type: 'standard__recordPage',
                //     attributes: {
                //         actionName: "view",
                //         recordId: updatedRecord,
                //         objectApiName: this.sobjectType
                //     }
                // });
            }
        })
    }
 
    //提交保存失败
    handleError(event) {
        event.preventDefault();
        event.stopImmediatePropagation();
        if (event.detail.output && event.detail.output.fieldErrors && Object.keys(event.detail.output.fieldErrors).length != 0) {
            let msg = '';
            for (let key in event.detail.output.fieldErrors) {
                msg += ',' + event.detail.output.fieldErrors[key][0].message;
            }
                msg = msg.substring(1);
            this.showMyToast("Error", event.detail.message + ' : ' + msg, 'error');
        } else {
            //add by Li Jun 20231025 Start 
            if(event.detail.message != '' &&  this.customLabel.LexRecordNotCreateable.indexOf(event.detail.message) != -1){
                this.showMyToast("Error", this.customLabel.LexNotCreateNote, 'error');
            }else{
                this.showMyToast("Error", event.detail.message + ' : ' + event.detail.detail, 'error');
            }
            //add by Li Jun 20231025 End
        }
        //add by Li Jun 20231025 Start 
        if(this.txId && this.staticResource){
            this.AWSService.confirm(false,'',this.txId,this.staticResource.token,this.staticResource.transactionUrl,function(result){
                console.log('result = ' + JSON.stringify(result))
            });
        }
        //add by Li Jun 20231025 End  
    }
 
    // 大段报错信息处理
    showMyToast(title, message, variant) {
        console.log('show custom message');
        let iconName = '';
        let content = '';
        if (variant == 'success') {
            iconName = 'utility:check';
        } else {
            iconName = 'utility:error';
        }
        if (message != '') {
            content =
                '<h2><strong>' +
                title +
                '<strong/></h2><h5>' +
                message +
                '</h5>';
        } else {
            content = '<h2><strong>' + title + '<strong/></h2>';
        }
        this.template
            .querySelector('c-common-toast')
            .showToast(variant, content, iconName, 10000);
        this.isLoading = false;
    }
 
    //验证字段
    validateFieldValueFormate(fields) {
        let error_msg = '';
        let b = false;
        for(let key in fields){
            if(fields[key] == "*****")
                b = true;
        }
        if(b)
            error_msg = '下拉框不能主动选择密文选项';
        return error_msg;
    }
 
    //验证required字段需要进行填写
    checkRequiredFieldMsg(fields) {
        let msg = '';
        try {
            for (let s of this.layout) {
                for (let lc of s.layoutColumns) {
                    if (lc.layoutItems) {
                        for (let c of lc.layoutItems) {
                            if (!c.isDisable && c.isRequired && (fields[c.field] == null || fields[c.field] === '')) {
                                msg += ";" + this.fieldLabel[item.field].label ;
                            }
                        }
                    }
                }
            }
        } catch (err) {
            this.showToast('Error',err.message);
        }
        msg = msg.substring(1);
        return msg;
    }
 
    //获取PI字段
    getPIPayload(sobjJsonLwc) {
        console.log()
        let leadPayloadList = [];
        let leadPIData = {};
 
        for (let f in this.AWSToSobjectMap) {
            if (sobjJsonLwc.hasOwnProperty(this.AWSToSobjectMap[f])) {
                leadPIData[f] = sobjJsonLwc[this.AWSToSobjectMap[f]]
            }
            else {
                console.log(this.AWSToSobjectMap[f] + 'is not in sobjJsonLwc');
            }
        }
 
        leadPIData.sfRecordId = '';
        console.log('Sobject PI Data x :' + leadPIData);
        leadPayloadList.push(leadPIData);
        console.log('leadPayloadList = ' + JSON.stringify(leadPayloadList));
        return JSON.stringify(leadPayloadList);
    }
    
    //查询客户人员根据医院
    searchHospitalNameModal(event){
        this.practitioner = event.target.getAttribute("data-field");
        if(this.modifyFieldArray.includes(this.practitioner)){
            if(this.practitioner == 'Delivered_Product__c'){
                if(this.hospitalId != '' && this.hospitalId){
                    this.lookupFieldLabel = '保有设备';
                    this.lookupTitle = '保有设备';
                    this.searchFieldArray = ['Id','Name','OwnershipMachine_No__c','SerialNumber','AssetManageConfirm__c','Product_Serial_No__c','Information_From__c','Posting_Date__c','guarantee_period__c','Status','Account.Name'];
                    this.searchWhere = 'Hospital__c =\'' +  this.hospitalId + '\' AND IsCompetitorProduct = false';
                    this.searchObjectType  = 'Asset'
                }else{
                    this.showToast('error', '请输入医院');
                    return
                }
 
                
            }
            if(this.practitioner == 'Incharge_Staff_Contact__c'){
                this.lookupFieldLabel = '客户名';
                this.lookupTitle = '客户名';
                this.searchObjectType  = 'Contact'
            }
            this.isShowSearchAccount = true;
        }
    }
 
    //选择客户人员后进行赋值
    handleSelectContact(event){
        this.isLoading = true;
        let fieldName = this.practitioner;
        const selectContact = event.detail;
        for (let s of this.layout) {
            for (let lc of s.layoutColumns) {
                if (lc.layoutItems) {
                    for (let c of lc.layoutItems) {
                        if(c['field'] == fieldName){
                            c['value'] = selectContact.data.medicalStaffFullName;
                            if(selectContact.data.sfRecordId){
                                this.contactIdMap[fieldName] = selectContact.data.sfRecordId;
                                let selectedElement =  this.template.querySelector('[data-field='+ fieldName + ']');
                                selectedElement.value =  c['value'];
                                //If there was a custom error before, reset it
                                selectedElement.setCustomValidity('');
                                // //Tells the lightning-input to show the error right away without needing interaction 
                                selectedElement.reportValidity();
                                this.template.querySelector('[data-icon='+ fieldName + ']').iconName = "utility:close";
                                this.isLoading = false;
                            }else{
                                getContactByAWSId({'awsId': selectContact.data.AWSDataId})
                                .then(result =>{
                                    this.contactIdMap[fieldName] = result.ContactInfo.Id;
                                    let selectedElement =  this.template.querySelector('[data-field='+ fieldName + ']');
                                    selectedElement.value =  c['value'];
                                    //If there was a custom error before, reset it
                                    selectedElement.setCustomValidity('');
                                    // //Tells the lightning-input to show the error right away without needing interaction 
                                    selectedElement.reportValidity();
                                    this.template.querySelector('[data-icon='+ fieldName + ']').iconName = "utility:close";
                                    this.isLoading = false;
                                })
                            }
                            console.log('selectContact.data.sfRecordId = ' + selectContact.data.sfRecordId);
                            console.log('c[value] = ' + c['value']);
                        }
                    }
                }
            }
        }
 
        this.layout = [...this.layout];
        this.closeHospitalNameModal();
    }
 
    //接受lexsearchlookuplwc组件消息,根据选择的数据为对应字段赋值
    handleSelectLookup(event){
        this.isLoading = true;
        let fieldName = this.practitioner;
        const selectLookup = event.detail;
        for (let s of this.layout) {
            for (let lc of s.layoutColumns) {
                if (lc.layoutItems) {
                    for (let c of lc.layoutItems) {
                        if(c['field'] == fieldName){
                            c['value'] = selectLookup.data.Name;
                            let selectedElement =  this.template.querySelector('[data-field='+ fieldName + ']');
                            selectedElement.value =  c['value'];
                            //If there was a custom error before, reset it
                            selectedElement.setCustomValidity('');
                            // //Tells the lightning-input to show the error right away without needing interaction 
                            selectedElement.reportValidity();
                            this.contactIdMap[fieldName] = selectLookup.data.Id;
                        }
                    }
                }
            }
        }
        this.layout = [...this.layout];
        this.isLoading = false;
        this.closeHospitalNameModal();
    }
    //清空客户姓名
    clearName(event) {
        let fieldname = event.target.getAttribute("data-icon")
        console.log("enter clearName");
        if (this.contactIdMap[fieldname] != "") {
            this.contactIdMap[fieldname] = "";
            for (let s of this.layout) {
                for (let c of s.layoutColumns) {
                    if (c.layoutItems) {
                        for (let item of c.layoutItems) {
                            if (item["field"] == fieldname) {
                                item["value"] = "";
                                //this.contactId = "";
                            }
                        }
                    }
                }
            }
            this.layout = [...this.layout];
            this.template.querySelector('[data-icon='+ fieldname + ']').iconName = "utility:search";
        }
    }
 
    //关闭客户人员根据医院模态框
    closeHospitalNameModal(){
        this.isShowSearchAccount = false;
    }
 
    showToast(type, msg) {
        this.isLoading = false;
        const event = new ShowToastEvent({
            title: msg,
            variant: type,
            //message: msg
        });
        this.dispatchEvent(event);
    }
}