global class SoakupHPDeptTeamBatch implements Database.Batchable<sObject> {
    global final List<String> deptRectIds;
    global final String batchUserId;
    global final String Salesdepartment_HP1;
    global final String Salesdepartment_HP2;

    /**
     * コンスタント、パラメータを受け取る
     */
    global SoakupHPDeptTeamBatch(List<String> deptRectIds, String batchUserId, String Salesdepartment_HP1, String Salesdepartment_HP2) {
        this.deptRectIds = deptRectIds;
        this.batchUserId = batchUserId;
        this.Salesdepartment_HP1 = Salesdepartment_HP1;
        this.Salesdepartment_HP2 = Salesdepartment_HP2;
    }

    /**
     * startには、queryを実行、病院を検索
     */
    global Database.QueryLocator start(Database.BatchableContext BC) {
        if (String.isBlank(Salesdepartment_HP2)) {
            return Database.getQueryLocator([select Id, OwnerId, RecordType.Name from Account where RecordType.DeveloperName = 'HP' and Is_Active__c <> '無効' and Salesdepartment_HP__c = :Salesdepartment_HP1]);
        } else {
            return Database.getQueryLocator([select Id, OwnerId, RecordType.Name from Account where RecordType.DeveloperName = 'HP' and Is_Active__c <> '無効' and (Salesdepartment_HP__c = :Salesdepartment_HP1 or Salesdepartment_HP__c = :Salesdepartment_HP2)]);
        }
    }
    
    global void execute(Database.BatchableContext BC, List<SObject> hpList) {
        List<Account> dcList = [select Id, Management_Code__c, RecordType.Name, ParentId, OwnerId, Owner.Name from Account where Parent.Is_Active__c <> '無効' and Parent.RecordType.DeveloperName = 'HP'and Parent.Owner.IsActive=true and ParentId in :hpList];
        List<Account> dptList = [select Id, Management_Code__c, RecordType.Name, ParentId, OwnerId, Owner.Name from Account where Parent.Parent.Is_Active__c <> '無効' and Parent.Parent.Owner.IsActive = true and Is_Active__c <> '無効' and RecordTypeId in :deptRectIds and ParentId in :dcList];
        // その他診療科
        List<Account> othDptList = [select Id, Management_Code__c, RecordType.Name, Parent.ParentId, OwnerId, Owner.Name from Account where Parent.Parent.Is_Active__c <> '無効' and Parent.Parent.Owner.IsActive = true and Is_Active__c <> '無効' and RecordType.Name = '診療科 その他' and Parent.ParentId in :hpList];
        SoakupHPDeptTeam.soakupFromDeptTeam(dptList, dcList);
        SoakupHPDeptTeam.soakupToHPTeam(dcList, hpList, othDptList);
    }
    
    global void finish(Database.BatchableContext BC) {
        // 今回はやることないです
    }
}