public with sharing class NFM622Controller {
    public class Actives_element {
        public NFMUtil.MonitoringToOnline Monitoring;
        public Active_element[] GeData;
    }

    public class Active_element {
        public String Num;
        public String Name;
        public String Status;
        public String StartDate; 
        public String EndDate; 
    }
    /**
     * NFM622の送信処理
     * 
     * @param iflog_Id     //日志表的ID
     * @param actIds       //发送目标活动
     */
    @future (callout=true)
    public static void callout(String iflog_Id, List<String> actIds) {
        if (actIds == null || actIds.size() == 0) {
            return;
        }
        //MessageGroupNumber的获取
        List<BatchIF_Log__c> iflogList = [Select Id, Name, Log__c, ErrorLog__c from BatchIF_Log__c where Id = :iflog_Id];
        BatchIF_Log__c iflog = null;
        if (iflogList.size() > 0) {
            iflog = iflogList.get(0);
            iflog.ErrorLog__c = '';
        } else {
            //没有取得数据，就是被rollback了
            return;
        }
        System.debug('iflogList---->'+iflogList);
        //数据的查询
        List<Campaign> itemList = [select id, Num__c, Name2__c, Status, StartDate, EndDate 
                                        from Campaign where id IN:actIds];
        //Monitoring的设定
        String logstr = null;
        for(Campaign item : itemList){
            logstr = iflog.Log__c + '\nNumberOfRecord=' + actIds.size() + '\n学会编码:' + item.Num__c;
        }
        Datetime nowDT = Datetime.now();
        String nowStr = nowDT.format('yyyyMMddHHmm');
        Actives_element actives = new Actives_element();
        actives.Monitoring = new NFMUtil.MonitoringToOnline();
        actives.Monitoring.TransmissionDateTime = nowStr;
        actives.Monitoring.Text                 = ''; 
        actives.Monitoring.Tag                  = 'MSGH';
        actives.Monitoring.Sender               = 'SFDC';
        actives.Monitoring.Receiver             = '智慧医疗';
        actives.Monitoring.NumberOfRecord       = '' + itemList.size();
        actives.Monitoring.MessageType          = 'NFM622';
        actives.Monitoring.MessageGroupNumber   = iflog.Name;
        actives.Monitoring.username             = 'SFDC';
        actives.Monitoring.password             = 'sfdcsendtoonline';

        BatchIF_Log__c rowData = null;

        //数据的设定
        try {
            actives.GeData = new List<Active_element>();
            for(Campaign cam : itemList){
                Active_element active = new Active_element();
                actives.GeData.add(active);
                active.Num = cam.Num__c;
                active.Name = cam.Name2__c;
                active.Status = cam.Status;
                active.StartDate = NFMUtil.formatDate2Str(cam.StartDate);
                active.EndDate = NFMUtil.formatDate2Str(cam.EndDate);
            }  
            System.debug('actives.GeData.size--->'+actives.GeData.size());
            if (actives.GeData.size() > 0) {
                        
                NFMUtil.Monitoring Monitoring = new NFMUtil.Monitoring();
                Monitoring.Tag                  = actives.Monitoring.Tag;
                Monitoring.Sender               = actives.Monitoring.Sender;
                Monitoring.Receiver             = actives.Monitoring.Receiver;
                Monitoring.MessageType          = actives.Monitoring.MessageType;
                Monitoring.MessageGroupNumber   = actives.Monitoring.MessageGroupNumber;
                Monitoring.NumberOfRecord       = actives.Monitoring.NumberOfRecord;
                Monitoring.TransmissionDateTime = actives.Monitoring.TransmissionDateTime;
                Monitoring.Text = '';
                
                rowData = NFMUtil.makeRowData(Monitoring, 'NFM622', actives);
                execute(rowData, iflog);
            } 
            logstr += '\n end';
            //测试类可以进catch
            if (System.Test.isRunningTest()) {
                throw new ControllerUtil.myException('aaa');
            }
        } catch(Exception ex) {
            //发生错误的情况
            System.debug(Logginglevel.ERROR, 'NFM622_' + iflog.Name + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM622_' + iflog.Name + ':' + ex.getStackTraceString());
            logstr += ex.getMessage();
            iflog.ErrorLog__c += ex.getMessage() + '\n';
            iflog.ErrorLog__c += ex.getStackTraceString() + '\n';
        }
        System.debug('rowData--->'+rowData);
        if (rowData != null) {
            upsert rowData;
        }

        System.debug(Logginglevel.DEBUG, 'NFM622_' + iflog.Name + ' end');
        iflog.Log__c = logstr;
        upsert iflog;
    }

    public static void execute(BatchIF_Log__c rowData, BatchIF_Log__c iflog) {
        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
        String rowDataStr = NFMUtil.getRowDataStr(rowData);
        Actives_element actives = (Actives_element) JSON.deserialize(rowDataStr, Actives_element.class);

        String logstr = actives.Monitoring.MessageGroupNumber + ' start\n';
        System.debug('rowData1:'+ rowData);
        System.debug('iflog1:' + iflog);
        Boolean needUpdateIflog = false;
        if (iflog == null) {
            needUpdateIflog = true;
            iflog = new BatchIF_Log__c();
            iflog.Type__c = 'NFM622';
            iflog.MessageGroupNumber__c = actives.Monitoring.MessageGroupNumber;
            iflog.Log__c = logstr;
            iflog.ErrorLog__c = '';
        } else {
            iflog.MessageGroupNumber__c = iflog.Name;
            logstr = iflog.Log__c;
        }

        try{
            // 向智慧医疗发送接口
            String status =  NFMUtil.sendToComPlat(rowDataStr, NFMUtil.NFM622_ENDPOINT);
            if ('OK'.equals(status)) {
            	logstr += '\n'+status;
            	rowData.retry_cnt__c = 0;
            }
        } catch (Exception ex) {
            //发生错误的情况
            logstr += ex.getMessage();
            iflog.ErrorLog__c += ex.getMessage() + '\n';
            iflog.ErrorLog__c += ex.getStackTraceString() + '\n';

            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+'错误次数已经超过自动送信设定的最大次数，请手动送信';
            }
        }
        iflog.Log__c = logstr;
        System.debug('logdate2' + rowData);

        if (needUpdateIflog) {
            upsert iflog;
            System.debug('iflog------>'+iflog);
            upsert rowData;
        }
    }

}