trigger CaseHpDeptUpd on Case (before insert, before update) { 
 | 
    List<Case> cList = new List<Case>(); 
 | 
    List<Id> contactIds = new List<Id>(); 
 | 
    for(Case c : Trigger.new) { 
 | 
        if (Trigger.isInsert) { 
 | 
            if (String.isBlank(c.ContactId) == false) { 
 | 
                cList.add(c); 
 | 
                contactIds.add(c.ContactId); 
 | 
            } 
 | 
        } 
 | 
        else { 
 | 
            Case cOld = Trigger.oldMap.get(c.Id); 
 | 
            if (cOld.ContactId != c.ContactId) { 
 | 
                cList.add(c); 
 | 
                if (String.isBlank(c.ContactId) == false) { 
 | 
                    contactIds.add(c.ContactId); 
 | 
                } 
 | 
            } 
 | 
        } 
 | 
    } 
 | 
    if (cList.size() > 0) { 
 | 
        // AccoutIdを「Olympus社内 其他 社内用户」にする、TODO 9999997 にする 
 | 
        List<Account> ocm = [select Id from Account where AgentCode_Ext__c = '9999997']; 
 | 
        if (ocm.size() > 0) { 
 | 
            Map<Id, Contact> contactMap = ControllerUtil.selectContactAccountForTrigger(contactIds); 
 | 
            // 診療科レコードタイプ 
 | 
            String[] recordTypes = new String[] {'販売店', '診療科 その他', '診療科 呼吸科', '診療科 婦人科', '診療科 普外科', '診療科 泌尿科', '診療科 消化科', '診療科 耳鼻喉科'}; 
 | 
            List<RecordType> recordTypeRects = [select Id, Name from RecordType where IsActive = true and SobjectType = 'Account' and Name IN :recordTypes]; 
 | 
            Map<String, String> deptRectMap = new Map<String, String>(); 
 | 
            for (RecordType rect : recordTypeRects) { 
 | 
                deptRectMap.put(rect.Id, rect.Name); 
 | 
            } 
 | 
            for(Case c : cList) { 
 | 
                if (String.isBlank(c.ContactId) == false) { 
 | 
                    Contact con = contactMap.get(c.ContactId); 
 | 
                    if (con != null 
 | 
                            && deptRectMap.get(con.Account.RecordTypeId) != null) { 
 | 
                        if (deptRectMap.get(con.Account.RecordTypeId) == '販売店') { 
 | 
                            c.Account__c = con.AccountId; 
 | 
                        } else { 
 | 
                            c.Account__c = con.Account.Parent.ParentId; 
 | 
                        } 
 | 
                        c.AccountId = ocm[0].Id; 
 | 
                    } else { 
 | 
                        // ありえない 
 | 
                        c.addError('请选择正确的客户人员'); 
 | 
                    } 
 | 
                } else { 
 | 
                    c.Account__c = null; 
 | 
                    c.AccountId = null; 
 | 
                } 
 | 
            } 
 | 
        } 
 | 
    } 
 | 
} 
 |