/**********************************************************************
 * 
 *
 * @url: /services/apexrest/rest
 * @data:
 *  {
        
    }
*************************************************************************/
@RestResource(urlMapping='/RVS005/*')
global with sharing class RVS005Rest {
    global class InspectionResults{
        public NFMUtil.Monitoring Monitoring;
        // public InspectionResult[] Partners;
        public InspectionResult InspectionResult;
        
    }

    global class InspectionResult{
        public String   SAPRepairNotificationNo;    //  SAP修理单号
        public String   RVSDetailNo;                //  RVS的警告管理Key
        public String   LocationGroupDesc;          //  部位１名称
        public String   LocationDesc;               //  部位2名称
        public String   Description;                //  新现象描述
        public String   DetermineDate;              //  RVS决定日期
        public String   DetermineTime;              //  RVS决定时间
        public String   DeterminePerson;            //  RVS决定者

    }



    @HttpPost
    global static void execute() {
        // 取得接口传输内容
        String strData = RestContext.request.requestBody.toString();
        InspectionResults ges = (InspectionResults) JSON.deserializeStrict(strData, InspectionResults.class);

        if (ges == null ) {
            return;
        }

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

        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'RVS005', ges.InspectionResult);
        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 = '{"status": "Success", "Message":'  + gedata + '}';
        String jsonResponse = '{"Status": "OK", "ErrItem":"","ErrMsg":""}';
        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, 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,retry_cnt__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 = 'RVS005';
        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
        iflog.Log__c = logstr;
        iflog.ErrorLog__c = '';
        insert iflog;

        String rowDataStr = NFMUtil.getRowDataStr(rowData);
        InspectionResult res = (InspectionResult) JSON.deserialize(rowDataStr, InspectionResult.class);
         if (res == null) {
            return;
        }
        // List<InspectionResult> inspectionResultList = (List<InspectionResult>) JSON.deserialize(rowDataStr, List<InspectionResult>.class);
        List<InspectionResult> inspectionResultList = new List<InspectionResult>();
        inspectionResultList.add(res);
        // if (inspectionResultList == null || inspectionResultList.size() == 0) {
        //     return;
        // }
        Savepoint sp = Database.setSavepoint();
        try {
            // 获取SAP修理单号
            Set<String> repairCodeList = new Set<String>();

            for (inspectionResult ins : inspectionResultList) {
                if (String.isBlank(ins.SAPRepairNotificationNo)) {
                    continue;
                }
                // if (String.isBlank(ins.RVSDetailNo)) {
                //     continue;
                // }
                repairCodeList.add(ins.SAPRepairNotificationNo);
            }
            // 获取修理信息
            Map<String,Repair__c> repairidMap = new Map<String,Repair__c>();
            List<Repair__c> repairList =[select Id,SAP_Service_Repair_No__c from Repair__c
                                    where SAP_Service_Repair_No__c in :repairCodeList];
            for (Repair__c re : repairList) {
                repairidMap.put(re.SAP_Service_Repair_No__c, re);
            }



            // Map<String,PAE_DecisionRecordDetail__c> repairConfirmMap = new Map<String,PAE_DecisionRecordDetail__c>();
            Map<String,PAE_DecisionRecordDetail__c> pAEDeMap = new Map<String,PAE_DecisionRecordDetail__c>();
            List<PAE_DecisionRecordDetail__c> pddList =
                                [select Id,PAED_Repair__r.SAP_Service_Repair_No__c,
                                    RVSDetailNo__c,
                                    LocationGroup__c,
                                    Location__c,
                                    Description__c,
                                    Cause__c,
                                    PAE_Judge__c,
                                    EtqPart__c,
                                    RVS_Decision_Person__c,
                                    RVS_Date__c,
                                    RVS_Time__c
                                from PAE_DecisionRecordDetail__c
                                where PAED_Repair__r.SAP_Service_Repair_No__c in :repairCodeList];
            for (PAE_DecisionRecordDetail__c pdd : pddList) {
                // if (!repairConfirmMap.containsKey(pdd.PAED_Repair__r.SAP_Service_Repair_No__c)) {
                //  repairConfirmMap.put(pdd.PAED_Repair__r.SAP_Service_Repair_No__c, pdd);
                // }
                if (!pAEDeMap.containsKey(pdd.PAED_Repair__r.SAP_Service_Repair_No__c + pdd.RVSDetailNo__c + '')) {
                    pAEDeMap.put(pdd.PAED_Repair__r.SAP_Service_Repair_No__c + pdd.RVSDetailNo__c + '', pdd);
                }
            }

            // 20201123 gzw add 
            // 修理对应的PAE判定记录 final
            List<PAE_DecisionRecord__c> dbPAEDecisionRecordList =  [select id,PAE_reappear_confirm__c,LastModifiedDate,PAE_Repair__c
                                                                        ,PAE_Repair__r.SAP_Service_Repair_No__c
                                                                        from PAE_DecisionRecord__c
                                                                        where PAE_Repair__r.SAP_Service_Repair_No__c in :repairCodeList
                                                                        and recordType.DeveloperName = 'ASACDecision'
                                                                        order by LastModifiedDate desc];

            // 修理对应的最新Final的PAE判定记录
            Map<String,PAE_DecisionRecord__c> repPaeRecordMap = new Map<String,PAE_DecisionRecord__c>();
            for (PAE_DecisionRecord__c ele : dbPAEDecisionRecordList) {
                if (!repPaeRecordMap.containsKey(ele.PAE_Repair__r.SAP_Service_Repair_No__c) ) {
                    repPaeRecordMap.put(ele.PAE_Repair__r.SAP_Service_Repair_No__c,ele);
                }
            }

            List<PAE_DecisionRecordDetail__c> updateList = new List<PAE_DecisionRecordDetail__c>();
            // 20201124 gzw add 更新修理 RVS005来的时候，清空OCSM Coding的PAE判定。
            List<Repair__c> reList = new List<Repair__c>();
            Map<String,List<PAE_DecisionRecordDetail__c>> insertMap = new Map<String,List<PAE_DecisionRecordDetail__c>>();
            Map<String,PAE_DecisionRecord__c> newPAEMap = new Map<String,PAE_DecisionRecord__c>();
            for (inspectionResult ins : inspectionResultList) {
                if (repairidMap.containsKey(ins.SAPRepairNotificationNo) == false) {
                    iflog.ErrorLog__c += 'Error! SAPNo[' + ins.SAPRepairNotificationNo + ']NotExist. This Repair is skipped.\n';
                    continue;
                }

                PAE_DecisionRecordDetail__c upPAEde;
                upPAEde = pAEDeMap.get(ins.SAPRepairNotificationNo + ins.RVSDetailNo + '');
                if (upPAEde == null) {
                    upPAEde = new PAE_DecisionRecordDetail__c();
                    PAE_DecisionRecord__c newPAERecord =  new PAE_DecisionRecord__c();
                    if (repPaeRecordMap.containsKey(ins.SAPRepairNotificationNo)) {
                        newPAERecord = repPaeRecordMap.get(ins.SAPRepairNotificationNo);
                    }else{
                        newPAERecord.RecordTypeId = Schema.SObjectType.PAE_DecisionRecord__c.getRecordTypeInfosByDeveloperName().get('ASACDecision').getRecordTypeId();
                        newPAERecord.PAE_Repair__c = repairidMap.get(ins.SAPRepairNotificationNo).Id;
                    }
                    // newPAERecord.RecordTypeId = Schema.SObjectType.PAE_DecisionRecord__c.getRecordTypeInfosByDeveloperName().get('ASACDecision').getRecordTypeId();
                    // newPAERecord.PAE_Repair__c = repairidMap.get(ins.SAPRepairNotificationNo);
                    newPAEMap.put(ins.SAPRepairNotificationNo, newPAERecord);
                    List<PAE_DecisionRecordDetail__c> pAEddtemp = new List<PAE_DecisionRecordDetail__c>();
                    if (insertMap.containsKey(ins.SAPRepairNotificationNo)) {
                        pAEddtemp = insertMap.get(ins.SAPRepairNotificationNo);
                    }
                    pAEddtemp.add(upPAEde);
                    // 获取需要插入的判断明细
                    insertMap.put(ins.SAPRepairNotificationNo, pAEddtemp);
                }else{
                    // 获取需要更新的判断明细
                    updateList.add(upPAEde);
                }
                upPAEde.RecordTypeId = Schema.SObjectType.PAE_DecisionRecordDetail__c.getRecordTypeInfosByDeveloperName().get('final').getRecordTypeId();
                upPAEde.PAED_RCAC__c = 'Final';
                upPAEde.PAED_Repair__c = repairidMap.get(ins.SAPRepairNotificationNo).Id;
                
                upPAEde.RVSDetailNo__c = ins.RVSDetailNo;
                upPAEde.LocationGroup__c = ins.LocationGroupDesc;
                upPAEde.Location__c = ins.LocationDesc;
                
                // 2020/08/03 taoqz start
                // upPAEde.Description__c = ins.Description;
                upPAEde.PhenomenonDesc__c = ins.Description;
                // 2020/08/03 taoqz end

                upPAEde.RVS_Date__c = NFMUtil.parseStr2Date(ins.DetermineDate);
                //update by rentongxiao 2020101009 start
                // upPAEde.RVS_Time__c  = null ;
                //
                //转为时间格式
                upPAEde.RVS_Time__c = NFMUtil.parseStr2Time(ins.DetermineTime);
                //update by rentongxiao 2020101009 end
                // 20201123 by gzw 式样变更 start
                // puPAEde.EtqPart__c = ins.DeterminePerson ;
                upPAEde.RVS_Decision_Person__c = ins.DeterminePerson ;
                // 20201123 by gzw 式样变更 end
                Repair__c re = repairidMap.get(ins.SAPRepairNotificationNo);
                re.PAE_DetermineAC__c = null;
                reList.add(re);
            }
            if (reList.size() > 0) {
                update reList;
            }

            if (updateList.size() > 0) {
                update updateList;
            }
            if (newPAEMap.size() > 0) {
                upsert newPAEMap.values();
            }
            if (insertMap.size() > 0) {
                System.debug('insertMap +++++');
                List<PAE_DecisionRecordDetail__c> instemp = new List<PAE_DecisionRecordDetail__c>();
                for (String str: insertMap.keySet()) {
                    for (PAE_DecisionRecordDetail__c pdd : insertMap.get(str)) {
                        pdd.PAE_DecisionRecordD__c = newPAEMap.get(str).Id;
                        instemp.add(pdd);
                    }
                }
                System.debug('instemp +++++' + instemp);
                // instemp.addAll(insertMap.values());
                insert instemp;
            }
            logstr += '\nend';
            rowData.retry_cnt__c=0;

        } catch (Exception ex) {
            Database.rollback(sp);
            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();
            } else {
                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;
    }
}