Li Jun
2022-03-31 3ba0123db48f8bab81ddf0913e1b95280ef545e8
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
global without sharing class NewAndEditReportController {
    public List <LayoutDescriberHelper.LayoutSection > layoutSections{set;get;}
    public static Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
    public static String sobjectTypeValue = 'Report__c';
    public Boolean isNewMode{set;get;}
    public String rtTypeId {get; set;}
    public String AWSDataId{set;get;}
    public String contactId{set;get;}//For Lookup field
    public List<String> encryptedAPIList{set;get;}   
    public String staticResource {get; set;}
    public String staticResourceContact {get; set;}
    public String requiredFieldAPIListStr {get; set;}
    public String fieldAPIToLabelMapStr {get; set;}
    public String Input_Required_Field_Msg{set;get;}
    public String contactsInfo {set;get;}
    public String PIPL_Input_Account_Error_Msg{set;get;}
    public String SaveAndNewButtonUrl{get;private set;}
    public String sobjectPrefix{get;private set;}
    public String sobjecttypeForFrontEnd{set;get;}
    public String sobjectId{set;get;}
    public String layoutSectionsStr {get; set;}
    public String no1Name{get; set;}
    public String no1Id{get; set;}
    // 当前页面中的加密字段集合
    public List<String> layoutEncryptedAPIList{private set;get;}
    public final string ApiPrefix{get;private set;} 
    public Map<string,string> AWSToSobjectEncryptedMap{get;private set;}
    public string AWSToSobjectEncryptedMapJson{get{return JSON.serialize(AWSToSobjectEncryptedMap);}}
    public NewAndEditReportController(ApexPages.StandardController controller) {
        ApiPrefix = 'PIBackApi';
        layoutEncryptedAPIList = new List<String>();
        AWSToSobjectEncryptedMap = new Map<string,string>();
        sobjectId = [SELECT CustomObjectId,CustomObjectName  FROM CustomObjectUserLicenseMetrics   where CustomObjectName ='Report' limit 1].CustomObjectId;
        isNewMode = true;
        Input_Required_Field_Msg = Label.Input_Required_Field_Msg;
        PIPL_Input_Account_Error_Msg = label.PIPL_Input_Account_Error_Msg;
        sobjecttypeForFrontEnd = sobjectTypeValue;
        //获取所有字段
        List<String> fieldList = new List<String>(Schema.getGlobalDescribe().get('Report__c').getDescribe().fields.getMap().keyset());  
        // Add fields to controller. This is to avoid the SOQL error in visualforce page
        if (!Test.isRunningTest()) { 
            controller.addFields(fieldList);
        }
        SObject obj = controller.getRecord();        
        if(obj.Id != null){
            //更新
            isNewMode = false;
            Report__c ReportData = [select Id,RecordTypeId,AWS_Data_Id__c,Practitioner1__c,Practitioner1__r.AWS_Data_Id__c,
            Practitioner2__c,Practitioner2__r.AWS_Data_Id__c,Practitioner3__c,Practitioner3__r.AWS_Data_Id__c,
            Practitioner4__c,Practitioner4__r.AWS_Data_Id__c,Practitioner5__c,Practitioner5__r.AWS_Data_Id__c,
            Person_In_Charge__c,Person_In_Charge__r.AWS_Data_Id__c
            from Report__c where id =: obj.Id];
            system.debug('ReportData = ' + ReportData);
 
            rtTypeId = ReportData.RecordTypeId;
            AWSDataId = ReportData.AWS_Data_Id__c;
            Map<String,String> sfIdToAWSIdMap = new Map<String,String>();
            system.debug('ReportData.Practitioner1__r.Id:' + ReportData.Practitioner1__r.Id);
            system.debug('ReportData.Practitioner1__r.AWS_Data_Id__c:' + ReportData.Practitioner1__r.AWS_Data_Id__c);
            
            if(ReportData.Practitioner1__r.Id != null && ReportData.Practitioner1__r.AWS_Data_Id__c!=null){
                sfIdToAWSIdMap.put(String.valueof(ReportData.Practitioner1__r.Id).subString(0,15),ReportData.Practitioner1__r.AWS_Data_Id__c);
            }
            if(ReportData.Practitioner2__r.Id != null && ReportData.Practitioner2__r.AWS_Data_Id__c!=null){
                sfIdToAWSIdMap.put(String.valueof(ReportData.Practitioner2__r.Id).subString(0,15),ReportData.Practitioner2__r.AWS_Data_Id__c);
            }
            if(ReportData.Practitioner3__r.Id != null && ReportData.Practitioner3__r.AWS_Data_Id__c!=null){
                sfIdToAWSIdMap.put(String.valueof(ReportData.Practitioner3__r.Id).subString(0,15),ReportData.Practitioner3__r.AWS_Data_Id__c);
            }
            if(ReportData.Practitioner4__r.Id != null && ReportData.Practitioner4__r.AWS_Data_Id__c!=null){
                sfIdToAWSIdMap.put(String.valueof(ReportData.Practitioner4__r.Id).subString(0,15),ReportData.Practitioner4__r.AWS_Data_Id__c);
            }
            if(ReportData.Practitioner5__r.Id != null && ReportData.Practitioner5__r.AWS_Data_Id__c!=null){
                sfIdToAWSIdMap.put(String.valueof(ReportData.Practitioner5__r.Id).subString(0,15),ReportData.Practitioner5__r.AWS_Data_Id__c);
            }
            if(ReportData.Person_In_Charge__r.Id != null && ReportData.Person_In_Charge__r.AWS_Data_Id__c!=null){
                sfIdToAWSIdMap.put(String.valueof(ReportData.Person_In_Charge__r.Id).subString(0,15),ReportData.Person_In_Charge__r.AWS_Data_Id__c);
            }
            contactsInfo = JSON.serialize(sfIdToAWSIdMap);
        }else if(ApexPages.currentPage().getParameters().get('CF00N10000008ps6d_lkid') != null){
            //OPD计划过来的,通过Id查出借出备品申请No1进行展示
            String opdPlanId = ApexPages.currentPage().getParameters().get('CF00N10000008ps6d_lkid');
            if(String.isNotEmpty(opdPlanId)&&String.isNotBlank(opdPlanId)){
                List<OPDPlan__c> opList = [select NewestRentalCode__c from OPDPlan__c where id=:opdPlanId];
                if(opList!=null&&opList.size()>0){
                    no1Name = opList[0].NewestRentalCode__c;
                    List<Rental_Apply__c> racList = [select id from Rental_Apply__c where Name=:opList[0].NewestRentalCode__c];
                    if(racList!=null&&racList.size()>0){
                        no1Id = racList[0].id;
                    }                   
                }
            }                                  
            rtTypeId = ApexPages.currentPage().getParameters().get('RecordType');
            obj.put('OwnerId',UserInfo.getUserId());
        }else{
            //新建
            Map<string,string> mso = ApexPages.currentPage().getParameters();
            //医院/科室/经销商(手写)
            if(mso.containsKey('00N10000002GE3Z')){
                controller.getRecord().put('Manual_Name__c',mso.get('00N10000002GE3Z'));
            }
            rtTypeId = ApexPages.currentPage().getParameters().get('RecordType');
            obj.put('OwnerId',UserInfo.getUserId());
        }
        LayoutDescriberHelper.LayoutWrapper LayoutWrapperValue = LayoutDescriberHelper.describeSectionWithFieldsWrapper(rtTypeId, 'Report__c','classic');
        layoutSections = LayoutWrapperValue.layoutSections;
        List<String> requiredFieldAPIList = LayoutWrapperValue.requiredFieldAPIList;
        Map<String,String> fieldAPIToLabelMap = LayoutWrapperValue.fieldAPIToLabelMap;
        requiredFieldAPIListStr = JSON.serialize(requiredFieldAPIList);
        fieldAPIToLabelMapStr = JSON.serialize(fieldAPIToLabelMap);
        PIHelper.PIIntegration piIntegration = PIHelper.getPIIntegrationInfo('Report__c');
        staticResource = JSON.serialize(piIntegration);
        encryptedAPIList = piIntegration.PIFields;
        System.debug('piIntegration.PIFields = ' + encryptedAPIList);
        staticResourceContact = JSON.serialize(PIHelper.getPIIntegrationInfo('Contact'));
        sobjectPrefix = piIntegration.sobjectPrefix;
        layoutSectionsStr = JSON.serialize(layoutSections);
        for (LayoutDescriberHelper.LayoutSection ls : layoutSections) {
            for (LayoutDescriberHelper.LayoutField lf : ls.layoutFields) {
                //在view解密section中只需显示当前layout中的加密字段
                if (encryptedAPIList.contains(lf.fieldAPI)) {
                    layoutEncryptedAPIList.add(lf.fieldAPI);
                }
            }
        }
        for (PI_Field_Policy_Detail__c PIDetail : piIntegration.PIDetails) {
            AWSToSobjectEncryptedMap.put(PIDetail.AWS_Field_API__c, PIDetail.SF_Field_API_Name__c);
        }
        System.debug('AWSToSobjectEncryptedMap = ' + AWSToSobjectEncryptedMap);
    }
 
    global class Response{
        public String recordId{set;get;}
        public String message{set;get;}
        public String status{set;get;}
    }
 
    @RemoteAction
    global static Response saveReport(String reportJson,String transId,Boolean isNew) {
        System.debug('report Info:' + JSON.serialize(reportJson));
        System.debug('report Info:' + reportJson);
        //System.debug('rtTypeId: ' + rtTypeId);
        //1. Prepare the payload for  report
        Schema.SObjectType reportSchema = schemaMap.get(sobjectTypeValue);
        Map<String, Schema.SObjectField> fieldAPIToTypeMap = reportSchema.getDescribe().fields.getMap();
        Map<String,Object> fieldValueMap = (Map<String,Object>)JSON.deserializeUntyped(reportJson);
        Report__c reportInfo = new Report__c();
 
        System.debug('自定义格式转换开始');
        //2. Save Record Process
        String status = 'success';    
        Response resp = new Response();
        Savepoint sp = Database.setSavepoint();
        String rid = '';
        //自定义格式转换
        try{
        for (String fieldAPI: fieldValueMap.keySet()) {
            if(!fieldAPIToTypeMap.containskey(fieldAPI)){
                continue;
            }
            Schema.DisplayType fielddataType = fieldAPIToTypeMap.get(fieldAPI).getDescribe().getType();  
            String fieldValue = String.valueOf(fieldValueMap.get(fieldAPI)); 
            if(String.valueOf(fielddataType)=='DATE'){
                System.debug('DATE fieldAPI = '+fieldAPI+' filedData = '+String.valueOf(fieldValueMap.get(fieldAPI)));
                //reportInfo.put(fieldAPI, Date.valueOf(String.valueOf(fieldValueMap.get(fieldAPI)).replace('/', '-')));
                reportInfo.put(fieldAPI,(String.isBlank(fieldValue)||String.isEmpty(fieldValue))? null:Date.valueOf(fieldValue.replace('/', '-')));
            }else if(String.valueOf(fielddataType)=='DATETIME'){
                System.debug('fieldValueMap:' + fieldValueMap);
                String dt = String.valueOf(fieldValueMap.get(fieldAPI));
                System.debug('fieldValueMap.get(fieldAPI)' + fieldValueMap.get(fieldAPI));
                System.debug('dt:'+dt);
                if(String.isNotBlank(dt)&&dt.contains('T')){
                    dt = dt.replace('T',' ');
                    reportInfo.put(fieldAPI, Datetime.valueOfGmt(dt));
                }else if(String.isNotBlank(dt))  {
                    reportInfo.put(fieldAPI, Datetime.valueOf(dt.replace('/', '-') + ':00'));
                }else{
                    reportInfo.put(fieldAPI, null);
                }         
            }else if(String.valueof(fielddataType)=='CURRENCY'|| String.valueof(fielddataType)=='PERCENT'||String.valueOf(fielddataType)=='Number'||String.valueOf(fielddataType)=='DOUBLE' ){
                //reportInfo.put(fieldAPI, Decimal.valueOf(String.valueOf(fieldValueMap.get(fieldAPI))));
                reportInfo.put(fieldAPI, (String.isBlank(fieldValue)||String.isEmpty(fieldValue))?null:Decimal.valueOf(fieldValue.replace(',', ''))); 
            } else if(String.valueof(fielddataType)=='BOOLEAN'){
                reportInfo.put(fieldAPI, fieldValueMap.get(fieldAPI));
            }else {
                reportInfo.put(fieldAPI, String.valueOf(fieldValueMap.get(fieldAPI)));
            }                  
        }
        System.debug('自定义格式转换结束');
            
            if(isNew){
                System.debug('reportInfo = ' + reportInfo);               
                if(!Test.isRunningTest()){
                    insert reportInfo;
                } else {
                    Report__c reportTest = new Report__c();
                    insert reportTest;
                }
            }else{
                System.debug('into update');
                String awsDataId = (String)reportInfo.get('AWS_Data_Id__c');
                System.debug('awsDataId = ' + awsDataId);
                report__c[] reports = [select id from report__c where AWS_Data_Id__c =:awsDataId];
                System.debug('reports[0].id = ' + reports[0].id);
                reportInfo.put('Id',reports[0].id);//For testing;                
                if(!Test.isRunningTest()){
                    update reportInfo;
                }
            }
            rid=reportInfo.Id;
            PIHelper.saveTransLog(sobjectTypeValue,(String)reportInfo.get('AWS_Data_Id__c'),rid,transId,reportJson ,status,'');
            resp.recordId = reportInfo.Id;
            // resp.message = 'success savereport';
            resp.status = status;
            return resp;
 
        }catch(DmlException e) {
            status = 'fail';
            Integer index = 0;
            System.debug(e.getNumDml());
            System.debug(e.getDmlFields(index));
            System.debug(e.getDmlId(index));
            System.debug(e.getDmlIndex(index));
            System.debug(e.getDmlMessage(index));
            System.debug(e.getDmlStatusCode(index));
            System.debug(e.getDmlType(index));
            system.debug(e.getMessage());
            system.debug(e.getStackTraceString());
 
            System.debug('into catch'+e.getMessage());
            Database.rollback(sp);
            resp.status = 'Exception';
            resp.message ='保存失败,原因:'+ e.getDmlMessage(index);
            PIHelper.saveTransLog(sobjectTypeValue,(String)reportInfo.get('AWS_Data_Id__c'),rid,transId,reportJson,status,e.getMessage()+e.getStackTraceString());
            return resp;
            
        } catch(Exception e) {
            System.debug('into catch'+e.getMessage());
            Database.rollback(sp);
            status = 'fail';
            PIHelper.saveTransLog(sobjectTypeValue,(String)reportInfo.get('AWS_Data_Id__c'),rid,transId,reportJson,status,e.getMessage());
            resp.message = e.getMessage();            
            resp.status = status;
            return resp;
        }
    }
}