public with sharing class NFM666Controller {
    public class SampleOrders_element {
        public NFMUtil.Monitoring Monitoring;
        public SampleOrder_element[] SampleOrder;
    }
    //样本订货单
    public class SampleOrder_element {
        public String Status;
        public String Send_Date;
        public SampleOrderDetail_element[] SampleOrderDetail;
    }
    //样本订货单明细
    public class SampleOrderDetail_element {
        public String Pro_model;
        public String Pro_Name;
        public String Term_Date;
        public Decimal Standards;
        public Decimal Quantity;
        public Decimal Total;
        public String NMPA_Status;
    }

    /**
     * NFM666の送信処理
     * 
     * @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=' + '';
        Datetime nowDT = Datetime.now();
        String nowStr = nowDT.format('yyyyMMddHHmm');
        SampleOrders_element sampleOrders = new SampleOrders_element();
        sampleOrders.Monitoring = new NFMUtil.Monitoring();
        sampleOrders.Monitoring.TransmissionDateTime = nowStr;
        sampleOrders.Monitoring.Text                 = ''; 
        sampleOrders.Monitoring.Tag                  = 'MSGH';
        sampleOrders.Monitoring.Sender               = 'SFDC';
        sampleOrders.Monitoring.Receiver             = 'SAP';
        sampleOrders.Monitoring.NumberOfRecord       = '' + samIds.size();
        sampleOrders.Monitoring.MessageType          = 'NFM666';
        sampleOrders.Monitoring.MessageGroupNumber   = iflog.Name;

        BatchIF_Log__c rowData = null;
        try {
            List<Sample_order_list__c> samList = [select id, Status__c, Send_Date__c from Sample_order_list__c
                                                    where Account__c IN:samIds];
            list<String> samIdList = new List<String>();
            for(Sample_order_list__c sam : samList){
                samIdList.add(sam.Id);
            }
            List<Sample_order_list_detail__c> samDetailList = [select id, Pro_model__c, Pro_Name__c, Term_Date__c, Standards__c, Quantity__c, Total__c from Sample_order_list_detail__c
                                                            where Sample_order_list__c IN:samIdList];
            
            sampleOrders.SampleOrder = new List<SampleOrder_element>();
            for(Sample_order_list__c sam : samList){
                SampleOrder_element sampleOrder = new SampleOrder_element();
                sampleOrder.Send_Date           = NFMUtil.formatDate2Str(sam.Send_Date__c);
                sampleOrder.Status              = sam.Status__c;
                sampleOrder.SampleOrderDetail   = new list<SampleOrderDetail_element>();
                sampleOrders.SampleOrder.add(sampleOrder);
                SampleOrderDetail_element sampleOrderDetail = new SampleOrderDetail_element();
                for(Sample_order_list_detail__c samDetail : samDetailList){
                    if(samDetail.Sample_order_list__c == sam.Id){
                        sampleOrderDetail.Pro_model     = samDetail.Pro_model__c;
                        sampleOrderDetail.Pro_Name      = samDetail.Pro_Name__c;
                        sampleOrderDetail.Term_Date     = NFMUtil.formatDate2Str(samDetail.Term_Date__c);
                        sampleOrderDetail.Standards     = samDetail.Standards__c;
                        sampleOrderDetail.Quantity      = samDetail.Quantity__c;
                        sampleOrderDetail.Total         = samDetail.Total__c;
                        sampleOrder.SampleOrderDetail.add(sampleOrderDetail);
                    }
                }
            }
            if(sampleOrders.SampleOrder.size() > 0){
                NFMUtil.Monitoring Monitoring   = new NFMUtil.Monitoring();
                Monitoring.Tag                  = sampleOrders.Monitoring.Tag;
                Monitoring.Sender               = sampleOrders.Monitoring.Sender;
                Monitoring.Receiver             = sampleOrders.Monitoring.Receiver;
                Monitoring.MessageType          = sampleOrders.Monitoring.MessageType;
                Monitoring.MessageGroupNumber   = sampleOrders.Monitoring.MessageGroupNumber;
                Monitoring.NumberOfRecord       = sampleOrders.Monitoring.NumberOfRecord;
                Monitoring.TransmissionDateTime = sampleOrders.Monitoring.TransmissionDateTime;
                Monitoring.Text = '';
                
                rowData = NFMUtil.makeRowData(Monitoring, 'NFM666', sampleOrders);
                execute(rowData, iflog);
            }
            logstr += '\nend';
        } catch(Exception ex) {
            //发生错误的情况
            System.debug(Logginglevel.ERROR, 'NFM666_' + iflog.Name + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM666_' + 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 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);
        SampleOrders_element sampleOrders = (SampleOrders_element) JSON.deserialize(rowDataStr, SampleOrders_element.class);
        String logstr = sampleOrders.Monitoring.MessageGroupNumber + ' start\n';
        Boolean needUpdateIflog = false;
        if (iflog == null) {
            needUpdateIflog = true;
            iflog = new BatchIF_Log__c();
            iflog.Type__c = 'NFM666';
            iflog.MessageGroupNumber__c = sampleOrders.Monitoring.MessageGroupNumber;
            iflog.Log__c = logstr;
            iflog.ErrorLog__c = '';
        } else {
            logstr = iflog.Log__c;
        }

        try{
            //发送接口
            NFMUtil.sendToSap(rowDataStr, NFMUtil.NFM666_ENDPOINT);
            rowData.retry_cnt__c = 0;      
        } catch (Exception ex) {
            //发生错误的情况
            System.debug(Logginglevel.ERROR, 'NFM666_' + iflog.Name + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM666_' + 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;
        }
    }

}