global class SBG010WebService {

    global class GeDatas {
        webservice NFMUtil.Monitoring Monitoring;
        webservice SBG010WebService.GeData[] GeData;
    }
    global class GeData {
        webservice String  OrderCode;
        webservice String  SoNo;
        webservice String  SoShippingStatus;
        webservice String  SoDate;
        webservice String  DeliveryDate;
        webservice String  Other1;
        webservice String  Other2;
        webservice String  Other3;
    }
    webservice static void SBG010(GeDatas geDatas) {
        if (geDatas == null) {
            return;
        }
        NFMUtil.Monitoring Monitoring = GeDatas.Monitoring;
        if (Monitoring == null) {
            return;
        }
        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'SBG010', GeDatas.GeData);
        if (String.isBlank(rowData.Log__c) == false) execute(rowData.Id);
    }
global static void execute(String rowData_Id) {
        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
        BatchIF_Log__c rowData = [Select Id, Name, Log__c,retry_cnt__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c, Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c from BatchIF_Log__c where RowDataFlg__c = true and Id = :rowData_Id];
        String logstr = rowData.MessageGroupNumber__c + ' start\n';
        BatchIF_Log__c iflog = new BatchIF_Log__c();
        iflog.Type__c = 'SBG010';
        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
        iflog.Log__c = logstr;
        iflog.ErrorLog__c = '';
        insert iflog;
        String rowDataStr = NFMUtil.getRowDataStr(rowData);
        List<GeData> GeDataList = (List<GeData>) JSON.deserialize(rowDataStr, List<GeData>.class);
        if (GeDataList == null || GeDataList.size() == 0) {
            return;
        }

        Savepoint sp = Database.setSavepoint();
        try {
            // 更新対応配列とMapなどをセット
            List<String> soNoList = new List<String>();
            List<String> soNoList1 = new List<String>();
            for (SBG010WebService.GeData GeData : GeDataList) {
                if (GeData.SoNo == null || GeData.SoNo == '' ||
                    GeData.OrderCode == null || GeData.OrderCode == '' ||
                    GeData.SoShippingStatus == null
                ) {
                    // 必須項目がない場合、処理と飛ばす
                    continue;
                }
                soNoList.add(GeData.OrderCode);
                if(String.isNotBlank(GeData.DeliveryDate))
                {
                    soNoList1.add(GeData.SoNo+GeData.DeliveryDate);
                }else
                {
                    soNoList1.add(GeData.SoNo);
                }
               
            }


            List<String> orderid = new List<String>();
            List<Delivery__c> soList = [select Id, SSBD_Contract__c, Delivery_Money__c,
                                                Delivery_Date__c, SAP_CreatDate__c,
                                                Delivery_Status__c,SONO__c
                                           from Delivery__c
                                          where SONO__c in :soNoList1];
            Map<String, Delivery__c> soMap = new Map<String, Delivery__c>();
            for (Delivery__c so : soList) {
                orderid.add(so.SSBD_Contract__c);
                soMap.put(so.SSBD_Contract__c, so);
            }

             List<String> oids = new List<String>();
            Map<String,Order> ordermap = new Map<String,Order>();
            for(Order o : [Select Id,OrderNumber,SAP_Contract__c,DeliveryDate__c,ShippedDate__c From Order Where OrderNumber in :soNoList])
            {
                oids.add(o.Id);
                ordermap.put(o.OrderNumber,o);
            }

         
                        
            // 更新対応配列をセット
            Map<String, Delivery__c> soUpdateMap = new Map<String, Delivery__c>();
            List<Order> orders = new List<Order>();
            for (SBG010WebService.GeData GeData : GeDataList) {
                if (GeData.SoNo == null || GeData.SoNo == '') {
                    // 必須項目がない場合、処理と飛ばす
                    iflog.ErrorLog__c += 'SoNo is required\n';
                    continue;
                }
                if (GeData.OrderCode == null || GeData.OrderCode == '') {
                    // 必須項目がない場合、処理と飛ばす
                    iflog.ErrorLog__c += 'OrderCode is required\n';
                    continue;
                }
                if (GeData.SoShippingStatus == null) {
                    // 必須項目がない場合、処理と飛ばす
                    iflog.ErrorLog__c += 'SoShippingStatus is required\n';
                    continue;
                }
                Order so = ordermap.get(GeData.OrderCode);
                if (so == null) {
                    // 更新対象商談がない場合
                    iflog.ErrorLog__c += '[' + GeData.SoNo + ']Order[' + GeData.OrderCode + ']NotExist\n';
                    continue;
                }
                //if(String.isBlank(GeData.DeliveryDate))
                //{
                //    iflog.ErrorLog__c += '[' + GeData.SoNo + ']Delivery[' + GeData.SoShippingStatus + ']NotExist\n';
                //    continue;
                //}
                // 
                Delivery__c deliv = new Delivery__c();
                if(soMap.get(ordermap.get(GeData.OrderCode).Id) != null)
                {
                    deliv.Id = soMap.get(ordermap.get(GeData.OrderCode).Id).Id;
                }
                if(String.isNotBlank(GeData.DeliveryDate))
                {
                    deliv.SONO__c = GeData.SoNo + GeData.DeliveryDate;
                }else
                {
                    deliv.SONO__c = GeData.SoNo;
                }
                if(String.isBlank(deliv.Id)){
                    deliv.SSBD_Contract__c            = ordermap.get(GeData.OrderCode).Id;
                }
                List<string> Datesplit = GeData.SoDate.split(',');
                deliv.Delivery_Status__c             = GeData.SoShippingStatus ;
                deliv.Delivery_Date__c         = NFMUtil.parseStr2Date(GeData.DeliveryDate, true);
                deliv.SAP_CreatDate__c   = NFMUtil.parseStr2Date(Datesplit[0], true);
                System.debug('idis' + ordermap.get(GeData.OrderCode).Id);
                System.debug('dateis' + ordermap.get(GeData.OrderCode).DeliveryDate__c);
                soUpdateMap.put(deliv.SONO__c, deliv);
               
                if(String.isNotBlank(GeData.SoNo)){
                    if((NFMUtil.parseStr2Date(GeData.DeliveryDate, true) > ordermap.get(GeData.OrderCode).DeliveryDate__c) || (ordermap.get(GeData.OrderCode).DeliveryDate__c == null)
                    || (NFMUtil.parseStr2Date(Datesplit[1], true) <> ordermap.get(GeData.OrderCode).ShippedDate__c))
                    {
                        if(Datesplit[1] <> '00000000'){
                        orders.add(new Order(id = ordermap.get(GeData.OrderCode).Id
                               , SAP_Contract__c = GeData.SoNo , DeliveryDate__c = NFMUtil.parseStr2Date(GeData.DeliveryDate, true),
                                OrderDate__c = NFMUtil.parseStr2Date(Datesplit[0], true), ShippedDate__c = NFMUtil.parseStr2Date(Datesplit[1], true)));
                        }
                        else if(Datesplit[1] == '00000000'){
                        orders.add(new Order(id = ordermap.get(GeData.OrderCode).Id
                               , SAP_Contract__c = GeData.SoNo , DeliveryDate__c = NFMUtil.parseStr2Date(GeData.DeliveryDate, true),
                                OrderDate__c = NFMUtil.parseStr2Date(Datesplit[0], true)));
                        }
                    }
                }
            }
            System.debug('ordersize' + orders.size());
       
            if (soUpdateMap.size() > 0) {
                System.debug(soUpdateMap.values());
                upsert soUpdateMap.values();
            }
            if(orders.size()>0)
            {
                update orders;
            }
//ToDo第一次进来的时候有可能没有DeliveryDate，当第一次没有DeliveryDate第二次有的情况会添加两条发货记录
            logstr += '\nend';
            rowData.retry_cnt__c=0;
        } catch(Exception ex) {
            // エラーが発生した場合
            Database.rollback(sp);
            System.debug(Logginglevel.ERROR, 'SBG010_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'SBG010_' + rowData.MessageGroupNumber__c + ':' + ex.getStackTraceString());
            logstr += '\n' + ex.getMessage();
            iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
            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+'错误次数已经超过自动收信设定的最大次数，请手动收信';
            }
        }
        update rowData;
        iflog.Log__c = logstr;
        if (iflog.Log__c.length() > 131072) {
            iflog.Log__c = iflog.Log__c.subString(0, 131065) + ' ...';
        }
        if (iflog.ErrorLog__c.length() > 32768) {
            iflog.ErrorLog__c = iflog.ErrorLog__c.subString(0, 32760) + ' ...';
        }
        update iflog;
    }
}