liuyn
2024-03-22 e8be4d964c6b336ed39dba5900b1b9a8f3181b96
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
import { LightningElement,api,track,wire } from 'lwc';
import { CurrentPageReference } from 'lightning/navigation';
import initData from '@salesforce/apex/lexNewAndEditMCController.initData';
import { NavigationMixin } from 'lightning/navigation';
import { AWSService } from 'c/piUtils';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import lexPIPLCustomStyle from '@salesforce/resourceUrl/lexPIPLCustomStyle'
import { loadStyle } from 'lightning/platformResourceLoader';
import { decodeDefaultFieldValues } from "lightning/pageReferenceUtils";
import mainTenance_record from '@salesforce/label/c.mainTenance_record';
 
export default class lexNewAndEditMaintenanceContract extends NavigationMixin(LightningElement) {
   sobjectType = 'Maintenance_Contract__c';
 
    @api recordId;
    @wire(CurrentPageReference) pageRef;
    @track layout = [];
    @track labelMap = {};
 
    title;
    recordTypeId = '' ;
    //recordtyId = '012C600000003IvIAI';//原环境id :01210000000gTYqAAM  新环境id : 012C600000003IvIAI
    recordtyId = mainTenance_record;
    staticResource;
    AWSDataId = '';
    txId = '';
    isNewMode = false;
    isCloneMode = false;
    isEditMode = false;
    isLoading = false;
    isClone = false;
    saveAndNew = false;
    sectionName = [];
    fieldNameList = ['Name','Hospital__c','Department_Class__c','Department__c','Estimate_Target__c'];
    AWSToSobjectMap = {};
    recordData = {};
    AWSService;
    contactIdMap = {};
    defaultValues = {};
    filedsObj = {};
    recordCopyId;
    @track CopyFlg;
    @track copyOfMc;
 
    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;
            console.log('this.recordTypeId = ' + this.recordTypeId);
            // 获取从其他页面带来的参数
            if (this.pageRef.state.defaultFieldValues) {
                this.defaultValues = decodeDefaultFieldValues(
                    this.pageRef.state.defaultFieldValues
                );
                console.log('this.contactAWSDataId = ' + this.contactAWSDataId);
            }
        }
        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(){
        if(this.isCloneMode){
            this.recordId = this.pageRef.state.c__recordId;
        }
        this.recordCopyId = this.pageRef.state.c__recordId;
        initData({
            'rid': this.recordId,
            'recordTypeId': this.recordtyId,
            'sobjectType': this.sobjectType
        }).then((r) => {
             console.log('r===='+r.status);
            r = JSON.parse(JSON.stringify(r));
            if (r.status == 'Success') {
                let layout = JSON.parse(r.entity.layout);
                this.layout = 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);
                // if(r.entity.AWSDataId){
                //     this.AWSDataId = r.entity.AWSDataId;
                // }
                if(r.entity.recordTypeId){
                    this.recordTypeId = r.entity.recordTypeId;
                }
                if(this.isCloneMode) {
                    this.CopyFlg = true;
                    this.copyOfMc = this.recordId;
                }
               
                this.sectionName = layout.map(s => s.label);
                layout = this.sortMetaLayouts(layout);
                layout.forEach(section =>{
                    section['showLabel'] = false;
                    section['showSection'] = false;
                    if(section['editHeading'] || section['detailHeading']){
                        section['showSection'] = true;
                    }
                    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.isNewMode && this.defaultValues) {
                                    if(this.defaultValues[filedName]){
                                        item['value'] = this.defaultValues[filedName];
                                    }
                                }
                                if(this.isCloneMode 
                                    && item['isDisable'] != true
                                    // && item['field'] == 'Hospital__c' 
                                    // || item['field'] == 'Department_Class__c' 
                                    // || item['field'] == 'Department__c' 
                                    // || item['field'] == 'Estimate_Target__c' 
                                    // || item['field'] == 'Estimation_Id__c' 
                                    // || item['field'] == 'Service_Contract_Staff__c' 
                                    // || item['field'] == 'Estimate_Target__c' 
                                    // || item['field'] == 'Dealer__c' 
                                    // || item['field'] == 'Service_Contract_Staff__c' 
 
                                   && item['field'] != 'PB_Contrant_Cnt__c'
                                   && item['field'] != 'PA_Contrant_Cnt__c'
                                   && item['field'] != 'Contract_Conclusion_Date__c'
                                   && item['field'] != 'Contract_Start_Date__c'
                                   && item['field'] != 'Estimate_Trial_Money__c'
                                   && item['field'] != 'Contract_End_Date__c'
                                   && item['field'] != 'Receipt_Date__c'
                                   && item['field'] != 'Recycling_Predetermined_Day__c'
                                   && item['field'] != 'Contract_Amount__c'
                                   && item['field'] != 'Collect_Date__c'
                                   && item['field'] != 'Recoverable_Amount__c'
                                   && item['field'] != 'Not_collect_money__c'
                                   && item['field'] != 'Sum_repair_price__c'
                                   && item['field'] != 'invoice_amount__c'
                                   && item['field'] != 'Total_not_collect_amount__c'
                                   && item['field'] != 'Description__c'
                                   && item['field'] != 'OCM_Print_request__c'
                                   && item['field'] != 'HP_Dealer_print__c'
                                   && item['field'] != 'Submit_contract_to_Financial_dept__c'
                                   && item['field'] != 'Received_Date__c'
                                   && item['field'] != 'Repair_Cost_Sum__c'
                                   && item['field'] != 'Last_year_service_contract__c'
                                   && item['field'] != 'Contract_print_completed__c'
                                   && item['field'] != 'Maintenance_Contract_No__c'
                                   && item['field'] != 'Service_contract_target_number__c'  
                                   && item['field'] != 'Name'  
                                   && item['field'] != 'Estimation_Id__c'  
                                   && item['field'] != 'MaintanceContractPack__c'  
                                   && item['field'] != 'HospitalAmountText__c'  
                                   && item['field'] != 'Status__c'  ){
                                    item['value'] = this.recordData[filedName] == null ? '' : this.recordData[filedName];
                                }
                                if (filedName == 'RecordTypeId') {
                                    item['value'] = this.recordtyId;
                                    console.log('RecordTypeId='+this.recordtyId);
                                } 
                                if (filedName == 'Last_year_service_contract__c') {
                                    item['value'] = this.recordId;
                                    console.log('Last_year_service_contract__c='+this.recordId);
                                } 
                               
                                // if (filedName == 'Status__c') {
                                //     item['value'] = '引合中';
                                //     console.log('Status__c='+'引合中');
                                // }
                            })
                        }
                        
                    })
                })
              
            } else {
                this.showToast('Error', r.Msg);
            }
            if(this.isCloneMode){
                this.recordId = '';
            }
            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;
    }
 
    
 
    //取消
    cancel() {
        debugger;
        console.log('--------------------------');
        console.log(this.defaultValues);
        console.log(JSON.stringify(this.defaultValues));
        if(this.defaultValues){
            window.history.go(-2);
        }else{
            window.history.back();
        }
        return false;
    }
 
    //change事件
    dataChange(event) {
        let fieldName = event.target.getAttribute("data-field");
        let value = event.detail.value;
        console.log("fieldName = " + fieldName + " value = " + value);
    }
 
    // 重写保存按钮
    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();
        var fields = event.detail.fields;
        this.filedsObj = event.detail.fields
        
 
        //2. select cannot actively select redaction option
        let validationResultMessage = this.validateFieldValueFormate(fields);
        console.log('validationResultMessage=' + validationResultMessage);
        if (validationResultMessage) {
            this.showToast('Error', validationResultMessage);
            return;
        }
 
        //3. Check Required Field
        let checkRequiredFieldMsgResult = this.checkRequiredFieldMsg(fields);
        console.log('checkRequiredFieldMsgResult = ' + checkRequiredFieldMsgResult);
        if (checkRequiredFieldMsgResult != '') {
            this.showToast('Error', checkRequiredFieldMsgResult  + '需要进行填写');
            return;
        }
        // fields['CopyFlg__c'] = true;
        // fields['copyOfMc__c'] = this.recordId;
        // console.log(' copyOfMc__c:' + fields['copyOfMc__c'] ) ;
         this.filedsObj = {
                    ...this.filedsObj,
                    CopyFlg__c: true,
                    copyOfMc__c: this.recordCopyId,
                };
        console.log(' CopyFlg__c:' + this.filedsObj.CopyFlg__c ) ;
        console.log(' copyOfMc__c:' + this.filedsObj.copyOfMc__c ) ;
 
         this.template.querySelector('lightning-record-edit-form').submit(this.filedsObj);
    }
 
    //提交保存成功
    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.navigate(updatedRecord);
        // });
    }
 
    // 保存成功后跳转页面
    navigate(updatedRecord){
        if(this.saveAndNew){
            window.location.reload(true);
        }else{
            let url = "/" + updatedRecord;
            parent.location.href = url
        }
    }
 
    //提交保存失败
    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 + ' : ' + event.detail.detail, 'error');
        } else {
            this.showMyToast("Error", event.detail.message + ' : ' + event.detail.detail, 'error');
        }
        // this.AWSService.confirm(false,'',this.txId,this.staticResource.token,this.staticResource.transactionUrl,function(result){
        //     console.log('result = ' + JSON.stringify(result))
        // });
    }
 
    // 大段报错信息处理
    showMyToast(title, message, variant) {
        console.log('show custom message');
        var iconName = '';
        var 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(var 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 += ';' + c.fieldLabel;
                            }
                        }
                    }
                }
            }
        } catch (err) {
            this.showToast('Error',err.message);
        }
        msg = msg.substring(1);
        return msg;
    }
 
    
 
    showToast(type, msg) {
        this.isLoading = false;
        const event = new ShowToastEvent({
            title: msg,
            variant: type,
            //message: msg
        });
        this.dispatchEvent(event);
    }
}