/*  
 * 每月25日跑 获取询价的最老（第一笔）发货日更新更新客户（医院）第一笔成交日，获取最新发货日更新客户(医院)的最新发货日
*/
global class UpdateHospitalOppDateBatch implements Database.Batchable<sObject> {
  String hpId;

  Boolean IsNeedExecute = false; // 2021-03-05  mzy  WLIG-BYHD79  SFDC环境batch合并调查  是否符合执行条件

  global UpdateHospitalOppDateBatch() {

  }
  global UpdateHospitalOppDateBatch(String hpId) {
    this.hpId = hpId;
  }
  global UpdateHospitalOppDateBatch(Boolean needExecute) {
    IsNeedExecute = needExecute;  // 2021-03-05  mzy  WLIG-BYHD79  SFDC环境batch合并调查  
  }
  global Database.QueryLocator start(Database.BatchableContext BC) {
    if (String.isBlank(this.hpId)) {
      return Database.getQueryLocator(
              [select Id,
                FirstCompleteOppDate__c,
                LastShippingOppDate__c
                from Account
                where RecordType.DeveloperName = 'HP'
                and Is_Active__c <> '無効'
                order by Id]
             );
      } else {
        return Database.getQueryLocator(
              [select Id,
                FirstCompleteOppDate__c,
                LastShippingOppDate__c
                from Account
                where RecordType.DeveloperName = 'HP'
                and Is_Active__c <> '無効'
                and id = :this.hpId
                order by Id]
             );
      }
    }
    global void execute(Database.BatchableContext BC, list<sObject> dcList) {

      List<Account> upsertList = main(dcList);
      if (upsertList.size() > 0) upsert upsertList;
    }
    public static List<Account> main(List<Account> dcList) {
      List<Account> upsertList = new  List<Account>();

      
      Map<Id, AggregateResult> First_Shipping_DateMap = new Map<Id, AggregateResult>([
        select Hospital__c Id,
            MIN(First_Shipping_Date__c) First_Shipping_Date
            from Opportunity
            where Hospital__c in: dcList
            and First_Shipping_Date__c != null
            group by Hospital__c
      ]);

      Map<Id, AggregateResult> Last_Shipping_DateMap = new Map<Id, AggregateResult>([
        select Hospital__c Id,
            MAX(Last_Shipping_Date__c) Last_Shipping_Date
            from Opportunity
            where Hospital__c in: dcList
            and Last_Shipping_Date__c !=null
            group by Hospital__c
      ]);


            
      for(Account acc :dcList){
        boolean upsertFlag = false;
        if(First_Shipping_DateMap.get(acc.id)!=null){
         
          Date temDate = Date.valueOf(First_Shipping_DateMap.get(acc.id).get('First_Shipping_Date'));
          if(acc.FirstCompleteOppDate__c == null && temDate !=null){
            acc.FirstCompleteOppDate__c = temDate;
            upsertFlag = true;
          }
        }
        if(Last_Shipping_DateMap.get(acc.id)!=null){
          Date temDate = Date.valueOf(Last_Shipping_DateMap.get(acc.id).get('Last_Shipping_Date'));
          if( temDate !=null && acc.LastShippingOppDate__c != temDate){
            acc.LastShippingOppDate__c = temDate;
            upsertFlag = true;
          }
        }
        if (upsertFlag){
           upsertList.add(acc);
        }
      }
      return upsertList;
    }

    global void finish(Database.BatchableContext BC) {
      //2021-03-05  mzy  WLIG-BYHD79  SFDC环境batch合并调查  start
        if(!Test.isRunningTest() &&IsNeedExecute==true){
          //batch里调用下一个batch时，希望跟原有的Schedule里面传的条数保持一致
           Id execBTId = Database.executebatch(new SpareIsLoanBatch(true),200);
        }
      //2021-03-05  mzy  WLIG-BYHD79  SFDC环境batch合并调查 end

    }
}