public without sharing class AfterCreateDepartmentTrigger {
    static String[] departmentTypes = new String[] {'診療科 その他', '診療科 呼吸科', '診療科 婦人科', '診療科 普外科', '診療科 泌尿科', '診療科 消化科', '診療科 耳鼻喉科'};
    static List<RecordType> rects; 
    
    // 診療科を作成する時、戦略科室のOwnerを診療科のOwnerにする
    public static void beforeInsert(List<Account> newList, Map<Id, Account> newMap, List<Account> oldList, Map<Id, Account> oldMap) {
        if (Trigger.isInsert && Trigger.isBefore) {
            if (rects == null) {
                rects = [select Id, Name from RecordType where IsActive = true and SobjectType = 'Account' and Name IN :departmentTypes];
            }
            Map<String, String> rectMap = new Map<String, String>();
            for (RecordType rect : rects) {
                rectMap.put(rect.Id, rect.Name);
            }
            
            // 戦略科室のIdを集める
            Map<String, String> dcIdMap = new Map<String, String>();               // 診療科Id, 戦略科室Id
            for (Account a : newList) {
// Account2__cになるため、この部分のロジックはいらなくなります。
//            // Account作成後(コピー)、triggerにて集計項目をnullにする
//            a.ThisYear1__c = null;
//            a.ThisYear2__c = null;
//            a.ThisYear3__c = null;
//            a.ThisYear4__c = null;
//            a.ThisYear5__c = null;
//            a.ThisYear6__c = null;
//            a.ThisYear7__c = null;
//            a.ThisYear8__c = null;
//            a.ThisYear9__c = null;
//            a.ThisYear10__c = null;
//            a.ThisYear11__c = null;
//            a.ThisYear12__c = null;
//            a.DoOPDHospital_ThisYear1__c = null;
//            a.DoOPDHospital_ThisYear2__c = null;
//            a.DoOPDHospital_ThisYear3__c = null;
//            a.DoOPDHospital_ThisYear4__c = null;
//            a.DoOPDHospital_ThisYear5__c = null;
//            a.DoOPDHospital_ThisYear6__c = null;
//            a.DoOPDHospital_ThisYear7__c = null;
//            a.DoOPDHospital_ThisYear8__c = null;
//            a.DoOPDHospital_ThisYear9__c = null;
//            a.DoOPDHospital_ThisYear10__c = null;
//            a.DoOPDHospital_ThisYear11__c = null;
//            a.DoOPDHospital_ThisYear12__c = null;
//            a.DoNTCHospital_ThisYear1__c = null;
//            a.DoNTCHospital_ThisYear2__c = null;
//            a.DoNTCHospital_ThisYear3__c = null;
//            a.DoNTCHospital_ThisYear4__c = null;
//            a.DoNTCHospital_ThisYear5__c = null;
//            a.DoNTCHospital_ThisYear6__c = null;
//            a.DoNTCHospital_ThisYear7__c = null;
//            a.DoNTCHospital_ThisYear8__c = null;
//            a.DoNTCHospital_ThisYear9__c = null;
//            a.DoNTCHospital_ThisYear10__c = null;
//            a.DoNTCHospital_ThisYear11__c = null;
//            a.DoNTCHospital_ThisYear12__c = null;
                if (rectMap.get(a.RecordTypeId) == null) {
                    continue;
                }
                dcIdMap.put(a.Id, a.ParentId);
            }
            // 戦略科室のOwnerId, OCM_Category__cを検索
            List<String> dcIds = dcIdMap.values();
            // 戦略科室Id, 戦略科室のaccount
            Map<Id, Account> dcMap = new Map<Id, Account>([select Id, OwnerId, OCM_Category__c from Account where Id in :dcIds]);
            // 戦略科室のOwnerを診療科のOwnerにする
            for (Account a : newList) {
                if (rectMap.get(a.RecordTypeId) == null) {
                    continue;
                }
                if (dcMap.get(dcIdMap.get(a.Id)) != null) {
                    a.OwnerId = dcMap.get(dcIdMap.get(a.Id)).OwnerId;
                    a.OCM_Category__c = dcMap.get(dcIdMap.get(a.Id)).OCM_Category__c;
                }
            }
        }
    }
    
    // 診療科を作成後、診療科のチームを作成
    public static void afterInsert(List<Account> newList, Map<Id, Account> newMap, List<Account> oldList, Map<Id, Account> oldMap) {
        if (Trigger.isInsert && Trigger.isAfter) {
            if (rects == null) {
                rects = [select Id, Name from RecordType where IsActive = true and SobjectType = 'Account' and Name IN :departmentTypes];
            }
            Map<String, String> rectMap = new Map<String, String>();
            for (RecordType rect : rects) {
                rectMap.put(rect.Id, rect.Name);
            }
            
            // 戦略科室のIdを集める
            Map<String, String> dcIdMap = new Map<String, String>();               // 診療科Id, 戦略科室Id
            for (Account a : newList) {
                if (rectMap.get(a.RecordTypeId) == null) {
                    continue;
                }
                dcIdMap.put(a.Id, a.ParentId);
            }
            // 戦略科室のチームを検索
            List<String> dcIds = dcIdMap.values();
            List<AccountTeamMember> dcListTeamList = 
                    [select Id, UserId, TeamMemberRole, AccountId, AccountAccessLevel
                       from AccountTeamMember
                      where AccountId in :dcIds];
            Map<String, List<AccountTeamMember>> dcTeamMap = new Map<String, List<AccountTeamMember>>();
            for (AccountTeamMember dcTeam : dcListTeamList) {
                if (dcTeamMap.get(dcTeam.AccountId) == null) {
                    dcTeamMap.put(dcTeam.AccountId, new List<AccountTeamMember>());
                }
                system.debug('dcTeam.AccountId:' + dcTeam.AccountId + ', dcTeam.UserId:' + dcTeam.UserId + ', Access:' + dcTeam.AccountAccessLevel);
                List<AccountTeamMember> dcTeamList = dcTeamMap.get(dcTeam.AccountId);
                dcTeamList.add(dcTeam);
            }
    
            // 診療科のチームを作成
            List<AccountTeamMember> dTeamList = new List<AccountTeamMember>();
            List<String> dTeamAccessLevelList = new List<String>();
            List<AccountShare> newShare = new List<AccountShare>();  //list of new shares to add
            for (Account a : newList) {
                if (rectMap.get(a.RecordTypeId) == null) {
                    continue;
                }
                system.debug('a.ParentId:' + a.ParentId);
                List<AccountTeamMember> dcTeamList = dcTeamMap.get(a.ParentId);
                if (dcTeamList != null) {
                    for (AccountTeamMember dcTeam : dcTeamList) {
                        AccountTeamMember dTeam = dcTeam.clone();
                        dTeam.AccountId = a.Id;
                        dTeamList.add(dTeam);
                        dTeamAccessLevelList.add(dcTeam.AccountAccessLevel);
                    }
                }
            }
            if (dTeamList.size() > 0) {
                Database.SaveResult[] lsr = Database.Insert(dTeamList, false);
                for (Integer tIdx = 0; tIdx < lsr.size(); tIdx++) {
                    Database.SaveResult sr = lsr[tIdx];
                    if (!sr.isSuccess()) {
                        Database.Error emsg =sr.getErrors()[0];
                        system.debug('\nERROR ADDING ACCOUNT TEAM MEMBER:' + emsg);
                    } else {
                        newShare.add(new AccountShare(
                                UserOrGroupId = dTeamList[tIdx].UserId, AccountId = dTeamList[tIdx].AccountId, AccountAccessLevel = dTeamAccessLevelList[tIdx], OpportunityAccessLevel = 'None'
                        ));
                    }
                }
                if (newShare.size() > 0) {
                    lsr = Database.insert(newShare, false); //insert the new shares
                    for (Integer sIdx = 0; sIdx < lsr.size(); sIdx++) {
                        Database.SaveResult sr = lsr[sIdx];
                        if (!sr.isSuccess()) {
                            Database.Error emsg =sr.getErrors()[0];
                            system.debug('\nERROR ADDING ACCOUNT SHARING:' + emsg);
                        }
                    }
                }
            }
        }
    }
}