//zhj MEBG新方案改造 2022-11-27
global without sharing class AWSServiceTool2V2 {

    public static Map<String,String>  matchupMap;

    public static void assignmentMatchupMap() {
        //map的键对应医院表上ocsm管理省值
        //map的值对应地址表上类型为办事处的 省+','+市
        matchupMap = new Map<String,String>();
        matchupMap.put('黑龙江','黑龙江,哈尔滨市');
        matchupMap.put('青海','青海省,西宁市');
        matchupMap.put('陕西','陕西省,西安市');
        matchupMap.put('重庆','重庆市,渝中区');
        matchupMap.put('贵州','贵州省,贵阳市');
        matchupMap.put('福建','福建省,福州市');
        matchupMap.put('甘肃','甘肃省,兰州市');
        matchupMap.put('湖南','湖南省,长沙市');
        matchupMap.put('湖北','湖北省,武汉市');
        matchupMap.put('深圳','广东省,深圳市');
        matchupMap.put('广东','广东省,广州市');
        //matchupMap.put('海南','');//没有
        matchupMap.put('浙江','浙江省,杭州市');
        matchupMap.put('河南','河南省,郑州市');
        matchupMap.put('河北','河北省,石家庄市');
        matchupMap.put('沈阳','辽宁省,沈阳市');
        matchupMap.put('大连','辽宁省,大连市');
        matchupMap.put('江西','江西省,南昌市');
        matchupMap.put('江苏','江苏省,南京市');
        matchupMap.put('新疆','新疆维吾尔自治区,乌鲁木齐市');
        matchupMap.put('广西','广西自治区,南宁市');
        matchupMap.put('山西','山西省,太原市');
        matchupMap.put('山东,济南市','山东省,济南市');
        matchupMap.put('山东,青岛市','山东省,青岛市');
        matchupMap.put('安徽','安徽省,合肥市');
        matchupMap.put('宁夏','宁夏回族自治区,银川市');
        matchupMap.put('天津','天津市,河西区');
        matchupMap.put('四川/西藏','四川省,成都市');
        matchupMap.put('吉林','吉林省,长春市');
        matchupMap.put('北京','北京市,朝阳区');
        matchupMap.put('内蒙古','内蒙古自治区,呼和浩特市');
        matchupMap.put('云南','云南省,昆明市');
        //add        wangweipeng                 2021/12/27         start
        matchupMap.put('上海','上海市,徐汇区');
        //add        wangweipeng                 2021/12/27         end
    }


    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 EncryptPushDataRepair(String rid){
        if(String.isBlank(rid)){
            return false;
        }
        assignmentMatchupMap();
        System.debug('matchupMap = ' + matchupMap);
        Map<String,PIHelper.PIIntegration> staticResource = new Map<String,PIHelper.PIIntegration>();
        staticResource.put('Repair__c',PIHelper.getPIIntegrationInfo('Repair__c'));
        staticResource.put('Contact',PIHelper.getPIIntegrationInfo('Contact'));
        staticResource.put('Address__c',PIHelper.getPIIntegrationInfo('Address__c'));
        Map<String, Map<String, PI_Field_Policy_Detail__c>> mmsp = new Map<String, Map<String,PI_Field_Policy_Detail__c>>();
        for (String key : staticResource.keySet()) {
            mmsp.put(key, new Map<String,PI_Field_Policy_Detail__c>());
            for (PI_Field_Policy_Detail__c detail : staticResource.get(key).PIDetails) {
                mmsp.get(key).put(detail.SF_Field_API_Name__c, detail);
            }
        }

        //1.查询出对应修理的数据
        Repair__c repair = [select Id,Hospital__c,address_Contacts__c,AWS_Data_Id__c from Repair__c where id=:rid];
        Account ac = [SELECT id,OCM_man_province_txt__c,FieldCity_Master_Name__c from Account where id =:repair.Hospital__c];
        String province = '';
        String city = '';
        String provinceAndCity = '';
        if('山东' == ac.OCM_man_province_txt__c){
            if('烟台市' == ac.FieldCity_Master_Name__c || '威海市' == ac.FieldCity_Master_Name__c || '日照市' == ac.FieldCity_Master_Name__c 
                || '青岛市' == ac.FieldCity_Master_Name__c || '潍坊市' == ac.FieldCity_Master_Name__c){
                provinceAndCity = matchupMap.get('山东,青岛市');
            }else{
                provinceAndCity = matchupMap.get('山东,济南市');
            }
        }else{
            provinceAndCity = matchupMap.get(ac.OCM_man_province_txt__c);
        }
        if(provinceAndCity != null){
            province = provinceAndCity.split(',')[0];
            city = provinceAndCity.split(',')[1];
        }
        String addressSQl = 'SELECT ID,AWS_Data_Id__c,Customer__c,Customer_Name__c,Contacts__c,Contacts__r.AWS_Data_Id__c,Contacts_Name__c,Telephone__c,Province__c,Province_Name__c,City__c,City_Name__c,Detailed_Address__c,ZipCode__c'
        + ' from Address__c  '
        + ' where Address_Classification__c =  \'办事处\' and Province_Name__c =: province and City_Name__c =: city '
        + ' order by Using_Datetime__c desc NULLS LAST ';
        system.debug('addressSQl='+addressSQl);
        List<Address__c> addressList = Database.query(addressSQl);
        //开始组装数据
        List<AWSServiceTool2V2.EncryptPushRequestBody> EncryptPushList = new List<AWSServiceTool2V2.EncryptPushRequestBody>();
        AWSServiceTool2V2.EncryptPushRequestBody EncryptPush = new AWSServiceTool2V2.EncryptPushRequestBody();
        EncryptPush.dataId = repair.AWS_Data_Id__c != null ?repair.AWS_Data_Id__c:'';
        EncryptPush.sfRecordId = repair.Id;
        EncryptPush.fieldsMapping = new Map<String, List<AWSServiceTool2V2.EncryptPushRes>>();
        //联系人名称，如果对应收货地址的联系人没有，就不更新该字段
        if(!String.isBlank(addressList[0].Customer__c)){
            List<AWSServiceTool2V2.EncryptPushRes> resList = new List<AWSServiceTool2V2.EncryptPushRes>();
            AWSServiceTool2V2.EncryptPushRes res = new AWSServiceTool2V2.EncryptPushRes();
            res.isQueryDb = true;
            res.table = staticResource.get('Contact').awsTableName;
            res.field = mmsp.get('Contact').get('LastName').AWS_Field_API__c;
            res.value = '';
            res.dataId = addressList[0].Contacts__r.AWS_Data_Id__c;
            resList.add(res);
            EncryptPush.fieldsMapping.put(mmsp.get('Repair__c').get('address_Contacts__c').AWS_Field_API__c, resList);
        }
        //邮编
        List<AWSServiceTool2V2.EncryptPushRes> resList2 = new List<AWSServiceTool2V2.EncryptPushRes>();
        AWSServiceTool2V2.EncryptPushRes res2 = new AWSServiceTool2V2.EncryptPushRes();
        res2.isQueryDb = true;
        res2.table = staticResource.get('Address__c').awsTableName;
        res2.field = mmsp.get('Address__c').get('ZipCode__c').AWS_Field_API__c;
        res2.value = '';
        res2.dataId = addressList[0].AWS_Data_Id__c;
        resList2.add(res2);
        EncryptPush.fieldsMapping.put(mmsp.get('Repair__c').get('address_ZipCode__c').AWS_Field_API__c, resList2);

        //address_Telephone__c
        List<AWSServiceTool2V2.EncryptPushRes> resList3 = new List<AWSServiceTool2V2.EncryptPushRes>();
        AWSServiceTool2V2.EncryptPushRes res3 = new AWSServiceTool2V2.EncryptPushRes();
        res3.isQueryDb = true;
        res3.table = staticResource.get('Address__c').awsTableName;
        res3.field = mmsp.get('Address__c').get('Telephone__c').AWS_Field_API__c;
        res3.value = '';
        res3.dataId = addressList[0].AWS_Data_Id__c;
        resList3.add(res3);
        EncryptPush.fieldsMapping.put(mmsp.get('Repair__c').get('address_Telephone__c').AWS_Field_API__c, resList3);

        String cityName = '';
        String ProvinceCity = '';
        if(String.isNotBlank(addressList[0].City_Name__c))
            cityName = addressList[0].City_Name__c.trim();
        if(String.isNotBlank(addressList[0].Province_Name__c))
            ProvinceCity = addressList[0].Province_Name__c.trim()+cityName;

        //Detailed_Address__c
        List<AWSServiceTool2V2.EncryptPushRes> resList4 = new List<AWSServiceTool2V2.EncryptPushRes>();
        AWSServiceTool2V2.EncryptPushRes res4 = new AWSServiceTool2V2.EncryptPushRes();
        res4.isQueryDb = false;
        res4.table = '';
        res4.field = '';
        res4.value = ProvinceCity;
        resList4.add(res4);
        AWSServiceTool2V2.EncryptPushRes res5 = new AWSServiceTool2V2.EncryptPushRes();
        res5.isQueryDb = true;
        res5.table = staticResource.get('Address__c').awsTableName;
        res5.field = mmsp.get('Address__c').get('Detailed_Address__c').AWS_Field_API__c;
        res5.value = '';
        res5.dataId = addressList[0].AWS_Data_Id__c;
        resList4.add(res5);
        EncryptPush.fieldsMapping.put(mmsp.get('Repair__c').get('Detailed_Address__c').AWS_Field_API__c, resList4);
        EncryptPushList.add(EncryptPush);
        System.debug('EncryptPushListdataId = ' + JSON.serialize(EncryptPushList[0].dataId));
        System.debug('EncryptPushListsfRecordId = ' + JSON.serialize(EncryptPushList[0].sfRecordId));
        System.debug('EncryptPushListfieldsMapping = ' + JSON.serialize(EncryptPushList[0].fieldsMapping));
        System.debug('EncryptPushList = ' + JSON.serialize(EncryptPushList));

        List<Repair__c> aclist = new List<Repair__c>();
        aclist.add(repair);
        return EncryptPushCoreV2(Json.serialize(EncryptPushList),Json.serialize(aclist), 'Repair__c');
    }

    //创建/更新联系人之后，创建/更新.客户人员，并且发给AWS
    @future(callout=true)
    public static void EncryptPushFutureV2(string json_list,string acList,string sobject_name){
        EncryptPushCoreV2(json_list,acList,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 EncryptPushCoreV2(string json_list,string acList,string sobject_name){
        system.debug('enter EncryptPushCoreV2');
        if(string.isBlank(json_list) || string.isBlank(sobject_name) || string.isBlank(acList)){
            system.debug('json_list or sobject_name is null');
            return false;
        }
        
        //调用滨璜接口更新
        PIHelper.PIIntegration staticResourceV2 =  getPIIntegration(sobject_name+'V2');
        system.debug('json_list='+json_list);
        system.debug('acList='+acList);
        system.debug('staticResourceV2.token='+staticResourceV2.token);
        system.debug('staticResourceV2='+staticResourceV2);
        system.debug('staticResourceV2.newEncryptUrl='+staticResourceV2.newEncryptUrl);
        if(String.isBlank(staticResourceV2.token)){
            System.debug('获取aws token 失败');
            return false;
        }

        Map<String,Object> temp = null;
        List<object> objList = new List<object>();
        temp = PostAws(json_list,staticResourceV2.newEncryptUrl,staticResourceV2.token);
        System.debug('temp = ' + temp);
        if(temp == null){
            System.debug('temp == null');
            return false;
        }
        List<object> newobjectList = (List<object>)Json.deserializeUntyped(acList);
        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);
            }
        }
        System.debug('newMap = ' + newMap);
        //进行更新，根据dataid
        List<Sobject> updateList = new List<Sobject>();
        for(String key : newMap.keySet()){ 
            if(temp.containsKey(key)){
                Sobject ra = newMap.get(key);
                ra.put('AWS_Data_Id__c',String.valueOf(temp.get(key)));
                updateList.add(ra);
            }
        }
        System.debug('updateList = ' + updateList);
        if(updateList.size() > 0){
            update updateList;
        }
        return true;




    //     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 Map<String,Object> PostAws(string payload,string url,string token){
        system.debug('payload='+payload);
        system.debug('url='+url);
        system.debug('token='+token);
        NFMUtil.response response = NFMUtil.sendToPiAWS(payload, url,token);
        system.debug('response = ' + 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;
        }
        
        Map<String,Object> objMap = (Map<String,Object>)res_obj.get('object');
        System.debug('objMap =' + objMap);
        if(objMap == null){
            System.debug('objMap == null');
            return null;
        }
        return objMap;
    }


    global class EncryptPushRequestBody {
        // aws dataid 目标对象
        public String dataId {set; get;} 
        // sfID 记录Id 目标对象
        public String sfRecordId {set; get;} 
        // 字段映射 如：name:{}
        public Map<String, List<EncryptPushRes>> fieldsMapping {set; get;} 

        public EncryptPushRequestBody(String dataId, String sfRecordId, Map<String, List<EncryptPushRes>> fieldsMapping) {
            this.dataId = dataId;
            this.sfRecordId = sfRecordId;
            this.fieldsMapping = fieldsMapping;
        }
        public EncryptPushRequestBody() {
        }
   }

   global class EncryptPushRes{
        public Boolean isQueryDb;
        public String table;
        public String dataId;
        public String field;
        public String value;

        public EncryptPushRes(Boolean isQueryDb, String table, String dataId, String field, String value) {
            this.isQueryDb = isQueryDb;
            this.table = table;
            this.dataId = dataId;
            this.field = field;
            this.value = value;
        }
        public EncryptPushRes() {}
   }
}