public without sharing class AgencyContactHandler extends Oly_TriggerHandler {
    private Map<Id, Agency_Contact__c> newMap;
    private Map<Id, Agency_Contact__c> oldMap;
    private List<Agency_Contact__c> newList;
    private List<Agency_Contact__c> oldList;

    public AgencyContactHandler() {
        this.newMap = (Map<Id, Agency_Contact__c>) Trigger.newMap;
        this.oldMap = (Map<Id, Agency_Contact__c>) Trigger.oldMap;
        this.newList = (List<Agency_Contact__c>) Trigger.new;
        this.oldList = (List<Agency_Contact__c>) Trigger.old;
    }

    protected override void beforeInsert() {
        beforeSetValue();
    }
    protected override void beforeUpdate() {
        beforeSetValue();
        shareAgency_Contact_ToRole(this.newList);
    }

    protected override void afterInsert() {
        shareAgency_Contact_ToRole(this.newList);
    }

    protected override void afterUndelete() {
        shareAgency_Contact_ToRole(this.newList);
    }

    private void beforeSetValue() {
        Set<String> nameSet = new Set<String>();
        Set<String> ahIdSet = new Set<String>();
        Map<String, Agency_Contact__c> keyMap = new Map<String, Agency_Contact__c>();
        for (Agency_Contact__c nObj : newList) {
            if (String.isBlank(nObj.Agency_ID__c)) {
                if (String.isBlank(nObj.getCloneSourceId()) == false) {
                    // 要注意 画面からしかないので、ここで selectする
                    Agency_Contact__c srcObj = [Select Id, Agency_Hospital__c, Contact__c, Hospital_ID18__c, Hospital_Name__c from Agency_Contact__c where Id = :nObj.getCloneSourceId()];
                    if (String.isBlank(nObj.Agency_Hospital__c) == false
                            && String.isBlank(srcObj.Agency_Hospital__c)
                            && nObj.Hospital_ID18__c != srcObj.Hospital_ID18__c) {
                        nObj.Agency_Hospital__c.addError('请选择：' + srcObj.Hospital_Name__c);
                    }
                    if (String.isBlank(srcObj.Contact__c) == false) {
                        nObj.Contact__c = srcObj.Contact__c;
                    }
                }
                nObj.Agency_ID__c = nObj.Agency_ID_F__c;
            }
            nameSet.add(nObj.Name);
            ahIdSet.add(nObj.Agency_Hospital__c);
            keyMap.put(nObj.Agency_Hospital__c + nObj.Name, nObj);
        }

        List<Agency_Contact__c> ars = [select Id, Agency_Hospital__r.Name, Agency_Hospital__c, Name from Agency_Contact__c 
            where Name in :nameSet and Agency_Hospital__c in :ahIdSet and Agency_Hospital__c != null];
        for (Agency_Contact__c ar : ars) {
            String key = ar.Agency_Hospital__c + ar.Name;
            //system.debug('========3333333key'+key);
            if (keyMap.containsKey(key)) {
                Agency_Contact__c a = keyMap.get(key);
                if (a.Id == ar.Id) continue;
                //system.debug('========3333333');
                a.addError('该客户人员名字已存在，在'+ar.Agency_Hospital__r.Name+'医院，请修改'); 
            }
        }
    }

    /**
     * 设定 apex share to role
     * @param accId UserRoleとGroupを取得するため
     */
    private static void setAgency_Contact_Share(Id accId, List<Id> pList) {
        Id grpId = MergeAgencyActivityBatch.accIdGrpIdMap(accId);
        if(grpId != null) {
            List<Agency_Contact__Share> shareList = new List<Agency_Contact__Share>();
            Set<Id> sharePIdSet = new Set<Id>();
            for (Agency_Contact__Share share : [SELECT Id, ParentId
                    FROM Agency_Contact__Share
                    WHERE UserOrGroupId = :grpId AND RowCause = 'Manual']) {
                sharePIdSet.add(share.ParentId);
            }
            for (Id pId : pList) {
                if (sharePIdSet.contains(pId) == false) {
                    Agency_Contact__Share apexShare = new Agency_Contact__Share(
                            RowCause = 'Manual',
                            ParentId = pId,
                            UserOrGroupId = grpId,
                            AccessLevel = 'Edit');
                    shareList.add(apexShare);
                }
            }
            if (System.Test.isRunningTest() && grpId == null) {
                 //没有造 User 的旧Test 也让可以过
                return;
            }
            insert shareList;
        }
        
    }

    // afterInsert, afterUndelete
    /**
     * 一定要是同一经销商的
     * @param nList {Id, Agency_ID__c}
     */
    public static void shareAgency_Contact_ToRole(List<Agency_Contact__c> nList) {
        Set<Id> targetAgencyIdSet = new Set<Id>();
        Map<Id, List<Id>> tMap = new Map<Id, List<Id>>();
        for (Agency_Contact__c nObj : nList) {
            if (nObj.Agency_ID__c == '000000000000000') continue;
            targetAgencyIdSet.add(nObj.Agency_ID__c);
            List<Id> tList = tMap.get(nObj.Agency_ID__c);
            if (tList == null) {
                tList = new List<Id>();
            }
            tList.add(nObj.Id);
            tMap.put(nObj.Agency_ID__c, tList);
        }
        if (targetAgencyIdSet.size() > 0) {
            List<Id> targetIdList = new List<Id> (targetAgencyIdSet);
            System.assertEquals(1, targetIdList.size(), '一定要是同一经销商 [' + targetIdList[0] + ']');
            setAgency_Contact_Share(targetIdList[0], tMap.get(targetIdList[0]));
        }
    }
}