Li Jun
2022-05-10 896e69e68ecc01b0b8a4c03dd010e0a31603be6e
force-app/main/default/classes/NewAndEditReportController.cls
@@ -3,6 +3,7 @@
    public static Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
    public static String sobjectTypeValue = 'Report__c';
    public Boolean isNewMode{set;get;}
    public Boolean isCloneMode{protected set;get;}
    public String rtTypeId {get; set;}
    public String AWSDataId{set;get;}
    public String contactId{set;get;}//For Lookup field
@@ -19,16 +20,44 @@
    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 String contactAWSDataId1{set;get;}
    public String contactAWSDataId2{set;get;}
    public String contactAWSDataId3{set;get;}
    public String contactAWSDataId4{set;get;}
    public String contactAWSDataId5{set;get;}
    public String contactName1{set;get;}
    public String contactName2{set;get;}
    public String contactName3{set;get;}
    public String contactName4{set;get;}
    public String contactName5{set;get;}
    public String sfRecordIdForEdit{set;get;}//Add By LiJun for Edit Record from NFM609, 20220510
    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;
        isCloneMode = false;
        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
        controller.addFields(fieldList);
        if (!Test.isRunningTest()) {
            controller.addFields(fieldList);
        }
        Map<string,string> mso = ApexPages.currentPage().getParameters();
        if(mso != null && mso.containsKey('newclone')){
            isCloneMode = true;
        }
        SObject obj = controller.getRecord();        
        if(obj.Id != null){
            //更新
@@ -42,7 +71,11 @@
            rtTypeId = ReportData.RecordTypeId;
            AWSDataId = ReportData.AWS_Data_Id__c;
            sfRecordIdForEdit = obj.Id;
            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);
            }
@@ -62,10 +95,80 @@
                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);
            //实施人1,2,3,4,5
            Report__c rc = [select Practitioner1__c,Practitioner2__c,Practitioner3__c,Practitioner4__c,Practitioner5__c from Report__c where id=:obj.Id];
            if (rc != null) {
                List<Contact> c1 = [select AWS_Data_Id__c,Name from Contact where id=:rc.Practitioner1__c];
                if(c1.size()>0){
                    if (c1[0].AWS_Data_Id__c != null && c1[0].AWS_Data_Id__c != '') {
                        contactAWSDataId1 = c1[0].AWS_Data_Id__c;
                    }else {
                        contactName1 = c1[0].Name;
                    }
                }
                List<Contact> c2 = [select AWS_Data_Id__c,Name from Contact where id=:rc.Practitioner2__c];
                if(c2.size()>0){
                    if (c2[0].AWS_Data_Id__c != null && c2[0].AWS_Data_Id__c != '') {
                        contactAWSDataId2 = c2[0].AWS_Data_Id__c;
                    }else {
                        contactName2 = c2[0].Name;
                    }
                }
                List<Contact> c3 = [select AWS_Data_Id__c,Name from Contact where id=:rc.Practitioner3__c];
                if(c3.size()>0){
                    if (c3[0].AWS_Data_Id__c != null && c3[0].AWS_Data_Id__c != '') {
                        contactAWSDataId3 = c3[0].AWS_Data_Id__c;
                    }else {
                        contactName3 = c3[0].Name;
                    }
                }
                List<Contact> c4 = [select AWS_Data_Id__c,Name from Contact where id=:rc.Practitioner4__c];
                if(c4.size()>0){
                    if (c4[0].AWS_Data_Id__c != null && c4[0].AWS_Data_Id__c != '') {
                        contactAWSDataId4 = c4[0].AWS_Data_Id__c;
                    }else {
                        contactName4 = c4[0].Name;
                    }
                }
                List<Contact> c5 = [select AWS_Data_Id__c,Name from Contact where id=:rc.Practitioner5__c];
                if(c5.size()>0){
                    if (c5[0].AWS_Data_Id__c != null && c5[0].AWS_Data_Id__c != '') {
                        contactAWSDataId5 = c5[0].AWS_Data_Id__c;
                    }else {
                        contactName5 = c5[0].Name;
                    }
                }
            }else {
                contactAWSDataId1 = '无';
                contactName1 = '无';
            }
        }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());
        }
        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;
                    }
                }
            }
        }
        //OPD计划
        if(mso.containsKey('CF00N10000008ps6d_lkid')){
            controller.getRecord().put('Report_OPDPlan__c',mso.get('CF00N10000008ps6d_lkid'));
        }
        LayoutDescriberHelper.LayoutWrapper LayoutWrapperValue = LayoutDescriberHelper.describeSectionWithFieldsWrapper(rtTypeId, 'Report__c','classic');
        layoutSections = LayoutWrapperValue.layoutSections;
@@ -76,9 +179,22 @@
        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{
@@ -90,6 +206,7 @@
    @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);
@@ -98,51 +215,75 @@
        Report__c reportInfo = new Report__c();
        System.debug('自定义格式转换开始');
        //自定义格式转换
        for (String fieldAPI: fieldValueMap.keySet()) {
            Schema.DisplayType fielddataType = fieldAPIToTypeMap.get(fieldAPI).getDescribe().getType();
            String fieldValue = String.valueOf(fieldValueMap.get(fieldAPI));
            if(String.isBlank(fieldValue)){
                continue;
            }
            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('/', '-')));
            }else if(String.valueOf(fielddataType)=='DATETIME'){
                String dt = String.valueOf(fieldValueMap.get(fieldAPI));
                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));
                }
            }else if(String.valueOf(fielddataType)=='Number'||String.valueOf(fielddataType)=='DOUBLE' ){
                reportInfo.put(fieldAPI, Decimal.valueOf(String.valueOf(fieldValueMap.get(fieldAPI))));
            } else if(String.valueof(fielddataType)=='BOOLEAN'){
                reportInfo.put(fieldAPI, fieldValueMap.get(fieldAPI));
            }else {
                reportInfo.put(fieldAPI, String.valueOf(fieldValueMap.get(fieldAPI)));
            }
        }
        System.debug('自定义格式转换结束');
        //2. Save Record Process
        String status = 'success';    
        Response resp = new Response();
        Savepoint sp = Database.setSavepoint();
        String rid = '';
        //自定义格式转换
        Boolean isClone = false;
        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('自定义格式转换结束');
            String awsDataId = (String)reportInfo.get('AWS_Data_Id__c');
            String sfRecordId =  (String)reportInfo.get('Id');
            System.debug('awsDataId = ' + awsDataId);
            report__c[] reports = [select id from report__c where AWS_Data_Id__c =:awsDataId or id =:sfRecordId];
            if(!isNew){
                isClone = reports.size() == 0;
            }
            system.debug('isClone'+isClone + ' isNew'+isNew);
            if(isNew){
                System.debug('reportInfo = ' + reportInfo);
                insert reportInfo;
                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];
                // 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;
                update reportInfo;
                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,'');
@@ -151,6 +292,26 @@
            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);