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
global without sharing class RentalApplyController {
    public String layoutSectionsStr {get; set;}//for dynamic add readonly attribute
    public List <LayoutDescriberHelper.LayoutSection > layoutSections{set;get;}
    public String awsToken{set;get;}
    public static Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
    public static String sobjectTypeValue = 'Rental_Apply__c';
    public Boolean isNewMode{set;get;}
    public Boolean isCloneMode{protected set;get;}
    public String rtTypeId {get; set;}
    public String AWSDataId{set;get;}
    public List<String> encryptedAPIList{set;get;}  
    // 当前页面中的加密字段集合
    public List<String> layoutEncryptedAPIList{private 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 requiredErrorMsg{set;get;}
    public String contactsInfo {set;get;}
    public String contactId{set;get;}
    public String PIPL_Input_Account_Error_Msg{set;get;}
    public final string ApiPrefix{get;private set;} //Add By Li Jun 20220403
    public Map<string,string> AWSToSobjectEncryptedMap{get;private set;}
    public string AWSToSobjectEncryptedMapJson{get{return JSON.serialize(AWSToSobjectEncryptedMap);}}
    //zhj MEBG新方案改造 2022-11-29 start
    public String staticResourceV2 {get; set;}
    public Boolean isEdit {get; set;}
    //zhj MEBG新方案改造 2022-11-29 end
 
    public RentalApplyController(ApexPages.StandardController controller) {
        ApiPrefix = 'PIBackApi';    
        isNewMode = true;
        isCloneMode = false;
        Input_Required_Field_Msg = Label.Input_Required_Field_Msg;
        PIPL_Input_Account_Error_Msg = label.PIPL_Input_Account_Error_Msg;
        layoutEncryptedAPIList = new List<String>();
        //获取所有字段
        List<String> fieldList = new List<String>(Schema.getGlobalDescribe().get('Rental_Apply__c').getDescribe().fields.getMap().keyset());  
        Map<string,string> mso = ApexPages.currentPage().getParameters();
        if(mso != null && mso.containsKey('newclone')){
            isCloneMode = true;
        }
        if(!Test.isRunningTest()){
            controller.addFields(fieldList);
        }
        SObject obj = controller.getRecord();
        if(obj.Id != null){
            //更新
            isNewMode = false;
            Rental_Apply__c rentalApplyData = [select Id,RecordTypeId,AWS_Data_Id__c,Loaner_medical_Staff__c,Loaner_medical_Staff__r.AWS_Data_Id__c,status__c,Add_Approval_Status__c,Routine_Check_Status__c,autoSplitContinue__c from Rental_Apply__c where id =: obj.Id];
            rtTypeId = rentalApplyData.RecordTypeId;
            //Update record type for Rental Apply by Li Jun 20220419 start
            if(ApexPages.currentPage().getParameters().containskey('RecordType')){
                rtTypeId = ApexPages.currentPage().getParameters().get('RecordType');
            }
            controller.getRecord().put('RecordTypeId',rtTypeId);
            //Update record type for Rental Apply  by Li Jun 20220419 end
 
            // DB202303417030 【大及巨大课题】备品中心维修续借课题 20230530 lc Start
            if (rentalApplyData.Routine_Check_Status__c == 'OK' || rentalApplyData.autoSplitContinue__c) {      //20240103 备品智能化 zyh 添加autoSplitContinue__c  去X的逻辑 
                AWSDataId = rentalApplyData.AWS_Data_Id__c.substring(0, rentalApplyData.AWS_Data_Id__c.length() - 1);
            } else {
                AWSDataId = rentalApplyData.AWS_Data_Id__c;
            }
            // DB202303417030 【大及巨大课题】备品中心维修续借课题 20230530 lc End
 
            Map<String,String> sfIdToAWSIdMap = new Map<String,String>();
            if(rentalApplyData.Loaner_medical_Staff__r.Id != null){
                sfIdToAWSIdMap.put(String.valueof(rentalApplyData.Loaner_medical_Staff__r.Id).subString(0,15),rentalApplyData.Loaner_medical_Staff__r.AWS_Data_Id__c);
            }
            contactsInfo = JSON.serialize(sfIdToAWSIdMap);
 
            //zhj MEBG新方案改造 2022-11-29 start
            User loginUser = [Select Id, Name, ProfileId From User where Id = :Userinfo.getUserId()];
            isEdit = false;
            if(rentalApplyData.status__c != '草案中' 
            && rentalApplyData.status__c != '填写完毕' 
            && rentalApplyData.status__c != '申请中'
            && rentalApplyData.status__c != '申请中(OPD未通过)'       //20231224 sx add  备品智能化添加状态 优化
            && rentalApplyData.Add_Approval_Status__c != '草案中'
            && rentalApplyData.Add_Approval_Status__c != '填写完毕'
            && rentalApplyData.Add_Approval_Status__c != '申请中'
            && loginUser.ProfileId != System.Label.getProfileId_CU
            && loginUser.ProfileId != System.Label.login_user_1
            && loginUser.ProfileId != System.label.login_user_2
            && loginUser.ProfileId != System.label.login_user_3){
                isEdit = true;
            }
            //zhj MEBG新方案改造 2022-11-29 end
        }else{
            //新建
            // Map<string,string> mso = ApexPages.currentPage().getParameters();
            system.debug('mso='+mso);
            if(mso.containsKey('Name')){
                controller.getRecord().put('Name',mso.get('Name'));
            }
            if(mso.containsKey(System.label.RentalApply_1)){
                controller.getRecord().put('OPDPlan__c',mso.get(System.label.RentalApply_1));
            }
            if(mso.containsKey(System.label.RentalApply_2)){
                controller.getRecord().put('Hospital__c',mso.get(System.label.RentalApply_2));
            }
            if(mso.containsKey(System.label.RentalApply_3)){
                controller.getRecord().put('Strategic_dept__c',mso.get(System.label.RentalApply_3));
            }
            if(mso.containsKey(System.label.RentalApply_4)){
                controller.getRecord().put('Account__c',mso.get(System.label.RentalApply_4));
            }
            if(mso.containsKey(System.Label.RentalApply_5)){
                controller.getRecord().put('Demo_purpose1__c',mso.get(System.label.RentalApply_5));
            }
            if(mso.containsKey(System.label.RentalApply_6)){
                controller.getRecord().put('demo_purpose2__c',mso.get(System.Label.RentalApply_6));
            }
            if(mso.containsKey(System.label.RentalApply_7)){
                controller.getRecord().put('NoOpp_Reason__c',mso.get(System.Label.RentalApply_7));
            }
            if(mso.containsKey(System.label.RentalApply_8)){
                controller.getRecord().put('Loaner_received_staff__c',mso.get(System.label.RentalApply_8));
            }
            
            
            
            rtTypeId = ApexPages.currentPage().getParameters().get('RecordType');
            obj.put('OwnerId',UserInfo.getUserId());
        }
        
        AssignValueFromUrl(mso,controller.getRecord());
        system.debug('Rental Apply Record Type:'+rtTypeId);
        LayoutDescriberHelper.LayoutWrapper LayoutWrapperValue = LayoutDescriberHelper.describeSectionWithFieldsWrapper(rtTypeId, 'Rental_Apply__c','classic');
        layoutSections = LayoutWrapperValue.layoutSections;
        layoutSectionsStr = JSON.serialize(layoutSections); //for dynamic add readonly attribute
        List<String> requiredFieldAPIList = LayoutWrapperValue.requiredFieldAPIList;
        Map<String,String> fieldAPIToLabelMap = LayoutWrapperValue.fieldAPIToLabelMap;
        requiredFieldAPIListStr = JSON.serialize(requiredFieldAPIList);
        fieldAPIToLabelMapStr = JSON.serialize(fieldAPIToLabelMap);
        PIHelper.PIIntegration piIntegration = PIHelper.getPIIntegrationInfo('Rental_Apply__c');
        staticResource = JSON.serialize(piIntegration);
        encryptedAPIList = piIntegration.PIFields;
        staticResourceContact = JSON.serialize(PIHelper.getPIIntegrationInfo('Contact'));
        AWSToSobjectEncryptedMap = new Map<String,String>();
        for (PI_Field_Policy_Detail__c PIDetail : piIntegration.PIDetails) {
            AWSToSobjectEncryptedMap.put(PIDetail.AWS_Field_API__c, PIDetail.SF_Field_API_Name__c);
        }
        //2023 08 18 张赫阳 添加permissonset start
        Schema.SObjectType sobjectSchema = schemaMap.get(sobjectTypeValue);
        Map<String, Schema.SObjectField> fieldMap = sobjectSchema.getDescribe().fields.getMap(); 
        //2023 08 18 张赫阳 添加permissonset en
        List<String> VLookUpFields = new List<String>();
        for (LayoutDescriberHelper.LayoutSection ls : layoutSections) {
            for (LayoutDescriberHelper.LayoutField lf : ls.layoutFields) {
                //在view解密section中只需显示当前layout中的加密字段
                if (encryptedAPIList.contains(lf.fieldAPI)) {
                    //2023 08 18 张赫阳 添加permissonset start
                    if(fieldMap.get(lf.fieldAPI).getDescribe().isAccessible()){
                    //2023 08 18 张赫阳 添加permissonset end
                        layoutEncryptedAPIList.add(lf.fieldAPI);
                    }
                    
                }
            }
        }
        //zhj MEBG新方案改造 2022-11-29 start
        staticResourceV2 = JSON.serialize(PIHelper.getPIIntegrationInfo('Rental_Apply__cV2'));
        //zhj MEBG新方案改造 2022-11-29 end
    }
    
    public static void AssignValueFromUrl(Map<string,string> mso, sobject sobj){
        Map<string,object> temp = new Map<string,object>();
        Map<string,FieldDefinition> fdm = new Map<string,FieldDefinition>();
        List<FieldDefinition> fds = [SELECT Id, DurableId, QualifiedApiName, EntityDefinitionId, NamespacePrefix, DeveloperName, MasterLabel, Label FROM FieldDefinition where EntityDefinition.QualifiedApiName = 'Rental_Apply__c'];
        for(FieldDefinition fd : fds){
            //system.debug(fd.DurableId);
            fdm.put(fd.DurableId.split('\\.')[1],fd);
        }
        
        for(string key : mso.keySet()){
            string new_key = key;
            system.debug('new_key='+new_key);
            if(new_key.contains('_lkid')){
                new_key = new_key.replace('_lkid', '');
                new_key = new_key.substring(2);
            }else{
                if(temp.containsKey(new_key)){
                    continue;
                }
            }
            
            system.debug('now new_key='+new_key);
            if(fdm.containsKey(new_key)){
                string val = EncodingUtil.urlDecode(mso.get(key),'UTF-8');
                if(string.isBlank(val)){
                    val = null;
                }
                temp.put(fdm.get(new_key).QualifiedApiName,val);
            }else{
                system.debug(key+' is not in fdm');
            }
        }
        
        for(string key : temp.keySet()){
            system.debug('assign '+key+'='+temp.get(key));
            try{
                sobj.put(key, temp.get(key));
            }catch(Exception e){
                system.debug(e.getMessage());
                system.debug(e.getStackTraceString());
            }
        }
    }
 
    global class Response{
        public String recordId{set;get;}
        public String message{set;get;}
        public String status{set;get;}
    }
 
    @RemoteAction
    global static Response saveRentalApply(String rentalApplyJson,String transId,Boolean isNew) {
        System.debug('Rental_Apply__c Info:' + JSON.serialize(rentalApplyJson));
        //1. Prepare the payload for  Rental_Apply__c
        Schema.SObjectType rentalApplySchema = schemaMap.get(sobjectTypeValue);
        Map<String, Schema.SObjectField> fieldAPIToTypeMap = rentalApplySchema.getDescribe().fields.getMap();
        system.debug(fieldAPIToTypeMap);
        Map<String,Object> fieldValueMap = (Map<String,Object>)JSON.deserializeUntyped(rentalApplyJson);
        Rental_Apply__c rentalApplyInfo = new Rental_Apply__c();
        String status = 'success';    
        Response resp = new Response();
        Savepoint sp = Database.setSavepoint();
        String rid = '';
        Boolean isClone = false;
        String awsDataId = '';
        // DB202303417030 【大及巨大课题】备品中心维修续借课题 20230530 lc Start
        String raName = null;
        // DB202303417030 【大及巨大课题】备品中心维修续借课题 20230530 lc End
        try{
            //自定义格式转换
            for (String fieldAPI: fieldValueMap.keySet()) {
                system.debug('field API'+fieldAPI);
                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'){
                    rentalApplyInfo.put(fieldAPI,(String.isBlank(fieldValue)||String.isEmpty(fieldValue))? null:Date.valueOf(fieldValue.replace('/', '-'))); 
                }else if(String.valueOf(fielddataType)=='DATETIME'){
                    if(String.isNotBlank(fieldValue)&&fieldValue.contains('T')){
                        fieldValue = fieldValue.replace('T',' ');
                        rentalApplyInfo.put(fieldAPI, Datetime.valueOfGmt(fieldValue));
                    }else if(String.isNotBlank(fieldValue))  {
                        fieldValue = fieldValue.replace('/', '-') + ':00';
                        System.debug('fieldValue = ' + fieldValue);
                        rentalApplyInfo.put(fieldAPI, Datetime.valueOf(fieldValue));
                    }else{
                        rentalApplyInfo.put(fieldAPI, null);
                    }
                    
                }else if(String.valueOf(fielddataType)=='PERCENT'||String.valueOf(fielddataType)=='CURRENCY'||String.valueOf(fielddataType)=='Number'||String.valueOf(fielddataType)=='DOUBLE' ){
                    rentalApplyInfo.put(fieldAPI, (String.isBlank(fieldValue)||String.isEmpty(fieldValue))?null:Decimal.valueOf(fieldValue.replace(',', ''))); 
                } else if(String.valueof(fielddataType)=='BOOLEAN'){
                    rentalApplyInfo.put(fieldAPI, fieldValueMap.get(fieldAPI));
                }else {
                    rentalApplyInfo.put(fieldAPI, String.valueOf(fieldValueMap.get(fieldAPI)));
                }
            }
            
            //2. Save Record Process
            
        
            System.debug('abcde:'+rentalApplyInfo);
            awsDataId = (String)rentalApplyInfo.get('AWS_Data_Id__c');
            // DB202303417030 【大及巨大课题】备品中心维修续借课题 20230530 lc Start
            raName = (String)rentalApplyInfo.get('Name');
            System.debug('awsDataId = ' + awsDataId);
            System.debug('raName = ' + raName);
            //Rental_Apply__c[] RentalApplys = [select id from Rental_Apply__c where AWS_Data_Id__c =:awsDataId];
            Rental_Apply__c[] RentalApplys = [select id, AWS_Data_Id__c, Routine_Check_Status__c from Rental_Apply__c where Name =:raName];
            // Rental_Apply__c[] RentalApplys = [select Name,id, AWS_Data_Id__c, Routine_Check_Status__c from Rental_Apply__c];
            System.debug('RentalApplys = ' + RentalApplys);
            System.debug('RentalApplys = ' + RentalApplys.size());
            // DB202303417030 【大及巨大课题】备品中心维修续借课题 20230530 lc End
            if(!isNew){
                isClone = RentalApplys.size() == 0;
            }
            System.debug('RentalApplys = ' + isNew+isClone);
            if(isNew || isClone){
                System.debug('rentalApplyInfozhj = ' + rentalApplyInfo);
                insert rentalApplyInfo;
                System.debug('rentalApplyInfo.Id' + rentalApplyInfo.Id);
            }else{
                System.debug('into update');
                // String awsDataId = (String)rentalApplyInfo.get('AWS_Data_Id__c');
                // System.debug('awsDataId = ' + awsDataId);
                // Rental_Apply__c[] RentalApplys = [select id from Rental_Apply__c where AWS_Data_Id__c =:awsDataId];
                System.debug('RentalApplys[0].id = ' + RentalApplys[0].id);
                rentalApplyInfo.put('Id',RentalApplys[0].id);//For testing;
                // DB202303417030 【大及巨大课题】备品中心维修续借课题 20230530 lc Start
                if (RentalApplys[0].Routine_Check_Status__c == 'OK') {
                    rentalApplyInfo.put('AWS_Data_Id__c',RentalApplys[0].AWS_Data_Id__c);
                }
                // DB202303417030 【大及巨大课题】备品中心维修续借课题 20230530 lc End
                
                update rentalApplyInfo;
            }
            rid=rentalApplyInfo.Id;
            // PIHelper.saveTransLog(sobjectTypeValue,transId, (String)rentalApplyInfo.get('AWS_Data_Id__c'),rentalApplyJson ,status,'');
            PIHelper.saveTransLog(sobjectTypeValue,(String)rentalApplyInfo.get('AWS_Data_Id__c'),rid,transId,rentalApplyJson,status,'');
            resp.recordId = rid;
            resp.message = 'success saveRentalApply';
            resp.status = status;
            System.debug('respzhj = ' + resp);
            return resp;
        } catch(DmlException e) {
            rid=rentalApplyInfo.Id;
            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,rid,transId, (String)rentalApplyInfo.get('AWS_Data_Id__c'),rentalApplyJson ,status,'');
            return resp;
            
        } catch(Exception e) {
            System.debug('into catch'+e.getMessage());
            Database.rollback(sp);
            status = 'fail';
            // PIHelper.saveTransLog(sobjectTypeValue,transId, (String)rentalApplyInfo.get('AWS_Data_Id__c'),rentalApplyJson,status,e.getMessage());
            PIHelper.saveTransLog(sobjectTypeValue,(String)rentalApplyInfo.get('AWS_Data_Id__c'),rid,transId,rentalApplyJson,status,e.getMessage());
            resp.message = e.getMessage();            
            resp.status = status;
            return resp;
        }
    }
 
    public static void improveTestReta(){
        Integer i = 0;
       
    }
    
    
}