/**
 * 引合チーム「副担当」重複のチェック、「副担当」をチームに自動同期などの処理
 */
public without sharing class OpportunityMemberTrigger {
    // OppId ==> OpportunityTeamMember(Opportunity_sub_owner__c)
    public static Map<Id, OpportunityTeamMember> syncMBOpportunityOtmMap = new Map<Id, OpportunityTeamMember>();
    // OppId ==> OpportunityTeamMember(Opportunity_stms_owner__c)
    public static Map<Id, OpportunityTeamMember> syncMBOpportunityOtmMapSTMS = new Map<Id, OpportunityTeamMember>();

    // on OpportunityTeamMember (after insert, after update)
    // 引合チーム「副担当」重複エラートリガ
    public static void opportunityMemberDuplicateError(List<OpportunityTeamMember> newList, Map<Id, OpportunityTeamMember> newMap, List<OpportunityTeamMember> oldList, Map<Id, OpportunityTeamMember> oldMap) {
        Map<Id, Integer> oppTmCntMap = new Map<Id, Integer>();
        Map<Id, Integer> oppTmCntMapSTMS = new Map<Id, Integer>();
        for (OpportunityTeamMember om : newList) {
            if (om.TeamMemberRole == '副担当') {
                oppTmCntMap.put(om.OpportunityId, 0);
            }
            if (om.TeamMemberRole == 'STMS担当') {
                oppTmCntMapSTMS.put(om.OpportunityId, 0);
            }
        }
        if (oppTmCntMap.size() > 0) {
            // 副担当が既に設定済みかを抽出する(Afterなので、Trigger.newのデータも入っています)
            List<OpportunityTeamMember> oppTmList = [
                    select Id, OpportunityId, TeamMemberRole from OpportunityTeamMember
                    where OpportunityId IN :oppTmCntMap.keySet()
                    and TeamMemberRole = '副担当'];
            if (oppTmList.size() > 0) {
                for (OpportunityTeamMember oppTm : oppTmList) {
                    oppTmCntMap.put(oppTm.OpportunityId, oppTmCntMap.get(oppTm.OpportunityId) + 1);
                    OpportunityTeamMember om = newMap.get(oppTm.Id);
                    if (om != null) {
                        // プログラムのロジックからのではない場合
                        if (OpportunityMemberTrigger.syncMBOpportunityOtmMap.get(om.OpportunityId) == null) {
                            om.addError('不能直接追加修改删除［副担当］，请从询价画面上操作。');
                        } else if (om.TeamMemberRole == '副担当' && oppTmCntMap.get(oppTm.OpportunityId) > 1) {
                            om.addError(System.Label.Error_Message_OppTeamMember01);
                        }
                    }
                }
            }
        }
        // CHAN-BB38N4 start stms 副担当以及没有了，去掉这个逻辑
        //if (oppTmCntMapSTMS.size() > 0) {
        //    // STMS担当が既に設定済みかを抽出する(Afterなので、Trigger.newのデータも入っています)
        //    List<OpportunityTeamMember> oppTmList = [
        //            select Id, OpportunityId, TeamMemberRole from OpportunityTeamMember
        //            where OpportunityId IN :oppTmCntMapSTMS.keySet()
        //            and TeamMemberRole = 'STMS担当'];
        //    if (oppTmList.size() > 0) {
        //        for (OpportunityTeamMember oppTm : oppTmList) {
        //            oppTmCntMapSTMS.put(oppTm.OpportunityId, oppTmCntMapSTMS.get(oppTm.OpportunityId) + 1);
        //            OpportunityTeamMember om = newMap.get(oppTm.Id);
        //            if (om != null) {
        //                // プログラムのロジックからのではない場合
        //                if (OpportunityMemberTrigger.syncMBOpportunityOtmMapSTMS.get(om.OpportunityId) == null) {
        //                    om.addError('不能直接追加修改删除［STMS担当］，请从询价画面上操作。');
        //                }
        //                if (om.TeamMemberRole == 'STMS担当' && oppTmCntMapSTMS.get(oppTm.OpportunityId) > 1) {
        //                    om.addError(System.Label.Error_Message_OppTeamMember02);
        //                }
        //            }
        //        }
        //    }
        //}
        //// CHAN-BB38N4 start stms 副担当以及没有了，去掉这个逻辑
    }

    // on OpportunityTeamMember (after delete)
    // 引合チーム「副担当」直接削除チェック
    public static void opportunityMemberDeleteError(List<OpportunityTeamMember> newList, Map<Id, OpportunityTeamMember> newMap, List<OpportunityTeamMember> oldList, Map<Id, OpportunityTeamMember> oldMap) {
        Map<Id, Id> oppIdMap = new Map<Id, Id>();
        Map<Id, Id> oppIdMapSTMS = new Map<Id, Id>();
        for (OpportunityTeamMember om : oldList) {
            if (om.TeamMemberRole == '副担当') {
                oppIdMap.put(om.OpportunityId, om.OpportunityId);
            }
            if (om.TeamMemberRole == 'STMS担当') {
                oppIdMapSTMS.put(om.OpportunityId, om.OpportunityId);
            }
        }
        if (oppIdMap.size() > 0) {
            Map<Id, Opportunity> oppMap = new Map<Id, Opportunity>([
                        select Id, Opportunity_sub_owner__c from Opportunity
                        where Id IN :oppIdMap.keySet()]);
            for (OpportunityTeamMember om : oldList) {
                if (om.TeamMemberRole == '副担当' && String.isBlank(oppMap.get(om.OpportunityId).Opportunity_sub_owner__c) == false) {
                    // プログラムのロジックからのではない場合
                    if (OpportunityMemberTrigger.syncMBOpportunityOtmMap.get(om.OpportunityId) == null) {
                        om.addError('不能直接追加修改删除［副担当］，请从询价画面上操作。');
                    }
                }
            }
        }
        // CHAN-BB38N4 start stms 副担当以及没有了，去掉这个逻辑
        //if (oppIdMapSTMS.size() > 0) {
        //    Map<Id, Opportunity> oppMap = new Map<Id, Opportunity>([
        //                select Id, Opportunity_stms_owner__c from Opportunity
        //                where Id IN :oppIdMapSTMS.keySet()]);
        //    for (OpportunityTeamMember om : oldList) {
        //        if (om.TeamMemberRole == 'STMS担当' && String.isBlank(oppMap.get(om.OpportunityId).Opportunity_stms_owner__c) == false) {
        //            // プログラムのロジックからのではない場合
        //            if (OpportunityMemberTrigger.syncMBOpportunityOtmMapSTMS.get(om.OpportunityId) == null) {
        //                om.addError('不能直接追加修改删除［STMS担当］，请从询价画面上操作。');
        //            }
        //        }
        //    }
        //}
        //// CHAN-BB38N4 start stms 副担当以及没有了，去掉这个逻辑
    }

    // データ操作の共通関数
    public static void delInsOpportunityTeamMember(Map<Id, OpportunityTeamMember> otmMap) {
        syncMBOpportunityOtmMap.putAll(otmMap);
        List<OpportunityTeamMember> delOppTMList = new List<OpportunityTeamMember>();
        // oppId ==> userId
        Id breakOppId = null;

        //OLY_OCM-199 0512 start
        List<Id> userIdList = new List<Id>();
        for (OpportunityTeamMember otm : otmMap.values()) {
            if (otm.UserId != null) {
                userIdList.add(otm.UserId);
            }
        }
        Map<Id, User> IsActiveMap = new Map<Id, User>([SELECT Id, IsActive From User where IsActive = false AND Id IN :userIdList]);
        for (Id oppId : otmMap.keyset()) {
            if (IsActiveMap.containsKey(otmMap.get(oppId).UserId) == true) {
                otmMap.remove(oppId);
            }
        }
        //OLY_OCM-199 0512 end

        // CHAN-AVS9S2 修正:手动共享删除
        // HWAG-B6J4ZN 手动共享不能删除给FSE主担当的共享 start
        List<OpportunityShare> osList = [select id,UserOrGroupId,OpportunityId from OpportunityShare where OpportunityId in :otmMap.keySet() and rowcause = 'Manual'];

        Map<Id, AggregateResult> aggMap =
            new Map<Id, AggregateResult>([select Opportunity__r.id Id,
                // SWAG-B7LADC 2018/12/21 获取出对应医院所有的副担当，并检索出其ID start
                                          Max(Opportunity__r.Hospital__r.FSE_GI_Main_Leader__r.Alias__c) FSE_GI,
                                          Max(Opportunity__r.Hospital__r.FSE_SP_Main_Leader__r.Alias__c) FSE_SP,
                                          Max(Opportunity__r.Hospital__r.FSE_ENG_Main_Leader__r.Alias__c) FSE_ENG,
                                          Max(Opportunity__r.Hospital__r.FSE_ENG_Vice_Leader__c) FSE_ENG_VICE,
                                          Max(Opportunity__r.Hospital__r.FSE_GI_Vice_Leader__c) FSE_GI_VICE,
                                          Max(Opportunity__r.Hospital__r.FSE_SP_Vice_Leader__c) FSE_SP_VICE
                    // SWAG-B7LADC 2018/12/21 获取出对应医院所有的副担当，并检索出其ID end
                                          from Statu_Achievements__c
                                          where ForecastAccuracyObject__c = true and DeliveryDate__c != null
                                                          and Opportunity__r.id != null
                                                          and Opportunity__r.id in :otmMap.keySet()
                                                          group by Opportunity__r.id]);
        // SWAG-B7LADC 2018/12/21 获取出对应医院所有的副担当，并检索出其ID start
        list<string> allUserNameList = new list<string>();
        for(AggregateResult temAgg: aggMap.values()){
            if(temAgg.get('FSE_GI') != null){
                allUserNameList.add(String.valueOf(temAgg.get('FSE_GI')));
            }
            if(temAgg.get('FSE_SP') != null){
                allUserNameList.add(String.valueOf(temAgg.get('FSE_SP')));
            }
            if(temAgg.get('FSE_ENG') != null){
                allUserNameList.add(String.valueOf(temAgg.get('FSE_ENG')));
            }
            if(temAgg.get('FSE_ENG_VICE') != null){
                for(String UsrName : String.valueOf(temAgg.get('FSE_ENG_VICE')).split('[,\\，]')){
                     allUserNameList.add(UsrName);
                }
            }
            if(temAgg.get('FSE_GI_VICE') != null){
                for(String UsrName : String.valueOf(temAgg.get('FSE_GI_VICE')).split('[,\\，]')){
                     allUserNameList.add(UsrName);
                }
            }
            if(temAgg.get('FSE_SP_VICE') != null){
                for(String UsrName : String.valueOf(temAgg.get('FSE_SP_VICE')).split('[,\\，]')){
                     allUserNameList.add(UsrName);
                }
            } 
        }
        list<User> allFSEUserlist = [select id from User where Alias__c in: allUserNameList];
        list<ID> allFSEUserIDList = new list<ID>();
        for(User TempUser: allFSEUserlist){
            allFSEUserIDList.add(TempUser.id);
        }
        
        // SWAG-B7LADC 2018/12/21 获取出对应医院所有的副担当，并检索出其ID end
        
        // SWAG-B7LADC 2018/12/21 FSE 手动不删除 start

        List<OpportunityShare> DelosList = new List<OpportunityShare>();
        system.debug('aggMap:' + aggMap);
        system.debug('aggMap:' + osList);

        if(aggMap.size()>0){
            for ( Opportunityshare ops : osList) {
                if (!allFSEUserIDList.contains((ID)ops.UserOrGroupId)
                    && ops.UserOrGroupId != Label.Group_ServiceManagementID) {
                    //system.debug('ops.UserOrGroupId:' + ops.UserOrGroupId);
                    DelosList.add(ops);
                }
            }
        }
        // SWAG-B7LADC 2018/12/21 FSE 手动不删除 end
         // HWAG-B6J4ZN 手动共享不能删除给FSE主担当的共享 end
        if (DelosList.size() > 0) delete DelosList;

        // CHAN-AVS9S2

        for (OpportunityTeamMember otm :
                [select Id, OpportunityId, UserId
                 from OpportunityTeamMember where OpportunityId in :otmMap.keySet() and TeamMemberRole = '副担当' order by OpportunityId, CreatedDate desc]
            ) {
            // 前提、副担当１人だけです。
            if (breakOppId == null || breakOppId != otm.OpportunityId) {
                System.debug('breakOppId:' + breakOppId + 'OpportunityId:' + otm.OpportunityId);
                if (breakOppId != null && otmMap.get(breakOppId) != null && otmMap.get(breakOppId).UserId == null) {
                    otmMap.remove(breakOppId);
                }
                breakOppId = otm.OpportunityId;
                System.debug('breakOppId:' + breakOppId);
            }
            System.debug('otmMap.UserId:' + otmMap.get(otm.OpportunityId).UserId);
            System.debug('otm.UserId:' + otm.UserId);
            // 削除か、新規か を判断
            // 要注意 otmMap の UserId が nullの場合も削除します。
            if (otmMap.get(otm.OpportunityId).UserId != otm.UserId) {
                System.debug('delOppTMList.add(otm)');
                delOppTMList.add(otm);
            } else {
                System.debug('otmMap.remove(otm.OpportunityId)');
                otmMap.remove(otm.OpportunityId);
            }
        }
        // otmMapに残っているデータをloopして、UserIdがnullのものを削除
        // 例えば、削除対象になってけど、チームに副担当が居ない場合、先ほどのfor (OpportunityTeamMember otm :) よりremoveしきれないです。
        for (Id oppId : otmMap.keyset()) {
            if (otmMap.get(oppId).UserId == null) {
                otmMap.remove(oppId);
            }
        }
        if (delOppTMList.size() > 0) {
            delete delOppTMList;
        }
        if (otmMap.size() > 0) {
            insert otmMap.values();
            List<OpportunityShare> newShare = new List<OpportunityShare>();
            for (OpportunityTeamMember otm : otmMap.values()) {
                newShare.add(new OpportunityShare(
// Edit に固定 by xud 20131203
                                 UserOrGroupId = otm.UserId, OpportunityId = otm.OpportunityId, OpportunityAccessLevel = 'Edit'
                             ));
            }
            if (newShare.size() > 0) {
                Database.SaveResult[] 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 OPPORTUNITY SHARING:' + emsg);
                    }
                }
            }
        }
    }

     // CHAN-BB38N4 start stms 副担当以及没有了，去掉这个逻辑
    // データ操作の共通関数
    //public static void delInsOpportunityTeamMemberSTMS(Map<Id, OpportunityTeamMember> otmMap) {
    //    syncMBOpportunityOtmMapSTMS.putAll(otmMap);
    //    List<OpportunityTeamMember> delOppTMList = new List<OpportunityTeamMember>();
    //    // oppId ==> userId
    //    Id breakOppId = null;

    //    //OLY_OCM-199 0512 start
    //    List<Id> userIdList = new List<Id>();
    //    for (OpportunityTeamMember otm : otmMap.values()) {
    //        if (otm.UserId != null) {
    //            userIdList.add(otm.UserId);
    //        }
    //    }
    //    Map<Id, User> IsActiveMap = new Map<Id, User>([SELECT Id, IsActive From User where IsActive = false AND Id IN :userIdList]);
    //    for (Id oppId : otmMap.keyset()) {
    //        if (IsActiveMap.containsKey(otmMap.get(oppId).UserId) == true) {
    //            otmMap.remove(oppId);
    //        }
    //    }
    //    //OLY_OCM-199 0512 end

    //    // CHAN-AVS9S2 修正:手动共享删除
    //    // HWAG-B6J4ZN 手动共享不能删除给FSE主担当的共享 start
    //    List<OpportunityShare> osList = [select id,UserOrGroupId,OpportunityId from OpportunityShare where OpportunityId in :otmMap.keySet() and rowcause = 'Manual'];

    //    Map<Id, AggregateResult> aggMap =
    //        new Map<Id, AggregateResult>([select Opportunity__r.id Id,
    //            // SWAG-B7LADC 2018/12/21 获取出对应医院所有的副担当，并检索出其ID start
    //                                      Max(Opportunity__r.Hospital__r.FSE_GI_Main_Leader__r.Alias__c) FSE_GI,
    //                                      Max(Opportunity__r.Hospital__r.FSE_SP_Main_Leader__r.Alias__c) FSE_SP,
    //                                      Max(Opportunity__r.Hospital__r.FSE_ENG_Main_Leader__r.Alias__c) FSE_ENG,
    //                                      Max(Opportunity__r.Hospital__r.FSE_ENG_Vice_Leader__c) FSE_ENG_VICE,
    //                                      Max(Opportunity__r.Hospital__r.FSE_GI_Vice_Leader__c) FSE_GI_VICE,
    //                                      Max(Opportunity__r.Hospital__r.FSE_SP_Vice_Leader__c) FSE_SP_VICE
    //                // SWAG-B7LADC 2018/12/21 获取出对应医院所有的副担当，并检索出其ID end
    //                                      from Statu_Achievements__c
    //                                      where ForecastAccuracyObject__c = true and DeliveryDate__c != null
    //                                                      and Opportunity__r.id != null
    //                                                      and Opportunity__r.id in :otmMap.keySet()
    //                                                      group by Opportunity__r.id]);
    //    // SWAG-B7LADC 2018/12/21 获取出对应医院所有的副担当，并检索出其ID start
    //    list<string> allUserNameList = new list<string>();
    //    for(AggregateResult temAgg: aggMap.values()){
    //        if(temAgg.get('FSE_GI') != null){
    //            allUserNameList.add(String.valueOf(temAgg.get('FSE_GI')));
    //        }
    //        if(temAgg.get('FSE_SP') != null){
    //            allUserNameList.add(String.valueOf(temAgg.get('FSE_SP')));
    //        }
    //        if(temAgg.get('FSE_ENG') != null){
    //            allUserNameList.add(String.valueOf(temAgg.get('FSE_ENG')));
    //        }
    //        if(temAgg.get('FSE_ENG_VICE') != null){
    //            for(String UsrName : String.valueOf(temAgg.get('FSE_ENG_VICE')).split('[,\\，]')){
    //                 allUserNameList.add(UsrName);
    //            }
    //        }
    //        if(temAgg.get('FSE_GI_VICE') != null){
    //            for(String UsrName : String.valueOf(temAgg.get('FSE_GI_VICE')).split('[,\\，]')){
    //                 allUserNameList.add(UsrName);
    //            }
    //        }
    //        if(temAgg.get('FSE_SP_VICE') != null){
    //            for(String UsrName : String.valueOf(temAgg.get('FSE_SP_VICE')).split('[,\\，]')){
    //                 allUserNameList.add(UsrName);
    //            }
    //        } 
    //    }
    //    list<User> allFSEUserlist = [select id from User where Alias__c in: allUserNameList];
    //    list<ID> allFSEUserIDList = new list<ID>();
    //    for(User TempUser: allFSEUserlist){
    //        allFSEUserIDList.add(TempUser.id);
    //    }
    //    // SWAG-B7LADC 2018/12/21 获取出对应医院所有的副担当，并检索出其ID end
        
    //    // SWAG-B7LADC 2018/12/21 FSE 手动不删除 start

    //    List<OpportunityShare> DelosList = new List<OpportunityShare>();
    //    system.debug('aggMap:' + aggMap);
    //    system.debug('aggMap:' + osList);
    //    if(aggMap.size()>0){
    //        for ( Opportunityshare ops : osList) {
    //            if (!allFSEUserIDList.contains( (ID) ops.UserOrGroupId)
    //                && ops.UserOrGroupId != Label.Group_ServiceManagementID  ) {
    //                DelosList.add(ops);
    //                //system.debug('ops.UserOrGroupId:' + ops.UserOrGroupId);
    //            }
    //        }
    //    }
    //    // SWAG-B7LADC 2018/12/21 FSE 手动不删除 end
    //     // HWAG-B6J4ZN 手动共享不能删除给FSE主担当的共享 end
    //    if (DelosList.size() > 0) delete DelosList;

    //    // CHAN-AVS9S2

    //    for (OpportunityTeamMember otm :
    //            [select Id, OpportunityId, UserId
    //             from OpportunityTeamMember where OpportunityId in :otmMap.keySet() and TeamMemberRole = 'STMS担当' order by OpportunityId, CreatedDate desc]
    //        ) {
    //        // 前提、STMS担当１人だけです。
    //        if (breakOppId == null || breakOppId != otm.OpportunityId) {
    //            if (breakOppId != null && otmMap.get(breakOppId) != null && otmMap.get(breakOppId).UserId == null) {
    //                otmMap.remove(breakOppId);
    //            }
    //            breakOppId = otm.OpportunityId;
    //        }
    //        // 削除か、新規か を判断
    //        // 要注意 otmMap の UserId が nullの場合も削除します。
    //        if (otmMap.get(otm.OpportunityId).UserId != otm.UserId) {
    //            delOppTMList.add(otm);
    //        } else {
    //            otmMap.remove(otm.OpportunityId);
    //        }
    //    }
    //    for (Id oppId : otmMap.keyset()) {
    //        if (otmMap.get(oppId).UserId == null) {
    //            otmMap.remove(oppId);
    //        }
    //    }
    //    if (delOppTMList.size() > 0) {
    //        delete delOppTMList;
    //    }
    //    if (otmMap.size() > 0) {
    //        insert otmMap.values();
    //        List<OpportunityShare> newShare = new List<OpportunityShare>();
    //        for (OpportunityTeamMember otm : otmMap.values()) {
    //            newShare.add(new OpportunityShare(
    //                             UserOrGroupId = otm.UserId, OpportunityId = otm.OpportunityId, OpportunityAccessLevel = 'Edit'
    //                         ));
    //        }
    //        if (newShare.size() > 0) {
    //            Database.SaveResult[] 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 OPPORTUNITY SHARING:' + emsg);
    //                }
    //            }
    //        }
    //    }
    //}
    // // CHAN-BB38N4 start stms 副担当以及没有了，去掉这个逻辑
}