/**********************************************************************
 * 
 *
 * @url: /services/apexrest/rest
 * @data:
 *  {
        
    }
*************************************************************************/
@RestResource(urlMapping='/NFM707/*')
global with sharing class NFM707Rest {
    public static final String LOG_TYPE = 'NFM707';
    global class GeDatas {
        public NFMUtil.Monitoring Monitoring;
        public  GeData[] GeData;
    }
    global class GeData {
		public String MeetingApprovedNo; //	会议决裁编码
		public String Num; //	会议编码
		public String Competitor; //	竞品公司
		public String Publicity; //	宣传方式
		public String SocietyHoldPlace; //	会议日程
    }
    @HttpPost
    global static void execute() {
        // 取得接口传输内容
        String strData = RestContext.request.requestBody.toString();
        
        GeDatas geds = (GeDatas) JSON.deserializeStrict(strData, GeDatas.class);

        if (geds == null) {
            return;
        }

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

        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, LOG_TYPE, geds.GeData);
        // insert rowData;
        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 = '{"Result":{"Result":"00","Message":"成功"}}';
        res.responseBody = Blob.valueOf(jsonResponse);
        return;
    }
    @future(callout = true)
    global static void executefuture(String rowData_Id) {
        main(rowData_Id);
    }
    global static void main(String rowData_Id) {
        BatchIF_Log__c rowData = [Select Id, Name, 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, retry_cnt__c from BatchIF_Log__c where RowDataFlg__c = true and Id =: rowData_Id];

        String logstr = 'start\n';
        BatchIF_Log__c iflog = new BatchIF_Log__c();
        iflog.Type__c = LOG_TYPE;
        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
        iflog.Log__c = logstr;
        iflog.ErrorLog__c = '';
        insert iflog;

        String rowDataStr = NFMUtil.getRowDataStr(rowData);

        List < GeData > itemMasterList = (List < GeData > ) JSON.deserialize(rowDataStr, List < GeData > .class);
        logstr += '数据总数为：' + itemMasterList.size() + '\n';
        if (itemMasterList == null || itemMasterList.size() == 0) {
            return;
        }
        Savepoint sp = Database.setSavepoint();
        try {
        	List<Result_for_Conference_Adjudication__c> rcaList = new List<Result_for_Conference_Adjudication__c>();
        	Map<String,GeData> meetingApprovedNoMap = new Map<String,GeData>();
            // Map<String , String> camMap = new Map<String , String>();
	    	List<String> camList = new List<String>();
            for(GeData ged : itemMasterList){
                //验证数据完整性
                // String dataComplete = verify(ged);
                // if (!String.isBlank(dataComplete)) {
                //     logstr += dataComplete;
                //     iflog.ErrorLog__c += dataComplete;
                //     upsert iflog;
                //     continue;
                // }
                if (String.isNotBlank(ged.Num)) {
					// camMap.put(ged.Num, ged.MeetingApprovedNo);
                	camList.add(ged.MeetingApprovedNo);
                }
                meetingApprovedNoMap.put(ged.MeetingApprovedNo, ged);
            }
	    	if (meetingApprovedNoMap.size() > 0) {
                // 查询系统里的 会议决裁申请
	    		Map<String,Application_for_Conference_Adjudication__c> acaMap = getAcaMap(meetingApprovedNoMap);
	    		// 查询系统里的 市场活动
                Map<String,Campaign> campaignMap = new Map<String,Campaign>();
	            if (camList.size() > 0) {
                    campaignMap = getcampaignMap(camList);
	            }
	            for (String meetingApprovedNo : meetingApprovedNoMap.keySet()) {
	            	Result_for_Conference_Adjudication__c rca 		= new Result_for_Conference_Adjudication__c();
	            	GeData ged = meetingApprovedNoMap.get(meetingApprovedNo);
	            	if (!acaMap.containsKey(ged.MeetingApprovedNo)) {
	            		logstr += '会议决裁申请不存在，此条数据跳过';
                        iflog.ErrorLog__c += 'Error! MeetingApprovedNo['+ ged.MeetingApprovedNo +']NotExist. This data is skipped.\n';
                        upsert iflog;
	            		continue;
	            	}
	            	rca.Application_for_Conference_Adjudication__c	= acaMap.get(ged.MeetingApprovedNo).Id;
	            	rca.Competitor__c 							 	= ged.Competitor;
	            	rca.Publicity__c 							 	= ged.Publicity;
					rca.SocietyHoldPlace__c   					 	= ged.SocietyHoldPlace;
                    if (campaignMap.containsKey(ged.Num)) {
	            		rca.Campaign__c 							= campaignMap.get(ged.Num).Id;
                        // 更新会议日程
                        Campaign cam = campaignMap.get(ged.Num);
                        cam.Meeting_Report__c = rca.Id;
                        cam.Society_Hold_Place__c = rca.SocietyHoldPlace__c;
                        cam.Report_approved_day__c = Date.today();
	            	}
					rcaList.add(rca);
	            }
	            if (rcaList.size() > 0) {
	                insert rcaList;
	            }
                if (campaignMap.size() > 0) {
                    update campaignMap.values();
                }
	    	}
            logstr += '\nend';
            rowData.retry_cnt__c = 0;
        }catch (Exception ex) {
            Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
            // エラーが発生した場合
            Database.rollback(sp);
            logstr += '\n' + ex.getMessage();
            iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
            // 异常重发
            rowData = NFMUtil.LogAutoSend(rowData, ex, null);
        }
        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) + ' ...';
        }
        upsert iflog;

        
    }
    /**
     * [查询系统里的 会议决裁申请]
     * @param  meetingApprovedNoMap [description]
     * @return                      [description]
     */
    public static Map<String,Application_for_Conference_Adjudication__c> getAcaMap(Map<String,GeData> meetingApprovedNoMap){
        List<Application_for_Conference_Adjudication__c> acaList = [
                            select id,MeetingApprovedNo__c 
                            from Application_for_Conference_Adjudication__c 
                            where MeetingApprovedNo__c in: meetingApprovedNoMap.keySet()];
        Map<String,Application_for_Conference_Adjudication__c> acaMap = new Map<String,Application_for_Conference_Adjudication__c>();
        
        for (Application_for_Conference_Adjudication__c aca : acaList ) {
            acaMap.put(aca.MeetingApprovedNo__c, aca);
        }
        return acaMap;
    }

    /**
     * [查询系统里的 市场活动]
     * @param  camMap [description]
     * @return        [description]
     */
    public static Map<String,Campaign> getcampaignMap(List<String> camList){
        Map<String,Campaign> campaignMap = new Map<String,Campaign>();
        
        List<Campaign> camNoList = [select id,Num__c,MeetingApprovedNo__c
                                    from Campaign 
                                    where MeetingApprovedNo__c in: camList];
        if (camNoList.size() > 0) {
            for (Campaign cam : camNoList) {
                campaignMap.put(cam.Num__c, cam);
            }                              
        }                             
		return campaignMap;
		
    }



    // 必填字段验证
    private static String verify(GeData ged) {
        String result = '';
        if (String.isBlank(ged.MeetingApprovedNo)) {
            result += 'DataError: 会议决裁编码 [ MeetingApprovedNo ] is null!This data is skipped.\n';
        }
        if (String.isBlank(ged.SocietyHoldPlace)) {
            result += 'DataError: 会议日程 [ SocietyHoldPlace ] is null!This data is skipped.\n';
        }
        return result;
    }
}