public without sharing class AWSServiceTool2 {

    static Map<string,PIHelper.PIIntegration> staticResourceBuffer = new Map<string,PIHelper.PIIntegration>();
    static PIHelper.PIIntegration getPIIntegration(string sobject_name){
        system.debug('sobject_name='+sobject_name);
        if(!staticResourceBuffer.containsKey(sobject_name)){
            PIHelper.PIIntegration staticResource =  PIHelper.getPIIntegrationInfo(sobject_name);
            staticResourceBuffer.put(sobject_name,staticResource);
        }
        return staticResourceBuffer.get(sobject_name);
    }
    
    public static boolean EncryptPushData(List<string> Ids){
        if(ids == null || ids.size() == 0){
            return false;
        }
        
        Id rid = Ids[0];
        string sobject_name = rid.getSobjectType().getDescribe().getName();
        string sql = 'select id ';
        
        PIHelper.PIIntegration staticResource = getPIIntegration(sobject_name);
        for(PI_Field_Policy_Detail__c detail :staticResource.PIDetails){
            sql += ',' + detail.SF_Field_API_Name__c+',' + detail.SF_Field_Encrypted_API__c;
        }
        sql += ' ,AWS_Data_Id__c from ' + sobject_name + ' where id in :Ids';
        system.debug('sql='+sql);
        List<Sobject> lso = Database.query(sql);
        system.debug('lso.size()='+lso.size());
        if(lso.size()==0){
            return false;
        }
        return EncryptPushCore(Json.serialize(lso),sobject_name);
    }
    
    @future(callout=true)
    public static void EncryptPushFuture(string json_list,string sobject_name){
        EncryptPushCore(json_list,sobject_name);
    }
    
    // List<Rental_Apply__c> temps = [select id,AWS_Data_Id__c,name, direct_shippment_address__c,  Direct_Shippment_Address_Encrypt__c, Phone_number__c,  Phone_Number_Encrypt__c,CreatedDate   from Rental_Apply__c where AWS_Data_Id__c != null order by CreatedDate desc limit 2];
    public static boolean EncryptPushCore(string json_list,string sobject_name){
        system.debug('enter EncryptPushCore');
        system.debug(json_list);
        if(string.isBlank(json_list) || string.isBlank(sobject_name)){

            system.debug('json_list or sobject_name is null');
            return false;
        }
        
        //调用滨璜接口更新
        PIHelper.PIIntegration staticResource =  getPIIntegration(sobject_name);
        system.debug('staticResource.token='+staticResource.token);
        if(String.isBlank(staticResource.token)){
            System.debug('获取aws token 失败');
            return false;
        }
        List<object> newobjectList = (List<object>)Json.deserializeUntyped(json_list);
        Map<Id,Sobject> newMap = new Map<Id,Sobject>();
        
        for(object obj : newobjectList){
            Map<string,object> mobj = (Map<string,object>)obj;
            if(mobj.containsKey('Id')){
                Sobject sobj_temp = (Sobject)Json.deserialize(Json.serialize(obj), Type.forName(sobject_name));
                newMap.put(sobj_temp.Id,sobj_temp);
            }
        }
        List<Map<string,object>> insert_list = new List<Map<string,object>>();
        List<Map<string,object>> update_list = new List<Map<string,object>>();
        List<sobject> newList = newMap.values();
        for(Sobject ra : newList){
            Map<string,object> mso = new Map<string,object>();
            
            
            for(PI_Field_Policy_Detail__c detail : staticResource.PIDetails){
                if(ra.isSet(detail.SF_Field_API_Name__c)){
                    mso.put(detail.AWS_Field_API__c,ra.get(detail.SF_Field_API_Name__c));
                    mso.put(detail.AWS_Encrypted_Field_API__c,ra.get(detail.SF_Field_Encrypted_API__c));
                }
            }
            mso.put('sfRecordId',ra.Id);
            string aws_id = string.valueOf(ra.get('AWS_Data_Id__c'));
            system.debug('aws_id='+aws_id);
            if(string.isBlank(aws_id)){
                insert_list.add(mso);
            }else{
                system.debug('aws_id.lenth='+aws_id.length());
                mso.put('dataId',aws_id);
                update_list.add(mso);
            }
            
        }
        List<object> objList = new List<object>();
        List<Sobject> updateList = new List<Sobject>();
        List<object> temp = null;
        system.debug('insert_list.size()='+insert_list.size());
        system.debug('update_list.size()='+update_list.size());
        //if(true)return;
        if(insert_list.size() > 0){
            system.debug('url='+staticResource.newEncryptUrl);
            temp = PostAws(Json.serialize(insert_list),staticResource.newEncryptUrl,staticResource.token);
            if(temp != null){
                objList.addAll(temp);
            }
        }
        
        
        if(update_list.size() > 0){
            system.debug('url='+staticResource.updateEncryptUrl);
            temp = PostAws(Json.serialize(update_list),staticResource.updateEncryptUrl,staticResource.token);
            if(temp != null){
                objList.addAll(temp);
            }
        }
        
        system.debug('objList.size()='+objList.size());
        if(objList.size()==0){
            return false;
        }
        
       
        for(object obj : objList){
            Map<string,object> obj_map = (Map<string,object>)obj;
            string sfRecordId = null;
            string dataId = null;
            if(obj_map.containsKey('sfRecordId')){
                sfRecordId = string.valueOf(obj_map.get('sfRecordId'));
            }else{
                system.debug('obj_map.containsKey(\'sfRecordId\')='+obj_map.containsKey('sfRecordId'));
                continue;
            }
            
            if(obj_map.containsKey('dataId')){
                dataId = string.valueOf(obj_map.get('dataId'));
            }else{
                system.debug('obj_map.containsKey(\'dataId\')='+obj_map.containsKey('dataId'));
                continue;
            }
            
            
            if(newMap.containsKey(sfRecordId)){
                Sobject ra = newMap.get(sfRecordId);
                for(PI_Field_Policy_Detail__c detail : staticResource.PIDetails){
                    if(obj_map.containsKey(detail.AWS_Field_API__c)){
                        ra.put(detail.SF_Field_API_Name__c,obj_map.get(detail.AWS_Field_API__c));
                    }else{
                        system.debug('detail.AWS_Field_API__c='+detail.AWS_Field_API__c+' not in obj_map');
                    }
                    
                    if(obj_map.containsKey(detail.AWS_Encrypted_Field_API__c)){
                        ra.put(detail.SF_Field_Encrypted_API__c,obj_map.get(detail.AWS_Encrypted_Field_API__c));
                    }else{
                        system.debug('detail.AWS_Encrypted_Field_API__c='+detail.AWS_Encrypted_Field_API__c+' not in obj_map');
                    }
                }
                ra.put('AWS_Data_Id__c',dataId);
                
                updateList.add(ra);
            }else{
                system.debug('newMap.containsKey('+sfRecordId+')='+newMap.containsKey(sfRecordId));
                continue;
            }
        }
        
        system.debug('updateList.size='+updateList.size());
        if(updateList.size()>0){
            update updateList;
        }
        
        return true;
    }
    
    static List<object> PostAws(string payload,string url,string token){
        system.debug('payload='+payload);
        AWSServiceTool.response response = AWSServiceTool.sendToPiAWS(payload, url,token);
        system.debug(response);
        Map<string,object> res_obj = (Map<string,object>)Json.deserializeUntyped(response.responseBody);
        if(res_obj == null || !res_obj.containsKey('object') ){
            System.debug('res_obj == null || !res_obj.containsKey(\'object\')');
            return null;
        }
        
        List<object> objList = (List<object>)res_obj.get('object');
        if(objList == null){
            System.debug('objList == null');
            return null;
        }
        return objList;
    }

}