/**
 * 103,104,105,Te2am,系统管理员 に実行権限があります。
 */
global without sharing class SoakupHPDeptTeam {
    static Integer dmlcount = 0;
    static BatchIF_Log__c iflog = null;

    /**
     * soakupFromDeptTeam()を呼び出す
     * soakupToHPTeam()を呼び出す
     */
    @AuraEnabled
    WebService static String execute(String deptClassId) {
        List<Account> dcList = [select  Id,
                                        ParentId, 
                                        OwnerId 
                                from 
                                        Account 
                                where 
                                        Parent.Is_Active__c <> '無効'
                                and
                                        Parent.owner.IsActive = true 
                                and 
                                        Parent.RecordType.DeveloperName = 'HP' 
                                and 
                                        Id = :deptClassId];
        if (dcList.size() == 0) {
            return System.Label.NotExist_DeptClass;
        }
        
        String[] recTypes = new String[] {'診療科 呼吸科', '診療科 婦人科', '診療科 普外科', '診療科 泌尿科', '診療科 消化科', '診療科 耳鼻喉科'};
        List<RecordType> rects = [select Id, Name from RecordType where IsActive = true and SobjectType = 'Account' and Name IN :recTypes];
        List<String> deptRectIds = new List<String>();
        for (RecordType rect : rects) {
            deptRectIds.add(rect.Id);
        }
        
        soakupFromDeptTeam(dcList, deptRectIds);
        soakupToHPTeam(new String[] {dcList[0].ParentId});
        return 'OK';
    }

    /**
     * 戦略課室のIDから配下の診療科にチームをセット
     * dcListにその他のdcIdが来る場合、無視
     *
     * @param dcList      戦略課室の配列
     * @param deptRectIds 対象診療科のレコードタイプの配列
     */
    public static void soakupFromDeptTeam(List<Account> dcList, List<String> deptRectIds) {
        // 戦略科室配下の診療科のチームを検索
        List<Account> childList = [select 
                                            Id, 
                                            RecordType.Name, 
                                            ParentId, 
                                            OwnerId, 
                                            Owner.Name 
                                    from 
                                            Account 
                                    where 
                                            Parent.Parent.Is_Active__c <> '無効' 
                                    and 
                                            Is_Active__c <> '無効'
                                    and 
                                            Parent.Parent.owner.IsActive = true 
                                    and 
                                            RecordTypeId in :deptRectIds 
                                    and 
                                            ParentId in :dcList];
        //if (childList.size() == 0) return;
        soakupFromDeptTeam(childList, dcList);
    }
    public static void soakupFromDeptTeam(List<Account> dptList, List<Account> oyaList) {
        iflog = new BatchIF_Log__c();
        iflog.Type__c = 'PushNotification';
        iflog.Log__c = 'soakupFromDeptTeam start\n';
        dmlcount = 0;
        
        // ------------病院のFSE主担当を戦略科室にセット、戦略科室のチームを作成------------
        List<Account> dcFseSpList = [select Id, FSE_Main__c, Parent.FSE_Main__c, SP_Main__c, Parent.SP_Main__c from Account where Id in :oyaList];
        List<Account> updDcList = new List<Account>();
        Map<String, Account> dcFseSpMap = new Map<String, Account>();
        for (Account acc : dcFseSpList) {
            if (acc.FSE_Main__c != acc.Parent.FSE_Main__c || acc.SP_Main__c != acc.Parent.SP_Main__c) {
                updDcList.add(acc);
                acc.FSE_Main__c = acc.Parent.FSE_Main__c;
                acc.SP_Main__c = acc.Parent.SP_Main__c;
            }
            dcFseSpMap.put(acc.Id, acc);
        }
        if (updDcList.size() > 0) Database.update(updDcList, false);
        
        // 戦略科室のチームを検索
        List<AccountTeamMember> dcFseSpTeamList = [select AccountId, UserId, TeamMemberRole from AccountTeamMember where AccountId in :oyaList];
        
        // 戦略科室のチームのFSE主担当を削除
        List<AccountTeamMember> deleteFseSpTeamList = new List<AccountTeamMember>();
        for (AccountTeamMember atm : dcFseSpTeamList) {
            // 戦略科室のチームにすでにFSE主担当が存在すれば、チームのFSE主担当を削除
            if (dcFseSpMap.containsKey(atm.AccountId)) {
                // TeamMemberRoleを判断
                if (atm.TeamMemberRole == 'FSE主担当' || atm.TeamMemberRole == 'SP主担当') {
                    deleteFseSpTeamList.add(atm);
                }
            }
        }
        
        if (deleteFseSpTeamList.size() > 0) {
            dmlcount = dmlcount + deleteFseSpTeamList.size();
            iflog.Log__c += 'soakupFromDeptTeam deleteFseSpTeamList ' + dmlcount + '\n';
            Database.delete(deleteFseSpTeamList, false);
        }
        
        // 戦略科室のチームのFSE主担当を作成
        List<AccountTeamMember> insertFseSpTeamList = new List<AccountTeamMember>();
        for (Account acc : dcFseSpList) {
            if (acc.Parent.FSE_Main__c != null) {
                AccountTeamMember newAtm = new AccountTeamMember(
                    UserId = acc.Parent.FSE_Main__c,
                    TeamMemberRole = 'FSE主担当',
                    AccountId = acc.Id
                );
                insertFseSpTeamList.add(newAtm);
            }
            if (acc.Parent.SP_Main__c != null) {
                AccountTeamMember newAtm = new AccountTeamMember(
                    UserId = acc.Parent.SP_Main__c,
                    TeamMemberRole = 'SP主担当',
                    AccountId = acc.Id
                );
                insertFseSpTeamList.add(newAtm);
            }
        }
        
        if (insertFseSpTeamList.size() > 0) {
            dmlcount = dmlcount + insertFseSpTeamList.size();
            iflog.Log__c += 'soakupFromDeptTeam insertFseSpTeamList ' + dmlcount + '\n';
            Database.SaveResult[] lsr = Database.insert(insertFseSpTeamList, false);
            List<AccountShare> newShare = new List<AccountShare>();
            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(
// Edit に固定 by xud 20131203
                        UserOrGroupId = insertFseSpTeamList[tIdx].UserId, AccountId = insertFseSpTeamList[tIdx].AccountId, AccountAccessLevel = 'Edit', OpportunityAccessLevel = 'None'
                    ));
                }
            }
            if (newShare.size() > 0) {
                dmlcount = dmlcount + newShare.size();
                iflog.Log__c += 'soakupFromDeptTeam newShare ' + dmlcount + '\n';
                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);
                    }
                }
            }
        }
        
        // 診療科がなければ終了
        if (dptList.size() == 0) return;
        
        List<Account> childList = new List<Account>();                // 'その他' を除いた診療科
        Map<String, String> c_o_Map = new Map<String, String>();
        for (Account child : dptList) {
            if (child.RecordType.Name != '診療科 その他') {
                childList.add(child);
                c_o_Map.put(child.Id, child.ParentId);
            }
        }
        if (childList.size() == 0) return;
        Map<String, String> oOwnerMap = new Map<String, String>();
        for (Account oya : oyaList) {
            oOwnerMap.put(oya.Id, oya.OwnerId);
        }

        // 戦略科室のチームを検索
        List<AccountTeamMember> dcListTeamList = 
                [select Id, UserId, TeamMemberRole, AccountId, AccountAccessLevel
                   from AccountTeamMember
                  where AccountId in :oyaList];
        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> deleteTeamList = 
                [select Id, UserId, TeamMemberRole, AccountId, AccountAccessLevel
                   from AccountTeamMember
                  where AccountId in :dptList];                   // 削除の場合 その他も削除するため
        dmlcount = dmlcount + deleteTeamList.size();
        iflog.Log__c += 'soakupFromDeptTeam deleteTeamList ' + dmlcount + '\n';
        Database.delete(deleteTeamList, false);
        // 診療科のチームを作成
        List<Account> updChildList = new List<Account>();
        List<AccountTeamMember> dTeamList = new List<AccountTeamMember>();
// Edit に固定 by katsu 20130605
//        List<String> dTeamAccessLevelList = new List<String>();
        List<AccountShare> newShare = new List<AccountShare>();  //list of new shares to add
        for (Account child : childList) {
            if (child.OwnerId != oOwnerMap.get(c_o_Map.get(child.Id))) {
                child.OwnerId = oOwnerMap.get(c_o_Map.get(child.Id));
                updChildList.add(child);
            }
            List<AccountTeamMember> dcTeamList = dcTeamMap.get(child.ParentId);
            if (dcTeamList != null) {
                for (AccountTeamMember dcTeam : dcTeamList) {
                    AccountTeamMember dTeam = dcTeam.clone();
                    dTeam.AccountId = child.Id;
                    dTeamList.add(dTeam);
// Edit に固定 by katsu 20130605
//                    dTeamAccessLevelList.add(dcTeam.AccountAccessLevel);
                }
            }
        }
        if (updChildList.size() > 0) {
            dmlcount = dmlcount + updChildList.size();
            iflog.Log__c += 'soakupFromDeptTeam updChildList ' + dmlcount + '\n';
            Database.SaveResult[] lsr = Database.update(updChildList, false);
            for (Integer tIdx = 0; tIdx < lsr.size(); tIdx++) {
                Database.SaveResult sr = lsr[tIdx];
                if (!sr.isSuccess()) {
                    System.debug(Logginglevel.ERROR, 'soakupFromDeptTeam update department owner AccountId = ' + sr.getId() + ' error:' + sr.getErrors()[0]);
                }
            }
        }
        if (dTeamList.size() > 0) {
            dmlcount = dmlcount + dTeamList.size();
            iflog.Log__c += 'soakupFromDeptTeam dTeamList ' + dmlcount + '\n';
            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(
// Edit に固定 by katsu 20130605
//                            UserOrGroupId = dTeamList[tIdx].UserId, AccountId = dTeamList[tIdx].AccountId, AccountAccessLevel = dTeamAccessLevelList[tIdx], OpportunityAccessLevel = 'None'
                            UserOrGroupId = dTeamList[tIdx].UserId, AccountId = dTeamList[tIdx].AccountId, AccountAccessLevel = 'Edit', OpportunityAccessLevel = 'None'
                    ));
                }
            }
            if (newShare.size() > 0) {
                dmlcount = dmlcount + newShare.size();
                iflog.Log__c += 'soakupFromDeptTeam newShare ' + dmlcount + '\n';
                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);
                    }
                }
            }
        }
    }

    /**
     * 病院のIDからチームを病院に上げる
     * 同時に戦略課室分類分類がその他 の チームも生成
     *
     * @param hpIds       病院Idの配列
     * @param batchUserId バッチユーザーのId
     */
    public static void soakupToHPTeam(List<String> hpIds) {
        // 病院配下の戦略科室のチームを検索
        // 增加判断ownerid是否为启用状态
        List<Account> dcList = [select  Id,
                                        Management_Code__c, 
                                        RecordType.Name, 
                                        ParentId,Parent.ParentId, 
                                        OwnerId, 
                                        Owner.Name, 
                                        FSE_Main__c, 
                                        SP_Main__c 
                                from 
                                        Account 
                                where 
                                        Parent.Is_Active__c <> '無効' 
                                and 
                                        Parent.RecordType.DeveloperName = 'HP' 
                                and 
                                        Parent.owner.IsActive = true
                                and      
                                        ParentId 
                                in :hpIds];
        if (dcList.size() == 0) return;
        List<Account> oyaList = [select Id,
                                        OwnerId, 
                                        RecordType.Name 
                                    from 
                                        Account 
                                    where 
                                        Is_Active__c <> '無効' 
                                    and 
                                        Id in :hpIds
                                    and 
                                        owner.IsActive = true
                                    ];
        // その他診療科
        List<Account> othDptList = [select 
                                            Id, 
                                            Management_Code__c, 
                                            RecordType.Name, 
                                            Parent.ParentId, 
                                            OwnerId, 
                                            Owner.Name 
                                    from 
                                            Account 
                                    where 
                                            Parent.Parent.Is_Active__c <> '無効' 
                                    and 
                                            Is_Active__c <> '無効' 
                                    and     
                                            RecordType.Name = '診療科 その他'
                                    and
                                            Parent.Parent.owner.IsActive = true
                                    and 
                                            Parent.ParentId in :hpIds];
        soakupToHPTeam(dcList, oyaList, othDptList);
    }
    public static void soakupToHPTeam(List<Account> dcList, List<Account> oyaList, List<Account> othDptList) {

        if (iflog == null) {
            iflog = new BatchIF_Log__c();
            iflog.Type__c = 'PushNotification';
        }
        iflog.Log__c += 'soakupToHPTeam start\n';
        for (Account hp : oyaList) {
            iflog.Log__c += 'hp[' + hp.Id + ']\n';
        }
        Map<String, Id> oyaOwnerMap = New Map<String, Id>();                  // '戦略科室分類 消化科'のId.ParentId => '戦略科室分類 消化科'のownerId
        List<Account> childList = new List<Account>();                // 'その他' を除いた戦略課室
        List<Account> updOyaList = new List<Account>();
        Map<String, List<String>> hp2otherList = new Map<String, List<String>>();         // 病院からその配下の '診療科 その他' のIdのListのMap
        Map<String, String> c_o_Map = new Map<String, String>();
        //Map<Id, Id> oyaFSEMap = New Map<Id, Id>();                    // '戦略科室分類 消化科'のId.ParentId => '戦略科室分類 消化科'のFSE主担当
        System.debug('dcList===============' + dcList + ')');
        for (Account child : dcList) {
            System.debug('child.RecordType.Name===============' + child.RecordType.Name + ')');
            String OwnerIdString = '';
            //if(child.RecordType.Name != '戦略科室分類 その他'){
            //    OwnerIdString
            //}
            if (child.RecordType.Name != '戦略科室分類 その他') {
                c_o_Map.put(child.Id, child.ParentId);
                childList.add(child);
            } else {
                if (hp2otherList.containsKey(child.ParentId) == false) {
                    hp2otherList.put(child.ParentId, new List<String>());
                }
                List<String> otherIdList = hp2otherList.get(child.ParentId);
                otherIdList.add(child.Id);
                oyaList.add(child);    // '戦略科室分類 その他' もbatchに設定する対象
System.debug('otherIdList.add dc(' + child.Management_Code__c + ')');
            }
            if (child.RecordType.Name == '戦略科室分類 消化科' ) {
System.debug('戦略科室分類 消化科 ownerId:::::' + child.ownerId);
                oyaOwnerMap.put(child.ParentId, child.ownerId);
System.debug('戦略科室分類 消化科 child.ParentId:::::' + child.ParentId);
            }

            if (child.RecordType.Name == '戦略科室分類 普外科') {
System.debug('戦略科室分類 普外科 ownerId:::::' + child.ownerId);
                oyaOwnerMap.put('NormalOut'+child.ParentId, child.ownerId);
System.debug('戦略科室分類 普外科 NormalOut===child.ownerId:::::' + child.ownerId);
            }
/************************************Update SWAG-AMDCQH START****************************************/
//业务要求战略科室负责人就是具体科室的负责人
/************************************Update SWAG-AMDCQH START****************************************/
            if(child.RecordType.Name == '戦略科室分類 その他'){
                system.debug('診療科 その他计入');
                system.debug('診療科 その他计入'+child.ownerid);
                system.debug('診療科 その他计入'+child.ownerId);
                oyaOwnerMap.put('others'+child.ParentId, child.ownerId);
            }
/************************************Update SWAG-AMDCQH END******************************************/
//业务要求战略科室负责人就是具体科室的负责人
/************************************Update SWAG-AMDCQH END******************************************/
        }
        for (Account othDpt : othDptList) {
            List<String> otherIdList = hp2otherList.get(othDpt.Parent.ParentId);
            otherIdList.add(othDpt.Id);
            oyaList.add(othDpt);    // '診療科 その他' もbatchに設定する対象
System.debug('otherIdList.add dpt(' + othDpt.Management_Code__c + ')');
        }
        system.debug('是否计入添加=========###'+oyaList);
        for (Account oya : oyaList) {
            String oyaId = null;
             system.debug('是否计入添加=========记录类型'+oya.RecordType.Name);
            if (oya.RecordType.Name == '病院') {
                oyaId = oya.Id;
            }
            else if (oya.RecordType.Name == '戦略科室分類 その他') {
                oyaId = 'NormalOut'+oya.ParentId;
            }
            else if (oya.RecordType.Name == '診療科 その他') {
/************************************Update SWAG-AMDCQH START****************************************/
//业务要求战略科室负责人就是具体科室的负责人
/************************************Update SWAG-AMDCQH START****************************************/
                //oyaId = oya.Parent.ParentId;
                oyaId = 'others'+oya.Parent.ParentId;
/************************************Update SWAG-AMDCQH END******************************************/
//业务要求战略科室负责人就是具体科室的负责人
/************************************Update SWAG-AMDCQH END******************************************/
            }
            else {
                iflog.Log__c += oya.RecordType.Name + ' ownerIdの更新対象外:::::' + oya.Id + '\n';
System.debug(Logginglevel.ERROR, oya.RecordType.Name + ' ownerIdの更新対象外:::::' + oya.Id);
            }
            system.debug('是否计入添加========='+(oyaOwnerMap.get(oyaId)));
            system.debug('是否计入添加========='+(oyaId != null ));
            system.debug('是否计入添加========='+(oya));
            system.debug('是否计入添加========='+(oyaId != null && oya.OwnerId != oyaOwnerMap.get(oyaId)));
            system.debug('是否计入添加========='+(oyaOwnerMap));
            if (oyaId != null && oya.OwnerId != oyaOwnerMap.get(oyaId)) {
                oya.OwnerId = oyaOwnerMap.get(oyaId);
                updOyaList.add(oya);
            }
        }
        if (updOyaList.size() > 0) {
            dmlcount = dmlcount + updOyaList.size();
            iflog.Log__c += 'soakupToHPTeam updOyaList ' + dmlcount + '\n';
system.debug('updOyaList最终结果========='+updOyaList);
            Database.update(updOyaList, false);
        }
        
        List<AccountTeamMember> childListTeamList = 
                [select Id, UserId, User.Name, TeamMemberRole, AccountId, AccountAccessLevel
                   from AccountTeamMember
                  where AccountId in :childList
                  order by LastModifiedDate desc];
        Map<String, List<AccountTeamMember>> childTeamMap = new Map<String, List<AccountTeamMember>>();                // key が病院
        for (AccountTeamMember childTeam : childListTeamList) {
            if (childTeamMap.get(c_o_Map.get(childTeam.AccountId)) == null) {
                childTeamMap.put(c_o_Map.get(childTeam.AccountId), new List<AccountTeamMember>());
            }
            
            system.debug('dcTeam AccountId:' + childTeam.AccountId + ', User:' + childTeam.User.Name + ', Access:' + childTeam.AccountAccessLevel);
            List<AccountTeamMember> childTeamList = childTeamMap.get(c_o_Map.get(childTeam.AccountId));
            childTeamList.add(childTeam);
        }
        for (Account child : childList) {
            if (child.OwnerId != oyaOwnerMap.get(child.ParentId)) {
                AccountTeamMember owner2Team = new AccountTeamMember(AccountId = child.Id, UserId = child.OwnerId, TeamMemberRole = '営業担当');
                system.debug('childList AccountId:' + owner2Team.AccountId + ', UserId:' + child.Owner.Name + ', Access:' + owner2Team.AccountAccessLevel);
                if (childTeamMap.get(c_o_Map.get(child.Id)) == null) {
                    childTeamMap.put(c_o_Map.get(child.Id), new List<AccountTeamMember>());
                }
                List<AccountTeamMember> childTeamList = childTeamMap.get(c_o_Map.get(child.Id));
                childTeamList.add(owner2Team);
            }
        }

        // 病院(と 診療科 その他)のチーム削除
        List<AccountTeamMember> deleteTeamList = 
                [select Id, UserId, TeamMemberRole, AccountId, AccountAccessLevel
                   from AccountTeamMember
                  where AccountId in :oyaList];
        System.debug(deleteTeamList+'病院(と 診療科 その他)のチーム削除');
        dmlcount = dmlcount + deleteTeamList.size();
        iflog.Log__c += 'soakupToHPTeam deleteTeamList ' + dmlcount + '\n';
        Database.delete(deleteTeamList, false);
        // 病院(と 診療科 その他)のチームを作成
        Set<String> teamKeySet = new Set<String>();
        List<AccountTeamMember> oyaTeamEList = new List<AccountTeamMember>();
// Edit に固定 by katsu 20130605
//        List<String> oyaTeamAccessLevelEList = new List<String>();
        List<AccountTeamMember> oyaTeamList = new List<AccountTeamMember>();
// Edit に固定 by katsu 20130605
//        List<String> oyaTeamAccessLevelList = new List<String>();
        for (String oyaId : childTeamMap.keySet()) {
            system.debug('oyaId:' + oyaId);
            List<AccountTeamMember> childTeamList = childTeamMap.get(oyaId);               // 病院配下の全て戦略課室のチーム
            if (childTeamList != null) {
                for (AccountTeamMember childTeam : childTeamList) {
                    AccountTeamMember oyaTeam = childTeam.clone();
                    oyaTeam.AccountId = oyaId;
                    String accessLevel = childTeam.AccountAccessLevel != null ? childTeam.AccountAccessLevel : 'Edit';
                    if (teamKeySet.contains(accessLevel + oyaId + oyaTeam.UserId)) {
                        continue;
                    }
System.debug('teamKeySet.add(' + accessLevel + oyaId + oyaTeam.UserId + ')');
                    teamKeySet.add(accessLevel + oyaId + oyaTeam.UserId);
                    if (accessLevel == 'Edit') {
                        oyaTeamEList.add(oyaTeam);
// Edit に固定 by katsu 20130605
//                        oyaTeamAccessLevelEList.add(accessLevel);
                    } else {
                        oyaTeamList.add(oyaTeam);
// Edit に固定 by katsu 20130605
//                        oyaTeamAccessLevelList.add(accessLevel);
                    }
                    List<String> otherIdList = hp2otherList.get(oyaId);
                    // 1行にするため、チームを その他 に移す
                    if (otherIdList != null ) for (String otherId : otherIdList) {
                        AccountTeamMember othTeam = oyaTeam.clone();
                        othTeam.AccountId = otherId;
                        if (accessLevel == 'Edit') {
                            oyaTeamEList.add(othTeam);
// Edit に固定 by katsu 20130605
//                            oyaTeamAccessLevelEList.add(accessLevel);
                        } else {
                            oyaTeamList.add(othTeam);
// Edit に固定 by katsu 20130605
//                            oyaTeamAccessLevelList.add(accessLevel);
                        }
                    }
                }
            }
        }
        List<AccountShare> newShare = new List<AccountShare>();  //list of new shares to add
        if (oyaTeamList.size() > 0) {
            dmlcount = dmlcount + oyaTeamList.size();
            iflog.Log__c += 'soakupToHPTeam oyaTeamList ' + dmlcount + '\n';
            if (dmlcount >= 10000) {
                iflog.ErrorLog__c = 'soakupToHPTeam oyaTeamList ' + dmlcount + '\n';
                insert iflog;
                return;
            }
            Database.SaveResult[] lsr = Database.insert(oyaTeamList, false);
            for (Integer tIdx = 0; tIdx < lsr.size(); tIdx++) {
                Database.SaveResult sr = lsr[tIdx];
                system.debug(sr.isSuccess()+'sr.isSuccess()++++++++=======++++++111');
                if (!sr.isSuccess()) {
                    Database.Error emsg = sr.getErrors()[0];
                    system.debug('\nERROR ADDING ACCOUNT TEAM MEMBER:' + emsg);
                } else {
                    newShare.add(new AccountShare(
// Edit に固定 by katsu 20130605
//                            UserOrGroupId = oyaTeamList[tIdx].UserId, AccountId = oyaTeamList[tIdx].AccountId, AccountAccessLevel = oyaTeamAccessLevelList[tIdx], OpportunityAccessLevel = 'None'
                            UserOrGroupId = oyaTeamList[tIdx].UserId, AccountId = oyaTeamList[tIdx].AccountId, AccountAccessLevel = 'Edit', OpportunityAccessLevel = 'None'
                    ));
                }
            }
        }
        if (oyaTeamEList.size() > 0) {
            // Editは優先的にするため、あとにinsertする
            dmlcount = dmlcount + oyaTeamEList.size();
            iflog.Log__c += 'soakupToHPTeam oyaTeamEList ' + dmlcount + '\n';
            if (dmlcount >= 10000) {
                iflog.ErrorLog__c = 'soakupToHPTeam oyaTeamEList ' + dmlcount + '\n';
                insert iflog;
                return;
            }
            Database.SaveResult[] lsr = Database.insert(oyaTeamEList, false);
            for (Integer tIdx = 0; tIdx < lsr.size(); tIdx++) {
                Database.SaveResult sr = lsr[tIdx];
                system.debug(sr.isSuccess()+'sr.isSuccess()++++++++=======++++++222');
                if (!sr.isSuccess()) {
                    Database.Error emsg = sr.getErrors()[0];
                    system.debug('\nERROR ADDING ACCOUNT TEAM MEMBER:' + emsg);
                } else {
                    newShare.add(new AccountShare(
// Edit に固定 by katsu 20130605
//                            UserOrGroupId = oyaTeamEList[tIdx].UserId, AccountId = oyaTeamEList[tIdx].AccountId, AccountAccessLevel = oyaTeamAccessLevelEList[tIdx], OpportunityAccessLevel = 'None'
                            UserOrGroupId = oyaTeamEList[tIdx].UserId, AccountId = oyaTeamEList[tIdx].AccountId, AccountAccessLevel = 'Edit', OpportunityAccessLevel = 'None'
                    ));
                }
            }
        }
        if (newShare.size() > 0) {
            dmlcount = dmlcount + newShare.size();
            iflog.Log__c += 'soakupToHPTeam newShare ' + dmlcount + '\n';
            if (dmlcount >= 10000) {
                iflog.ErrorLog__c = 'soakupToHPTeam newShare ' + dmlcount + '\n';
                insert iflog;
                return;
            }
            Database.SaveResult[] lsr = Database.insert(newShare, false); //insert the new shares
            for (Integer sIdx = 0; sIdx < lsr.size(); sIdx++) {
                Database.SaveResult sr = lsr[sIdx];
                system.debug(sr.isSuccess()+'sr.isSuccess()++++++++=======++++++333');
                if (!sr.isSuccess()) {
                    Database.Error emsg = sr.getErrors()[0];
                    system.debug('\nERROR ADDING ACCOUNT SHARING:' + emsg);
                }
            }
        }
    }
}