public with sharing class RepairSendToETQBatch implements Database.Batchable<sObject>, Database.AllowsCallouts,Database.Stateful   {
    
    public List<String> ids;
    
    //add by rentongxiao 2020-09-27 start 
    public String iflog_Id;
    public BatchIF_Log__c rowDataSFDC;
    public List<String> repairIds;
    public String statu;
    //add by rentongxiao 2020-09-27 end

    //HHOA-C3LJWQ 先更新修理再发送etq 20210616 start byrentx
    public List<String> idss;
    //HHOA-C3LJWQ 先更新修理再发送etq 20210616 end byrentx

    //update by rentongxiao 2020-09-27 start
     public RepairSendToETQBatch() {
        ids = new List<String>();
        this.statu = '';
        this.idss = new List<String>();
    }
    public RepairSendToETQBatch(String iflog_Id,BatchIF_Log__c rowDataSFDC, List<String> repairIds,String statu) {
        ids = repairIds;
        this.iflog_Id = iflog_Id;
        this.rowDataSFDC = rowDataSFDC;
        this.repairIds = repairIds;
        this.statu = statu;
        this.idss = new List<String>();

    }
    //update by rentongxiao 2020-09-27 end
    //add by rentx 2020-10-27 通过月份同步R3数据 
    public Integer monthNum;
    public RepairSendToETQBatch(String iflog_Id,BatchIF_Log__c rowDataSFDC, List<String> repairIds,String statu,Integer tempmonthNum) {
        this.iflog_Id = iflog_Id;
        this.rowDataSFDC = rowDataSFDC;
        this.repairIds = repairIds;
        // gzw add
        ids = repairIds;
        this.statu = statu;
        monthNum = tempmonthNum;
        this.idss = new List<String>();

    }
    ////add by renytx 2020-10-27 通过月份同步R3数据 end

    public RepairSendToETQBatch(List<String> argsIds) {
        ids = argsIds;
        this.idss = new List<String>();

    }

    public Database.QueryLocator start(Database.BatchableContext BC) {
        String staSql = 'select id,Name,ASReportedCodeAC__c,AE_DetermineResult__c,PAE_Determine__c,PAE_DetermineAC__c from Repair__c  ';
        if (ids != null && ids.size() > 0) {
            //update by rentongxiao 2020-09-27 start
            // staSql += ' and id in :ids';
            staSql += ' where id in :ids ';
            //update by rentongxiao 2020-09-27 end

        }else {
            // staSql += ' where AsyncData__c = false and Complaint_Number__c = null '; 
            // staSql += ' and Repair_Shipped_Date__c != null  and AE_DetermineResult__c != null and PAE_Determine__c != null and PAE_DetermineAC__c != null ';
            //update by rentx 2020-10-23
            staSql += ' WHERE AsyncData__c = false AND Repair_Shipped_Date__c != null AND AE_DetermineResult__c = \'nonAE\' AND PAE_Determine__c = \'nonPAE\' ';
            staSql += ' AND  PAE_DetermineAC__c = \'nonPAE\' AND Complaint_Number__c = null AND DOJ_Status__c != \'非对象\' AND PAE_reappear_confirm__c != null ';
        }

        if ((ids == null || ids.size() == 0) && monthNum != null) {
            Date startDay = Date.newInstance(2020,monthNum,1);
            Date tempDay = Date.newInstance(2020,monthNum+1, 1);
            Date endDay = tempDay.addDays(-1);
            staSql += ' and SAP_Transfer_day__c >= :startDay and SAP_Transfer_day__c <= :endDay ';
        }
        return Database.getQueryLocator(staSql);
    }

    public void execute(Database.BatchableContext BC, List<Repair__c> repList) {
        System.debug('repList.size() = ::'+repList.size());
        Map<String,Repair__c> idssMap = new Map<String,Repair__c>();
        
        List<Repair__c> updateList = new List<Repair__c>();

        for(Repair__c re : repList){
            // R3 FUC是空或者包含UseRSA 不发送ETQ 20201203
             if (!((re.AE_DetermineResult__c == 'nonAE' && re.PAE_Determine__c == 'nonPAE' && re.PAE_DetermineAC__c == 'nonPAE')
                   && (re.ASReportedCodeAC__c == null || re.ASReportedCodeAC__c.indexof('UseRSA') >= 0))) {
                re.AsyncData__c = true;
                re.AWS_Interface_Time__c = Datetime.now();
                updateList.add(re);
            }
        }

        //HHOA-C3LJWQ 先更新修理再发送etq 20210616 start byrentx
        if (updateList != null && updateList.size() > 0) {
            Database.SaveResult[] lsr = Database.update(updateList, false);
            BatchIF_Log__c iflog = new BatchIF_Log__c();
            iflog.Type__c = 'sendToETQ';
            iflog.Log__c  = 'RepairSendToETQBatch start\n';
            iflog.ErrorLog__c = '';
            for (Integer tIdx = 0; tIdx < lsr.size(); tIdx++) {
                Database.SaveResult sr = lsr[tIdx];
                System.debug('sr.isSuccess:' + sr.isSuccess());
                if (!sr.isSuccess()) {
                    Database.Error emsg = sr.getErrors()[0];
                    iflog.ErrorLog__c += 'ERROR ' + updateList[tIdx].Name + ' 更新 aws同步状态,同步时间失败:' + emsg + '\n';
                }else{
                    this.idss.add(updateList[tIdx].Id);
                    iflog.Log__c += updateList[tIdx].Name + ' 更新 aws同步状态,同步时间成功 \n';
                }

            }
            iflog.Log__c  += 'RepairSendToETQBatch end\n';
            iflog.Log__c += 'idss::'+idss;
            insert iflog;
        }
        //HHOA-C3LJWQ 先更新修理再发送etq 20210616 end byrentx



       
        
    // Savepoint sp = Database.setSavepoint();
        //add by rentx 2021-03-23 start
        // BatchIF_Log__c iflog = new BatchIF_Log__c();
        // iflog.Type__c = 'sendToETQ';
        // iflog.Log__c  = 'RepairSendToETQBatch start\n';
        // Savepoint sp = Database.setSavepoint();
        //add by rentx 2021-03-23 end
        // try{
            // BatchIF_Log__c iflog = new BatchIF_Log__c();
            // iflog.MessageGroupNumber__c = String.valueOf(DateTime.now()).replaceAll('\\D','');
            // iflog.Type__c = 'NFM401';
            // insert iflog;
            // NFM401Controller1.callout(null,null,idss,statu);

            //update by rentx 2021-03-23 start 需要先更新修理的信息再掉401接口 不然的话可能会出现 调用成功但是部分修理更新失败的情况 将更新修理的步骤提前 则当修理更新失败时 就不会往下执行401的接口了
            
            // if (idssMap.size() > 0) {
            //     update idssMap.values();
            // }
            //update by rentx 2021-03-23 end



            // NFM401Controller.callout(null,null,idss,statu);
            /*
            for(Repair__c re : repList){
                re.AsyncData__c = true;
                re.AWS_Interface_Time__c = Datetime.now();
            }*/
            //add by rentx 2020-11-19 start
            // Database.SaveResult[] lsr = Database.update(repList, false);
            //注释by rentx 2021-03-23 start
            /*Database.SaveResult[] lsr = Database.update(idssMap.values(), false);
            BatchIF_Log__c iflog = new BatchIF_Log__c();
            iflog = new BatchIF_Log__c();
            iflog.Type__c = 'sendToETQ';
            iflog.Log__c  = 'RepairSendToETQBatch start\n';
            iflog.ErrorLog__c = '';
            for (Integer tIdx = 0; tIdx < lsr.size(); tIdx++) {
                Database.SaveResult sr = lsr[tIdx];
                System.debug('sr.isSuccess:' + sr.isSuccess());
                if (!sr.isSuccess()) {
                    Database.Error emsg = sr.getErrors()[0];
                    iflog.ErrorLog__c += 'ERROR ' + repList[tIdx].Name + ' 更新 aws同步状态,同步时间失败:' + emsg + '\n';
                }else{
                    iflog.Log__c += repList[tIdx].Name + ' 更新 aws同步状态,同步时间成功 \n';
                }

            }
            iflog.Log__c  += 'RepairSendToETQBatch end\n';
            insert iflog;*/
            //注释by rentx 2021-03-23 end
            //add by rentx 2021-03-23 start
            // iflog.Log__c += 'Id为 :'+idss +'的修理更新 aws同步状态,同步时间 成功 \n';
            // iflog.Log__c += 'RepairSendToETQBatch end\n';
            // System.debug(iflog+'');
            // insert iflog;
            //add by rentx 2021-03-23 end


            // update repList;
            //add by rentx 2020-11-19 end
        // }catch(Exception e){
        //     // Database.rollback(sp);
        //     System.debug('00000000000');
        //     System.debug(e.getStackTraceString());
        //     Database.rollback(sp);
        //     //add by rentx 2021-03-23 start
        //     iflog.ErrorLog__c = '更新修理的aws同步状态失败:'+e.getMessage();
        //     iflog.Log__c += 'RepairSendToETQBatch end\n';
        //     System.debug(iflog+'');
            
        //     insert iflog;
            //add by rentx 2021-03-23 end
        // }
       
    }



    public void finish(Database.BatchableContext BC) {
        // gzw PDF空白优化 跳过测试程序
        if (!Test.isRunningTest()) {
            //HHOA-C3LJWQ 先更新修理再发送etq 20210616 start byrentx
            if (this.idss != null && this.idss.size() > 0) {
                NFM401Controller.callout(null,null,this.idss,statu);
                
            }
            //HHOA-C3LJWQ 先更新修理再发送etq 20210616 end byrentx

            Database.executeBatch(new NFM402Batch(),100);
        }
        // gzw PDF空白优化 跳过测试程序
    }

}