/*
发给谁
*/
public with sharing class NFM112Controller  {
    public static String status;
    // public class NFM112 {
    //     public Payments_element Payments_element;
    // }
    public class Payments_elements{
        public NFMUtil.Monitoring Monitoring;
        public Payment_element Agent;
    }
    public class Payment_element{
        public String AgentCode;
        public String AdvancePaymentFlag;
    }
    @future (callout=true)
    public static void callout(String iflog_Id, String samId){
        executeNotFuture(iflog_Id,samId);
    }
    
    public static void executeNotFuture(String iflog_Id, String samId){ 
        if (samId == null) {
            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;
            iflog = new BatchIF_Log__c();
            iflog.Type__c = 'NFM112';
            iflog.Log__c  = 'callout start\n'; 
        }
        //Monitoring的设定
        String logstr = iflog.Log__c + '\nNumberOfRecord=' + '';
        Datetime nowDT = Datetime.now();
        String nowStr = nowDT.format('yyyyMMddHHmm');
        Payments_elements paymentOrders = new Payments_elements();
        paymentOrders.Monitoring = new NFMUtil.Monitoring();
        paymentOrders.Monitoring.TransmissionDateTime = nowStr;
        paymentOrders.Monitoring.Text                 = ''; 
        paymentOrders.Monitoring.Tag                  = 'MSGH';
        paymentOrders.Monitoring.Sender               = 'SFDC';
        paymentOrders.Monitoring.Receiver             = 'NFM112';
        paymentOrders.Monitoring.NumberOfRecord       = '1';
        paymentOrders.Monitoring.MessageType          = 'NFM112';
        paymentOrders.Monitoring.MessageGroupNumber   = iflog.Name;

        BatchIF_Log__c rowData = null;
        try {
            //查数据付给字段
        paymentOrders.Agent = new Payment_element();
        List<Account> allList =[select 
                                Management_Code__c,
                                FirstParagraph__c,
                                MonthlyPayment__c 
                                from 
                                Account 
                                where 
                                RecordTypeId = '01210000000Qem1' 
                                AND Id =:samId];//AND RecordType = '販売店'
        for(Account ac : allList){
            Payment_element pm = new Payment_element();
            pm.AgentCode = ac.Management_Code__c;
            string temp;
            if(ac.FirstParagraph__c == false &&  ac.MonthlyPayment__c == false){
                temp = '';
            }else{
                temp = 'X';
            }
            pm.AdvancePaymentFlag = temp;
            paymentOrders.Agent = pm;
        }
        if(paymentOrders.Agent != null){
            NFMUtil.Monitoring Monitoring   = new NFMUtil.Monitoring();
            Monitoring.Tag                  = paymentOrders.Monitoring.Tag;
            Monitoring.Sender               = paymentOrders.Monitoring.Sender;
            Monitoring.Receiver             = paymentOrders.Monitoring.Receiver;
            Monitoring.MessageType          = paymentOrders.Monitoring.MessageType;
            Monitoring.MessageGroupNumber   = paymentOrders.Monitoring.MessageGroupNumber;
            Monitoring.NumberOfRecord       = paymentOrders.Monitoring.NumberOfRecord;
            Monitoring.TransmissionDateTime = paymentOrders.Monitoring.TransmissionDateTime;
            Monitoring.Text = '';

            // Payments_element nfm112 = new Payments_element();
            // nfm112.Payments_element = new Payments_element();
            // nfm112.Payments_element = paymentOrders;

            rowData = NFMUtil.makeRowData(Monitoring, 'NFM112', paymentOrders);
            execute(rowData, iflog);
        }
            logstr += '\nend';
        } catch(Exception ex) {
            //发生错误的情况
            System.debug(Logginglevel.ERROR, 'NFM112_' + iflog.Name + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM112_' + 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;
        }

        iflog.Log__c = logstr;
        upsert iflog;
    }
    //手动发送
    public static void ManualExecute(String rowDataId) {
        List < BatchIF_Log__c > row = [select id, name, MessageGroupNumber__c, retry_cnt__c,
            RowDataFlg__c, ErrorLog__c, Type__c,
            Log__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c,
            Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c
            from BatchIF_Log__c
            where id =: rowDataId
        ];
        if (row.size() > 0) execute(row[0], null);
    }
    //正常发送
    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);
        system.debug(rowDataStr);
        // Payments_element paymentOrders = (Payments_element) JSON.deserialize(rowDataStr, Payments_element.class);
        String logstr = rowData.MessageGroupNumber__c + ' start\n';
        Boolean needUpdateIflog = false;
        if (iflog == null) {
            needUpdateIflog = true;
            iflog = new BatchIF_Log__c();
            iflog.Type__c = 'NFM112';
            iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
            iflog.Log__c = logstr;
            iflog.ErrorLog__c = '';
        } else {
            logstr = iflog.Log__c;
            iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
        }

        try{
            system.debug('try内容');
            //发送接口
            status = NFMUtil.sendToSapRet(rowDataStr,NFMUtil.NFM112_ENDPOINT );
            System.debug('NFM112Log--status->'+ status);
            if (status == 'Accepted') {
                rowData.retry_cnt__c = 0;
            } else {
                // 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 = 'status:' + status +
                //                           '\n错误次数已经超过自动送信设定的最大次数，请手动送信';
                // }
                rowData = NFMUtil.LogAutoSend(rowData, null, status);
            }
        } catch (Exception ex) {
            //发生错误的情况
            System.debug(Logginglevel.ERROR, 'NFM112_' + iflog.Name + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM112_' + 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+'错误次数已经超过自动送信设定的最大次数，请手动送信';
            // }
            rowData = NFMUtil.LogAutoSend(rowData, ex, null);
        }
        iflog.Log__c = logstr;

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