public with sharing class NFM116Controller {
    public static String status;
    public class OnlineSigns {
        public NFMUtil.Monitoring Monitoring;
        public OnlineSign[] OnlineSign;
    }
    public class OnlineSign {
        public String SoNo;
        public String DeliveryNote;
        public String DealerResult;
        public String DealerDate;
        public String HospitalResult;
        public String HospitalDate;
    }

     /**
     * NFM116の送信処理
     * 
     * @param iflog_Id          //日志表的ID
     * @param OnlineSignIdList  //要发送的签收单的ID
     */
    @future (callout=true)
    public static void callout(String iflog_Id, List<String> OnlineSignIdList) {
        executeNotFuture(iflog_Id, OnlineSignIdList);
    }

    public static void executeNotFuture(String iflog_Id, List<String> OnlineSignIdList) {
        if (OnlineSignIdList == null || OnlineSignIdList.size() == 0) {
            return;
        }
        //MessageGroupNumber的获取
        Datetime nowDT = Datetime.now();
        String nowStr = nowDT.format('yyyyMMddHHmm');
        BatchIF_Log__c iflog = new BatchIF_Log__c();
        if(String.isNotBlank(iflog_Id)){
            iflog = [Select Id, Name, Log__c, ErrorLog__c, MessageGroupNumber__c from BatchIF_Log__c where Id = :iflog_Id];
        } else{
            iflog.MessageGroupNumber__c = nowStr;
        }
        iflog.Log__c = 'callout start\n';
        iflog.Type__c = 'NFM116';
        iflog.ErrorLog__c = '';
        String logstr = iflog.Log__c + '\nNumberOfRecord=' + OnlineSignIdList.size();

        //Monitoring的设定
        OnlineSigns onlineSigns = new OnlineSigns();
        onlineSigns.Monitoring = new NFMUtil.Monitoring();
        onlineSigns.Monitoring.TransmissionDateTime = nowStr;
        onlineSigns.Monitoring.Text                 = ''; 
        onlineSigns.Monitoring.Tag                  = 'MSGH';
        onlineSigns.Monitoring.Sender               = 'SFDC';
        onlineSigns.Monitoring.Receiver             = 'SAP';
        onlineSigns.Monitoring.NumberOfRecord       = '' + OnlineSignIdList.size();
        onlineSigns.Monitoring.MessageType          = 'NFM116';
        onlineSigns.Monitoring.MessageGroupNumber   = iflog.Name;

        BatchIF_Log__c rowData = new BatchIF_Log__c();
        try {
            List<eSignForm__c> eSignFormList = [select Id, SANumber__c, DNName__c, agencyAcceptSAPResult__c, HPAcceptSAPResult__c, agencyAccOrSAPConfirmDate__c, 
                                                    hpAccOrSAPConfirmDate__c from eSignForm__c where Id IN :OnlineSignIdList];
            System.debug('eSignFormList1:' + eSignFormList);
            onlineSigns.OnlineSign = new List<OnlineSign>();
            for(eSignForm__c eSignForm : eSignFormList){
                OnlineSign onlineSign = new OnlineSign();
                onlineSign.SoNo           = eSignForm.SANumber__c;
                onlineSign.DeliveryNote   = eSignForm.DNName__c;
                onlineSign.DealerResult   = eSignForm.agencyAcceptSAPResult__c;
                onlineSign.DealerDate     = NFMUtil.formatDate2Str(eSignForm.agencyAccOrSAPConfirmDate__c);
                onlineSign.HospitalResult = eSignForm.HPAcceptSAPResult__c;
                onlineSign.HospitalDate   = NFMUtil.formatDate2Str(eSignForm.hpAccOrSAPConfirmDate__c);
                onlineSigns.OnlineSign.add(onlineSign);
            }
            if(onlineSigns.OnlineSign.size() > 0){
                NFMUtil.Monitoring Monitoring   = new NFMUtil.Monitoring();
                Monitoring.Tag                  = onlineSigns.Monitoring.Tag;
                Monitoring.Sender               = onlineSigns.Monitoring.Sender;
                Monitoring.Receiver             = onlineSigns.Monitoring.Receiver;
                Monitoring.MessageType          = onlineSigns.Monitoring.MessageType;
                Monitoring.MessageGroupNumber   = onlineSigns.Monitoring.MessageGroupNumber;
                Monitoring.NumberOfRecord       = onlineSigns.Monitoring.NumberOfRecord;
                Monitoring.TransmissionDateTime = onlineSigns.Monitoring.TransmissionDateTime;
                Monitoring.Text                 = '';
                rowData = NFMUtil.makeRowData(Monitoring, 'NFM116', onlineSigns);
                execute(rowData, iflog);
            }
            logstr += '\nend';
        } catch(Exception ex) {
            System.debug(Logginglevel.ERROR, 'NFM116_' + iflog.Name + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM116_' + 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);
        OnlineSigns onlineSigns = (OnlineSigns) JSON.deserialize(rowDataStr, OnlineSigns.class);
        String logstr = onlineSigns.Monitoring.MessageGroupNumber + ' start\n';
        Boolean needUpdateIflog = false;
        if (iflog == null) {
            needUpdateIflog = true;
            iflog = new BatchIF_Log__c();      
            iflog.Log__c = logstr;
            iflog.ErrorLog__c = '';
        } else {
            logstr = iflog.Log__c;
        }
        iflog.Type__c = 'NFM116';
        iflog.MessageGroupNumber__c = onlineSigns.Monitoring.MessageGroupNumber;

        try{
            //发送接口
            status = NFMUtil.sendToSapRet(rowDataStr, NFMUtil.NFM116_ENDPOINT);
            System.debug('NFM116Log--status->' + status);
            if ('Accepted'.equals(status)) {
                logstr += 'status:' + status + '\n';
                rowData.retry_cnt__c = 0;
            }
        } catch (Exception ex) {
            System.debug(Logginglevel.ERROR, 'NFM116_' + iflog.Name + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM116_' + 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;
        }
    }
}