//SWAG-C6TBM8 【委托】OPD所有人离职，无法进行报告申请 精琢技术 pk 2021-9-16 statr
global with sharing class UpdateOPDStatusAndReasonBatch implements Database.Batchable<sObject>, Database.AllowsCallouts, Database.Stateful {
    public String OPDId;
    public List<String> OPDIdList;
    public String logstr = '';
    public String errorstr = '';
    //正常执行查询所有 状态 = '完毕未报告', 所有人是否启用 = false 的OPD计划
    global UpdateOPDStatusAndReasonBatch() {
    }
    //手动执行 查询指定的OPD计划
    global UpdateOPDStatusAndReasonBatch(String OPDId) {
        this.OPDId = OPDId;
    }
    //手动执行 查询指定的一部分OPD计划
    global UpdateOPDStatusAndReasonBatch(List<string> OPDIdList) {
        this.OPDIdList = OPDIdList;
    }
    //根据条件拼接查询SoQL
    global Database.QueryLocator start(Database.BatchableContext bc) {
        //string query = 'select Id, noReport_Reason__c,Status__c,Rental_Apply2__r.RA_Status__c from OPDPlan__c where Status__c = \'完毕未报告\' and UserEnable__c = false and Rental_Apply2__r.RA_Status__c = \'完了\' and OPDType__c != \'学会\'';
        string query = 'select Id, noReport_Reason__c,Status__c,Rental_Apply2__r.RA_Status__c from OPDPlan__c where Status__c = \'完毕未报告\' and UserEnable__c = false and OPDType__c != \'学会\'';
        if (String.isNotBlank(OPDId)){
            query += ' and Id =:OPDId';
        }
        if (OPDIdList != null){
            query += ' and Id in:OPDIdList';
        }
        return Database.getQueryLocator(query);
    }
    //遍历查询结果，并把 “无报告理由” “状态” 赋值
    global void execute(Database.BatchableContext BC, list<OPDPlan__c> IPlanList) {
        if(IPlanList.size()>0){
            for(OPDPlan__c IPL :IPlanList){
                if('完了'.equals(IPL.Rental_Apply2__r.RA_Status__c)){
                IPL.noReport_Reason__c = '计划所有人离职';
                IPL.Status__c = '完毕';
                }
            }   
            update IPlanList;
            //并不能能报出apex作业执行失败 先注释 wql
            // Database.SaveResult[] saveResults = Database.update(IPlanList,false);
            //     for(Integer i=0;i<saveResults.size();i++){
            //         if(!saveResults.get(i).isSuccess()){
            //             logstr += IPlanList.get(i).Id+',';
            //             errorstr += saveResults.get(i).getErrors();
            //         }
            //     } 
        }
    }
    //根据errorstr是否为空判断是否执行报错，报错时填写日志
    global void finish(Database.BatchableContext BC) {
        //并不能能报出apex作业执行失败 先注释 wql
        // if(errorstr != ''){
        //     BatchIF_Log__c iflog = new BatchIF_Log__c();
        //     iflog.Type__c = 'UpdateOPDStatusAndReason';
        //     iflog.Log__c = logstr;
        //     iflog.ErrorLog__c = errorstr;
        //     insert iflog;
        // }
       
    }
}
//SWAG-C6TBM8 【委托】OPD所有人离职，无法进行报告申请 精琢技术 pk 2021-9-16 end