trigger RentalApplyHpDeptUpd on Rental_Apply__c (before insert, before update) { 
 | 
     
 | 
    List<String> accIds = new List<String>(); 
 | 
  
 | 
    for(Rental_Apply__c a : Trigger.new) { 
 | 
        if ((Trigger.isUpdate 
 | 
                && (Trigger.oldMap.get(a.Id).get('Account__c') != a.Account__c 
 | 
                    || a.Account__r.ParentId != a.Strategic_dept__c 
 | 
                    || a.Account__r.Parent.ParentId != a.Hospital__c)) 
 | 
                || Trigger.isInsert) { 
 | 
            if (!String.isBlank(a.Account__c)) { 
 | 
                accIds.add(a.Account__c); 
 | 
            } 
 | 
        } 
 | 
    } 
 | 
  
 | 
    if (accIds.size() > 0) { 
 | 
        // 診療科レコードタイプ 
 | 
        String[] deptTypes = new String[] {'診療科 その他', '診療科 呼吸科', '診療科 婦人科', '診療科 普外科', '診療科 泌尿科', '診療科 消化科', '診療科 耳鼻喉科'}; 
 | 
        List<RecordType> deptRects = [select Id, Name from RecordType where IsActive = true and SobjectType = 'Account' and Name IN :deptTypes]; 
 | 
        Map<String, String> deptRectMap = new Map<String, String>(); 
 | 
        for (RecordType rect : deptRects) { 
 | 
            deptRectMap.put(rect.Id, rect.Name); 
 | 
        } 
 | 
        // TODO 販売店のレコードタイプのMapを生成 
 | 
  
 | 
        Map<Id, Account> accMap = new Map<Id, Account>(); 
 | 
        List<Account> accs = ControllerUtil.selectAccountForTrigger(accIds); 
 | 
        for(Account acc : accs) { 
 | 
            accMap.put(acc.Id, acc); 
 | 
        } 
 | 
         
 | 
        for(Rental_Apply__c a : Trigger.new) { 
 | 
            // 「診療科」に診療科を選択する場合 
 | 
            Account acc = accMap.get(a.Account__c); 
 | 
            if (acc != null 
 | 
                    && deptRectMap.get(acc.RecordTypeId) != null) { 
 | 
                a.Strategic_dept__c = acc.ParentId; 
 | 
                a.Hospital__c = acc.Parent.ParentId; 
 | 
            } 
 | 
        } 
 | 
    } 
 | 
} 
 |