public with sharing class NFM115Controller {
    public static String status;
    public class Samples {
        public NFMUtil.Monitoring Monitoring;
        public Sample[] Sample;
    }
    //样本订货单
    public class Sample {
        public String AgentCode;
        public String DeliveryAddress;
        public String DeliveryContact;
        public String DeliveryPhone;
        public String AreaCode;
        public Detail[] Detail;
    }
    //样本订货单明细
    public class Detail {
        public String ItemCode;
        public String ItemQuantity;
    }

    /**
     * NFM115の送信処理
     * 
     * @param iflog_Id     //日志表的ID
     * @param samIds       //发送样本订货单
     */
    @future (callout=true)
    public static void callout(String iflog_Id, List<String> samIds) {
        if (samIds == null || samIds.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;
        }
        //Monitoring的设定
        String logstr = iflog.Log__c + '\nNumberOfRecord=' + samIds.size();
        Datetime nowDT = Datetime.now();
        String nowStr = nowDT.format('yyyyMMddHHmm');
        Samples samples = new Samples();
        samples.Monitoring = new NFMUtil.Monitoring();
        samples.Monitoring.TransmissionDateTime = nowStr;
        samples.Monitoring.Text                 = ''; 
        samples.Monitoring.Tag                  = 'MSGH';
        samples.Monitoring.Sender               = 'SFDC';
        samples.Monitoring.Receiver             = 'SAP';
        samples.Monitoring.NumberOfRecord       = '' + samIds.size();
        samples.Monitoring.MessageType          = 'NFM115';
        samples.Monitoring.MessageGroupNumber   = iflog.Name;

        BatchIF_Log__c rowData = null;
        try {
            List<Sample_order_list__c> samList = [select Id, AgentCode__c, DeliveryAddress__c, DeliveryContact__c, DeliveryPhone__c, Account__c, 
                                                    Account__r.City_Master__r.Level2_Sys_No__c 
                                                    from Sample_order_list__c where Id IN:samIds];
            List<Sample_order_list_detail__c> samDetailList = [select id, ItemCode__c, ItemQuantity__c, Sample_order_list__c 
                                                                from Sample_order_list_detail__c where Sample_order_list__c IN:samIds];
            
            samples.Sample = new List<Sample>();
            for(Sample_order_list__c sam : samList){
                Sample sample = new Sample();
                sample.AgentCode       = sam.AgentCode__c;
                sample.DeliveryAddress = sam.DeliveryAddress__c;
                sample.DeliveryContact = sam.DeliveryContact__c;
                sample.DeliveryPhone   = sam.DeliveryPhone__c;
                sample.AreaCode        = sam.Account__r.City_Master__r.Level2_Sys_No__c;
                sample.Detail   = new List<Detail>();
                samples.Sample.add(sample);
                for(Sample_order_list_detail__c samDetail : samDetailList){
                    if(samDetail.Sample_order_list__c == sam.Id){
                        Detail Detail = new Detail();
                        Detail.ItemCode     = samDetail.ItemCode__c;
                        Detail.ItemQuantity = String.valueOf(samDetail.ItemQuantity__c);
                        sample.Detail.add(Detail);
                    }
                }
            }
            if(samples.Sample.size() > 0){
                NFMUtil.Monitoring Monitoring   = new NFMUtil.Monitoring();
                Monitoring.Tag                  = samples.Monitoring.Tag;
                Monitoring.Sender               = samples.Monitoring.Sender;
                Monitoring.Receiver             = samples.Monitoring.Receiver;
                Monitoring.MessageType          = samples.Monitoring.MessageType;
                Monitoring.MessageGroupNumber   = samples.Monitoring.MessageGroupNumber;
                Monitoring.NumberOfRecord       = samples.Monitoring.NumberOfRecord;
                Monitoring.TransmissionDateTime = samples.Monitoring.TransmissionDateTime;
                Monitoring.Text = '';
                
                rowData = NFMUtil.makeRowData(Monitoring, 'NFM115', samples);
                execute(rowData, iflog);
            }
            logstr += '\nend';
        } catch(Exception ex) {
            //发生错误的情况
            System.debug(Logginglevel.ERROR, 'NFM115_' + iflog.Name + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM115_' + iflog.Name + ':' + ex.getStackTraceString());
            logstr += ex.getMessage();
            iflog.ErrorLog__c += ex.getMessage() + '\n';
            iflog.ErrorLog__c += ex.getStackTraceString() + '\n';
        }
        System.debug('thhrowData--->'+rowData);
        if (rowData != null) {
            upsert rowData;
        }

        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);
        Samples samples = (Samples) JSON.deserialize(rowDataStr, Samples.class);
        String logstr = samples.Monitoring.MessageGroupNumber + ' start\n';
        Boolean needUpdateIflog = false;
        if (iflog == null) {
            needUpdateIflog = true;
            iflog = new BatchIF_Log__c();
            iflog.Type__c = 'NFM115';
            iflog.MessageGroupNumber__c = samples.Monitoring.MessageGroupNumber;
            iflog.Log__c = logstr;
            iflog.ErrorLog__c = '';
        } else {
            logstr = iflog.Log__c;
        }

        try{
            //发送接口
            status = NFMUtil.sendToSapRet(rowDataStr, NFMUtil.NFM115_ENDPOINT);
            System.debug('NFM115Log--status->' + status);
            if (status == 'Accepted') {
                logstr += status + '\n';
                rowData.retry_cnt__c = 0;
            } else {
                logstr += status + '\n';
                rowData = NFMUtil.LogAutoSend(rowData, null, status);
            }    
        } catch (Exception ex) {
            //发生错误的情况
            System.debug(Logginglevel.ERROR, 'NFM115_' + iflog.Name + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM115_' + iflog.Name + ':' + ex.getStackTraceString());
            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;

        if (needUpdateIflog) {
            upsert iflog;
            upsert rowData;
        }
    }

}