/**********************************************************************
 *
 *
 * @url: /services/apexrest/NFM623Rest
 * @data:
 *  {

    }
*************************************************************************/
@RestResource(urlMapping = '/NFM623/*')
global with sharing class NFM623Rest {
    /* 迁移ali sushanhu 20231018
     //add to AWS 回复 start sushanhu 20220225 
     static Boolean SFStatus=true;
     static String SFMessage='';
    //add to AWS 回复 end sushanhu 20220225 
    */
    //新增NFM623Rest 学会·活动参加人员接收数据接口 精琢技术 start

    global class GeDatas {
        public NFMUtil.Monitoring Monitoring;
        public  GeData[] GeData;
    }

    global class GeData {
        public String Num;                              // 活动编码
        public String Name;                             // 活动名称
        public ViewContactIdS[] ViewContactIdS;      //替换为aws存储凭据ID 20220225 sushanhu
        public LabelTypeS[] LabelTypeS;
    }

    global class ViewContactIdS {
    	public String ViewContactId;                     // 直播观看统一用户ID  
    }
    
    global class LabelTypeS {
    	public String LabelType;                         // 标签分类
    	public String Label;                             // 标签内容 
    }

    @HttpPost
    global static void execute() {
       
        // 取得接口传输内容
        String strData = RestContext.request.requestBody.toString();
        GeDatas ges = (GeDatas) JSON.deserializeStrict(strData, GeDatas.class);

        if (ges == null ) {
            return;
        }

        NFMUtil.Monitoring Monitoring = ges.Monitoring;
        if (Monitoring == null) {
            return;
        }

        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'NFM623', ges.GeData);
        if (String.isBlank(rowData.Log__c) == false) {
            executefuture(rowData.Id);
        }

        // JSONを戻す
        RestResponse res = RestContext.response;
        res.addHeader('Content-Type', 'application/json');
        res.statusCode = 200;
        String jsonResponse = '{"status": "Success", "Message":""}';
        res.responseBody = blob.valueOf(jsonResponse);
        /* 迁移ali sushanhu 20231018
        //updata response toAWS 20220225 sushanhu start
        NFMUtil.NFMResponse result = NFMUtil.getNFMResponse();
        result.SFStatus=SFStatus;
        result.SFMessage=SFMessage;
        String jsonResponse =JSON.serialize(result);
        system.debug('result---'+jsonResponse);
        res.responseBody = blob.valueOf(jsonResponse);
        //updata response toAWS 20220225 sushanhu end
        */
        return;
    }

    @future
    global static void executefuture(String rowData_Id) {
        main(rowData_Id);
    }

    global static void main (String rowData_Id) {

        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
        BatchIF_Log__c rowData = [Select Id, Name, retry_cnt__c, Log__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c, Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c from BatchIF_Log__c where RowDataFlg__c = true and Id = :rowData_Id];
        String logstr = rowData.MessageGroupNumber__c + ' start\n';
        BatchIF_Log__c iflog = new BatchIF_Log__c();
        iflog.Type__c = 'NFM623';
        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
        iflog.Log__c = logstr;
        iflog.ErrorLog__c = '';
        insert iflog;

        String rowDataStr = NFMUtil.getRowDataStr(rowData);
        List<GeData> geDataList = (List<GeData>) JSON.deserialize(rowDataStr, List<GeData>.class);

        if (geDataList == null || geDataList.size() == 0) {
            return;
        }

		Savepoint sp = Database.setSavepoint();

        try {
            List<Campaign> camInsList = new List<Campaign>();
        	List<CampaignMember__c> camMemInsList = new List<CampaignMember__c>();
            List<CampaignLable__c> camLabInsList = new List<CampaignLable__c>();

            //将市场活动编码存入List,统一用户ID存如Map
            List<String> camNoList = new List<String>();
            List<String> conIDListNew = new List<String>();
            Map<String, String> conIDMapNew = new Map<String, String>();
            List<GeData> geDataListNew = new List<GeData>();
            for (GeData geData : geDataList) {
            	if (String.isBlank(geData.Num)) {
            		//必須項目がない場合、処理と飛ばす
                    iflog.ErrorLog__c += '活动编码不能为空。\n';
                    continue;
            	}
                if (geData.ViewContactIdS == null || geData.ViewContactIdS.size() == 0) {
                    //必須項目がない場合、処理と飛ばす
                    iflog.ErrorLog__c += '统一用户ID不能为空。\n';
                    continue;
                }
                for (ViewContactIdS viewConIdS : geData.ViewContactIdS) {
                    conIDListNew.add(viewConIdS.ViewContactId);
                    conIDMapNew.put(geData.Num, viewConIdS.ViewContactId);
                }
                camNoList.add(geData.Num);
                geDataListNew.add(geData);
            }
            //使用统一用户ID获取客户人员ID、客户人员姓名、医院科室存入Map
            Map<String, Contact> contactMap = new Map<String, Contact>();
            List<String> conIDList = new List<String>();
            if (conIDMapNew.size() > 0) {	
                List<Contact> contactList = [select Id,Name,UnifiedI_Contact_ID__c,
                                            AccountId,Account.Name 
                                            from Contact where UnifiedI_Contact_ID__c in :conIDListNew];
                if (contactList.size() > 0) {
                    //客户人员ID获取成功
                    for (Contact conInfo : contactList) {
                        contactMap.put(conInfo.UnifiedI_Contact_ID__c, conInfo);
                        conIDList.add(conInfo.Id);
                    }
                } 
                //update to 通过aws存储的unified查询 start 20220225
                // List<Contact> contactList = [select Id,Name,AWS_UnifiedI_Contact_ID__c,
                //                             AccountId,Account.Name 
                //                             from Contact where AWS_UnifiedI_Contact_ID__c in :conIDListNew];	
                // if (contactList.size() > 0) {
                //     //客户人员ID获取成功
                //     for (Contact conInfo : contactList) {
                //         contactMap.put(conInfo.AWS_UnifiedI_Contact_ID__c, conInfo);
                //         conIDList.add(conInfo.Id);
                //     }
                // } 
                //update to 通过aws存储的unified查询 20220225 end
            }
            //使用市场活动编码获取市场活动ID和活动名称存入Map
            List<String> camIDList = new List<String>();
            Map<String, Campaign> camOldMap = new Map<String, Campaign>();
            List<Campaign> campList = [select Id, Num__c, Name2__c from Campaign where Num__c in :camNoList];
            if (campList.size() > 0) {
                //市场活动ID获取成功
                for (Campaign camInfo : campList) {
                    camIDList.add(camInfo.Id);
                    camOldMap.put(camInfo.Num__c, camInfo);
                }
            } 
            
            //查询已经存在的市场活动编码下的参会人员ID和统一用户ID
            List<CampaignMember__c>  camMemberList = [select Id,Contact_ID__c,ViewContactId__c,
                                                        Campaign__c,Campaign__r.Num__c 
                                                        from CampaignMember__c where Campaign__c in : camIDList];
            Map<String, String> camContactMap = new Map<String, String>();
            Map<String, String> camViewContactMap = new Map<String, String>();
            if (camMemberList.size() > 0 ) {
                for (CampaignMember__c cm : camMemberList) {
                    camContactMap.put(cm.Contact_ID__c, cm.Campaign__r.Num__c);
                    camViewContactMap.put(cm.ViewContactId__c, cm.Campaign__r.Num__c);
                }
            }
            
            //update to 获取aws 统一凭据关联 sushanhu 20220225 satrt
            // List<CampaignMember__c>  camMemberList = [select Id,Contact_ID__c,AWS_ViewContact_Id__c,
            //                                             Campaign__c,Campaign__r.Num__c 
            //                                             from CampaignMember__c where Campaign__c in : camIDList];
            // Map<String, String> camContactMap = new Map<String, String>();
            // Map<String, String> camViewContactMap = new Map<String, String>();
            // if (camMemberList.size() > 0 ) {
            //     for (CampaignMember__c cm : camMemberList) {
            //         camContactMap.put(cm.Contact_ID__c, cm.Campaign__r.Num__c);
            //         camViewContactMap.put(cm.AWS_ViewContact_Id__c, cm.Campaign__r.Num__c);
            //     }
            // }
             //update to 获取aws 统一凭据关联 sushanhu 20220225 end
            //将原有活动标签对象中市场活动ID和标签活动名称存入Map中
            List<CampaignLable__c> camLabInfoList = [select id,name,Campaign__c,Lable__c,LableType__c from CampaignLable__c where  Campaign__c in : camIDList];
            Map<String, String> camLabInfoMap = new Map<String, String>();
            if (camLabInfoList.size() > 0) {
                for (CampaignLable__c camLabIn : camLabInfoList) {
                    camLabInfoMap.put(camLabIn.Name,camLabIn.Id);
                }
            }
            

            // 将XML各数据项更新到市场活动、学会・活动参加人员及活动标签对象中
            for (GeData geData : geDataListNew) {
                 
                if (camOldMap.get(geData.Num) == null) {
                    iflog.ErrorLog__c += '市场活动编码' + geData.Num +'：不存在\n';
                    continue;
                }
                //插入学会参会人员对象
                for (ViewContactIdS viewConIdS : geData.ViewContactIdS) {
                    CampaignMember__c camMemberInfo = new CampaignMember__c();
                    if (contactMap.get(viewConIdS.ViewContactId) != null) {
                        if (camContactMap.get(contactMap.get(viewConIdS.ViewContactId).ID) != geData.Num) {
                            camMemberInfo.Contact_ID__c = contactMap.get(viewConIdS.ViewContactId).ID;                   //参会人员ID
                            camMemberInfo.Campaign__c = camOldMap.get(geData.Num).ID;                                    //活动ID
                            camMemberInfo.Department_ID__c = contactMap.get(viewConIdS.ViewContactId).AccountId;         //医院科室
                            camMemberInfo.Department__c = contactMap.get(viewConIdS.ViewContactId).Account.Name;         //医院科室（文本）
                            camMemberInfo.Contact__c = contactMap.get(viewConIdS.ViewContactId).Name;                    //客户人员姓名
                            camMemInsList.add(camMemberInfo);
                        }
                        
                    } else {
                        if (camViewContactMap.get(viewConIdS.ViewContactId) != geData.Num) {
                            camMemberInfo.Campaign__c = camOldMap.get(geData.Num).ID;
                            camMemberInfo.ViewContactId__c = viewConIdS.ViewContactId;
                            camMemInsList.add(camMemberInfo);
                        }
                        
                    }
                }
                //插入活动标签对象
                for (LabelTypeS labelTypeS : geData.LabelTypeS) {
                    List<String> lableList = labelTypeS.Label.split(';');
                    if (lableList.size() > 0) {
                        for (Integer i= 0 ; i < lableList.size(); i++) {
                            CampaignLable__c campaignLable = new CampaignLable__c();
                            if (camOldMap.get(geData.Num) != null ) {
                                campaignLable.Campaign__c = camOldMap.get(geData.Num).ID;
                                campaignLable.LableType__c = labelTypeS.LabelType;
                                campaignLable.Lable__c = lableList[i];
                                campaignLable.Name = campaignLable.LableType__c+'-'+campaignLable.Lable__c;
                                if (String.isBlank(camLabInfoMap.get(campaignLable.Name))) {
                                    camLabInsList.add(campaignLable);
                                }
                            }
                        }
                    }
                }
            }
            
            if (camMemInsList.size() > 0) {
                upsert camMemInsList;
                logstr += '学会参会人员更新成功。\n';
            }

            if (camLabInsList.size() > 0) {
                insert camLabInsList;
                logstr += '活动标签更新成功。\n';
            }

            logstr += '\nend';
            rowData.retry_cnt__c = 0;

        } catch (Exception ex) {
            // エラーが発生した場合
            Database.rollback(sp);
            System.debug(Logginglevel.ERROR, 'NFM623_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM623_' + rowData.MessageGroupNumber__c + ':' + ex.getStackTraceString());
            logstr += '\n' + ex.getMessage();
            iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
            if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
            if (rowData.retry_cnt__c < batch_retry_max_cnt) {
                rowData.retry_cnt__c++;
                LogAutoSendSchedule.assignOneMinute();
            }
            if (rowData.retry_cnt__c >= batch_retry_max_cnt) {
                rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c + '错误次数已经超过自动收信设定的最大次数，请手动收信';
            }
        }

        update rowData;
        iflog.Log__c = logstr;
        if (iflog.Log__c.length() > 131072) {
            iflog.Log__c = iflog.Log__c.subString(0, 131065) + ' ...';
        }
        if (iflog.ErrorLog__c.length() > 32768) {
            iflog.ErrorLog__c = iflog.ErrorLog__c.subString(0, 32760) + ' ...';
        }
        update iflog;
    }
    //新增NMF623接口 精琢技术 end
}