/**********************************************************************
 * 
 *
 * @url: /services/apexrest/NFM117/execute
 * 
 * 
*************************************************************************/
@RestResource(urlMapping='/NFM117/*')
global with sharing class NFM117Rest {
    //新增NFM117Rest 零件预计齐备日期  精琢技术 start
  
    global class GeDatas {
        public NFMUtil.Monitoring Monitoring;
        public  GeData[] GeData;
    }

    global class GeData {
        public String SAPRepairNo;                    // SAP修理单号
        public String PartsreadyDate;                 // 零件预计齐备日期
       
    }

    @HttpPost
    global static void execute() {

        // 取得接口传输内容
        String strData = RestContext.request.requestBody.toString();
        GeDatas ges = (GeDatas) JSON.deserializeStrict(strData, GeDatas.class);
        system.debug('rquest----'+strData);
        if (ges == null ) {
            return;
        }

        NFMUtil.Monitoring Monitoring = ges.Monitoring;
        if (Monitoring == null) {
            return;
        }

        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'NFM117', ges.GeData);
        if (String.isBlank(rowData.Log__c) == false) {
            executefuture(rowData.Id);
        }

        // JSONを戻す
        RestResponse res = RestContext.response;
        res.addHeader('Content-Type', 'application/json');
        res.statusCode = 200;
        String jsonResponse = '{"Result": {"Result": "00", "Message":""}}';
        res.responseBody = blob.valueOf(jsonResponse);
        return;
    }

    @future
    global static void executefuture(String rowData_Id) {
        main(rowData_Id);
    }

    global static void main (String rowData_Id) {

        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
        BatchIF_Log__c rowData = [Select Id, Name, retry_cnt__c, Log__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 = 'NFM117';
        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 {
            List<Repair__c> repairInsList = new List<Repair__c>();

            //将SAP修理单号、零件预计齐备日期存入List
            List<String> sapRepairNoList = new List<String>();
            List<String> partsreadyDateList = new List<String>();
            
            for (GeData geData : geDataList) {
                if (String.isBlank(geData.SAPRepairNo)) {
                    // 必須項目がない場合、処理と飛ばす
                    iflog.ErrorLog__c += 'SAP修理单号不能为空。\n';
                    continue;
                } else {
                    sapRepairNoList.add(geData.SAPRepairNo);
                }

                if (String.isBlank(geData.PartsreadyDate)) {
                    // 必須項目がない場合、処理と飛ばす
                    iflog.ErrorLog__c += geData.SAPRepairNo+':零件预计齐备日期为空。\n';
                    continue;
                } 
                
            }
            
            //SAP修理单号和零件预计齐备日期存入Map
            Map<String, Repair__c> repairInfoMap = new Map<String, Repair__c>();
            if (sapRepairNoList.size() > 0) {
                List<Repair__c> repairList = [select ID,SAPRepairNo__c,PartsreadyDate__c  from Repair__c where SAPRepairNo__c in :sapRepairNoList];
                if (repairList.size() > 0) {
                    for (Repair__c repairInfo : repairList) {
                        repairInfoMap.put(repairInfo.SAPRepairNo__c, repairInfo);
                    }
                }
            }
            
            // 将XML的零件预计齐备日期存入修理对象中
            for (GeData geData : geDataList) {
                    
                Repair__c repair = new Repair__c();
                if (!repairInfoMap.containsKey(geData.SAPRepairNo)){
                	iflog.ErrorLog__c += 'SAP修理单号:' +geData.SAPRepairNo +'：未找到。\n';
                	continue;
                }
                repair.Id = (repairInfoMap.get(geData.SAPRepairNo)).ID;            
                repair.PartsreadyDate__c = NFMUtil.parseDateTimeStr2Date(geData.PartsreadyDate);             //零件预计齐备日期
                
                repairInsList.add(repair);
                logstr += 'SAP修理单号:' +geData.SAPRepairNo +'：获取成功。\n';

            }

            if (repairInsList.size() > 0) {
                upsert repairInsList;
                logstr += '更新成功。\n';
            }

            logstr += '\nend';
            rowData.retry_cnt__c = 0;

        } catch (Exception ex) {
            // エラーが発生した場合
            Database.rollback(sp);
            System.debug(Logginglevel.ERROR, 'NFM117_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM117_' + 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;
    }
    //新增NFM117Rest 零件预计齐备日期 精琢技术 end
}