public class NewAgencyContactController {

    static string sobjectType = 'Agency_Contact__c';
    
    @AuraEnabled
    public static ControllerResponse Init(string rid,Id pid, string record_type_id){
        system.debug('rid='+rid+',length='+(rid==null?'null':rid.length()+''));
        system.debug('record_type_id='+record_type_id+',length='+(record_type_id==null?'null':record_type_id.length()+''));
        
        
        ControllerResponse res = new ControllerResponse();
        Map<string,object> data = new Map<string,object>();
        res.Data = data;
        
        Agency_Contact__c ac = null;
        List<Metadata.LayoutSection> layout = null;
        if(string.isBlank(rid)){
            
            layout = MetaDataUtility.GetRecordTypePageLayout(record_type_id, sobjectType);
            data.put('layout', Json.serialize(layout));
            
        }else{
            ac = [select RecordTypeId from Agency_Contact__c where id = :rid];
            if(ac == null){
                res.Message = 'id不存在';
            	return res;
            }
            record_type_id = ac.RecordTypeId;
            system.debug('record_type_id is fresh ='+ac.RecordTypeId);
            
            layout = MetaDataUtility.GetRecordTypePageLayout(record_type_id, sobjectType);
            data.put('layout', Json.serialize(layout));
            
            List<String> fieldApiList = new List<String>(); 
            /*
            for (LayoutDescriberHelper.LayoutSection ls : layout.layoutSections) {
                for (LayoutDescriberHelper.LayoutField lf : ls.layoutFields) {
                    if (lf.fieldAPI != '') {
                        System.debug('lf.fieldAPI='+lf.fieldAPI+' fieldType='+lf.fieldType);
                        fieldApiList.add(lf.fieldAPI);
                    }
                }
            }
			*/
            for( Metadata.LayoutSection s: layout){
               system.debug(s);
                for( Metadata.LayoutColumn c: s.layoutColumns){
                   system.debug(c);
                    if(c.layoutItems != null){
                        for( Metadata.layoutItem item: c.layoutItems){
                           system.debug(item);
                            fieldApiList.add(item.field);
                        }
                    }
                    
                }
            }
            
            system.debug(fieldApiList);
            ac = database.query(SoqlHelper.DistinctQueryFields('select id, AWS_Data_Id__c , ' + string.join(fieldApiList, ',') + ' from ' + sobjectType + ' where id = :rid'));
            
            data.put('data', ac);
        }
        if(!string.isBlank(pid)){
            data.put('pidType',pid.getSObjectType().getDescribe().getName());
        }
        data.put('fields', SObjectHelper.GetFieldInfos(sobjectType));
        data.put('staticResource', Json.serialize(PIHelper.getPIIntegrationInfo(sobjectType)));
        res.IsSuccess = true;
        return res;
    }
    
    @AuraEnabled
    public static ControllerResponse Save(Map<string,object> data,string transId){
        system.debug('data='+data);
        system.debug(!data.containsKey('Id') );
        system.debug( data.get('Id') == null);
        //NewAndEditBaseController.Response response = NewAndEditBaseController.save(new Agency_Contact__c(),Json.serialize(data),transId, !data.containsKey('Id') || data.get('Id') == null );
        //ControllerResponse r = new ControllerResponse();
        
        Sobject sobj = new Agency_Contact__c();
        ControllerResponse r = SaveCore(sobj, data, transId);
        if (r.IsSuccess) {
            r.Data = new Map<string,object>{
                'recordId'=> sobj.Id
            };
        }
        return r;
    }
    

    public static ControllerResponse SaveCore(Sobject sobj, Map<string,object> data,string transId ) {
        string sobjectTypeValue = sobj.getSObjectType().getDescribe().getName();
        System.debug('sobjectTypeValue:'+sobjectTypeValue+' Info:' + JSON.serialize(data));
        
        //1. Prepare the payload for  Lead
        Map<String, Schema.SObjectField> fieldAPIToTypeMap = SobjectHelper.GetFieldMap(sobjectTypeValue);
        ControllerResponse r = new ControllerResponse();
        
        //2. Save Record Process
        String awsDataId = string.valueOf(data.get('AWS_Data_Id__c'));
        Savepoint sp = Database.setSavepoint();
        try{
            for(string field : fieldAPIToTypeMap.keySet()){
                if(data.containsKey(field)){
                    sobj.put(field, data.get(field));
                }
            }
            if(!Test.isRunningTest()){
                upsert sobj;
            }
            PIHelper.saveTransLog(sobjectTypeValue,awsDataId,sobj.Id,transId, Json.serialize(data) ,'success','');
            //System.debug('respzhj = ' + resp);
            r.IsSuccess = true;
            return r;

        } catch(Exception e) {
            System.debug('into catch'+e.getMessage());
            Database.rollback(sp);
            r.IsSuccess = false;
            r.message = e.getMessage()+e.getStackTraceString();
            PIHelper.saveTransLog(sobjectTypeValue,awsDataId,sobj.Id,transId, Json.serialize(data) ,'failed',r.message);
            return r;
        }
    }
}