public with sharing class ConsumableTargetManageHandler extends Oly_TriggerHandler  {
    private Map<Id, ConsumableTargetManage__c> newMap;
    private Map<Id, ConsumableTargetManage__c> oldMap;
    private List<ConsumableTargetManage__c> newList;
    private List<ConsumableTargetManage__c> oldList;
    public ConsumableTargetManageHandler() {
        this.newMap = (Map<Id, ConsumableTargetManage__c>) Trigger.newMap;
        this.oldMap = (Map<Id, ConsumableTargetManage__c>) Trigger.oldMap;
        this.newList = (List<ConsumableTargetManage__c>) Trigger.new;
        this.oldList = (List<ConsumableTargetManage__c>) Trigger.old;
    }
    protected override void beforeInsert(){
        createdConsumableTargetManage();
    }
    protected override void afterInsert(){
        HospitalToIMSUser();
        OCSMToTMSUser(); // you 20240307 为IMS添加办事处中ET，ENG担当的查看权限
    }
    protected override void afterUpdate(){
        OCSMToTMSUser();
    }
    //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 start
    protected override void beforeUpdate(){
        createdConsumableTargetManage();
        HospitalToIMSUser();
    }
    //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 end
    private void createdConsumableTargetManage(){
        //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 start
        // if(trigger.isInsert){
        if(trigger.isInsert||trigger.isUpdate){
        //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 end
            List<Id> hospit = new List<Id>();
            for(ConsumableTargetManage__c ctm : newList){
                hospit.add(ctm.Hospital__c);
            }
            List<Account> hospital = [select Id,ET_owner__c,ET_Product_Leader__c from Account where Id in:hospit];
            Map<Id,Account> hospitalMap = new Map<Id,Account>();
            if(hospital.size()>0){
                for(Account account : hospital){
                    hospitalMap.put(account.Id,account);
                }
            }
            for(ConsumableTargetManage__c ctm : newList){
                //将ET主担当赋给所有人,并给担当添加共享，只有ET修改所有人
                if(hospitalMap.containsKey(ctm.Hospital__c) && hospitalMap.get(ctm.Hospital__c) != null){
                    //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 start
                    if(ctm.OwnerId != hospitalMap.get(ctm.Hospital__c).ET_owner__c){
                        if(ctm.productType__c == 'ET耗材'){
                    //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 end
                            ctm.OwnerId = hospitalMap.get(ctm.Hospital__c).ET_owner__c;
                    //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 start
                        }
                    }
                    //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 end
                }
            }
        }
    }
    private void HospitalToIMSUser(){
        //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 start
        // if(trigger.isInsert){
        System.debug('test>>');
        if(trigger.isInsert||trigger.isUpdate){
        //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 end
            List<Id> hospit = new List<Id>();
            List<Id> cbtmit = new List<Id>();
            for(ConsumableTargetManage__c ctm : newList){
                hospit.add(ctm.Hospital__c);
                cbtmit.add(ctm.Id);
            }
            //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 start
            // List<Account> hospital = [select Id,ET_owner__c,ET_Product_Leader__c from Account where Id in:hospit];
            List<Account> hospital = [select Id,ET_owner__c,ET_Product_Leader__c,Energy_LeaderStr__c from Account where Id in:hospit];
            //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 end
            Map<Id,Account> hospitalMap = new Map<Id,Account>();
            Map<String, String> product_leaders = new Map<String, String>();
            if(hospital.size()>0){
                for(Account account : hospital){
                    hospitalMap.put(account.Id,account);
                    if (String.isNotBlank(account.ET_Product_Leader__c)) {
                        String[] names = account.ET_Product_Leader__c.split(',');
                        for(String name : names) {
                            if (String.isNotBlank(name)) {
                                product_leaders.put(name, null);
                            }
                        }
                    }
                    //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 start
                    if (String.isNotBlank(account.Energy_LeaderStr__c)) {
                        String[] names = account.Energy_LeaderStr__c.split(',');
                        for(String name : names) {
                            if (String.isNotBlank(name)) {
                                product_leaders.put(name, null);
                            }
                        }
                    }
                    //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 end
                    System.debug('Energy_LeaderStr__c>>'+account.Energy_LeaderStr__c);
                    System.debug('ET_Product_Leader__c>>'+account.ET_Product_Leader__c);
                }
            }
            // 获得担当
            //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 start
            Map<Id,User> product_leaderMap = new Map<Id,User>();
            //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 end
            if (product_leaders.size() > 0) {
                List<User> lstUsers = [select Id, Alias from User where Alias in :product_leaders.keySet() and IsActive = true];
                for (User user : lstUsers) {
                    product_leaders.put(user.Alias, user.Id);
                    //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 start
                    product_leaderMap.put(user.Id,user);
                    //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 end
                }
            }
            System.debug('product_leaders>>'+product_leaders);
            // 权限类型
            List<String> rowCauseList = new List<String>();
            String rowCauseEdit = Schema.ConsumableTargetManage__Share.RowCause.HospitalToIMSUser__c;
            rowCauseList.add(rowCauseEdit);
            // 清理共享
            //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 start
            // List<ConsumableTargetManage__Share> delShares = [select Id from ConsumableTargetManage__Share where ParentId in :cbtmit and RowCause in :rowCauseList];
            List<ConsumableTargetManage__Share> delShares = [select Id,UserOrGroup.Name,ParentId,Parent.productType__c from ConsumableTargetManage__Share where ParentId in :cbtmit and RowCause in :rowCauseList];
            Set<Id> notdelShares = new Set<Id>();
            //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 end
            if (delShares != null && delShares.size() > 0) {
                System.debug('delShares>>'+delShares);
                //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 start
                Set<Id> shareId= new Set<Id>();
                List<ConsumableTargetManage__Share> delShares2 = new List<ConsumableTargetManage__Share>();
                for (ConsumableTargetManage__Share sharevalue : delShares) {
                    if(sharevalue.Parent.productType__c == '外科耗材'){
                        String Energy_LeaderStr = hospitalMap.get(newMap.get(sharevalue.ParentId).Hospital__c).Energy_LeaderStr__c;
                        if(String.isBlank(Energy_LeaderStr) ||(String.isNotBlank(Energy_LeaderStr) && !(Energy_LeaderStr.contains(sharevalue.UserOrGroup.Name)))){
                            shareId.add(sharevalue.ParentId);
                        }
                    }else{
                        String ET_Product_Leader = hospitalMap.get(newMap.get(sharevalue.ParentId).Hospital__c).ET_Product_Leader__c;
                        if(String.isBlank(ET_Product_Leader) ||(String.isNotBlank(ET_Product_Leader) && !(ET_Product_Leader.contains(sharevalue.UserOrGroup.Name)))){
                            shareId.add(sharevalue.ParentId);
                        }
                    }
                    
                }
                for (ConsumableTargetManage__Share sharevalue2 : delShares) {
                    if(shareId.contains(sharevalue2.ParentId)){
                        delShares2.add(sharevalue2);
                    }else{
                        notdelShares.add(sharevalue2.ParentId);
                    }
                }
                System.debug('delShares2>>'+delShares2);
                if(delShares2 != null && delShares2.size() > 0){
                    delete delShares2;
                }
                // delete delShares;
                //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 end
            }
            List<ConsumableTargetManage__Share> addShares = new List<ConsumableTargetManage__Share>();
            for(ConsumableTargetManage__c ctm : newList){
                //将ET主担当赋给所有人,并给担当添加共享
                //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 start
                if(!notdelShares.contains(ctm.Id)){
                //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 end
                    if(hospitalMap.containsKey(ctm.Hospital__c) && hospitalMap.get(ctm.Hospital__c) != null){
                        Account hospitalvalue = hospitalMap.get(ctm.Hospital__c);
                        System.debug('hospitalvalue>>'+hospitalvalue);
                        //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 start
                        if(ctm.productType__c == '外科耗材'){
                            if (String.isNotBlank(hospitalvalue.Energy_LeaderStr__c)) {
                                String[] users = hospitalvalue.Energy_LeaderStr__c.split(',');
                                for (String user : users) {
                                    if (product_leaders.get(user) != null) {
                                        addShares.add(new ConsumableTargetManage__Share(ParentId = ctm.Id, RowCause = rowCauseEdit, UserOrGroupId = product_leaders.get(user), AccessLevel = 'Edit'));
                                    }
                                }
                            }
                        }else{
                        //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 end
                            if (String.isNotBlank(hospitalvalue.ET_Product_Leader__c)) {
                                String[] users = hospitalvalue.ET_Product_Leader__c.split(',');
                                System.debug('users>>'+users);
                                for (String user : users) {
                                    if (product_leaders.get(user) != null) {
                                        addShares.add(new ConsumableTargetManage__Share(ParentId = ctm.Id, RowCause = rowCauseEdit, UserOrGroupId = product_leaders.get(user), AccessLevel = 'Edit'));
                                    }
                                }
                            }
                        //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 start
                        }
                        System.debug('ctm>>'+ctm);
                        System.debug('addShares>>'+addShares);
                        //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 end
                    }
                //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 start
                }
                //DB202312611748 【IMS/TMS】IMS管理表--耗材管理工具 end
            }
            if (addShares.size() > 0) {
                insert addShares;
            }
        }
    }
    private void OCSMToTMSUser(){
        Set<String> IMSPros = new Set<String>();
                String rowCause = Schema.ConsumableTargetManage__Share.RowCause.OCSMToIMSUser__c;
                List<OCM_Management_Province__c> mpList = new List<OCM_Management_Province__c>();
                Map<String, OCM_Management_Province__c> mpMap = new Map<String, OCM_Management_Province__c>();
        
                List<ConsumableTargetManage__Share> imssharlist =new List<ConsumableTargetManage__Share>();
                List<Id> deletetemsharlist = new List<Id>();
        
                for (ConsumableTargetManage__c newims : newList) {
                    if (Trigger.isInsert || (Trigger.isUpdate && newims.productType__c != oldMap.get(newims.Id).productType__c)) {
                        IMSPros.add(newims.H_OCM_man_province_HP__c); 
                    }            
                }
                
                if(null !=IMSPros && IMSPros.size()>0){
                    mpList = [select id,Name,ET_DataWindow__c,ET_BusinessWindow__c,ET_Assistant1__c,ET_Assistant2__c,ENG_DataWindow__c,ENG_BusinessWindow__c,ENG_Assistant1__c,ENG_Assistant2__c from OCM_Management_Province__c where Name in: IMSPros];
                    for (OCM_Management_Province__c mp: mpList){
                        mpMap.put(mp.Name, mp);
                    }          
                }
                if(null!=mpMap){      
                    for (ConsumableTargetManage__c nObj : newList) {
                        if (mpMap.containsKey(nObj.H_OCM_man_province_HP__c)) {
                           if(null!=nObj.productType__c && ''!= nObj.productType__c && null!=mpMap.get(nObj.H_OCM_man_province_HP__c)){
                              if(nObj.productType__c=='ET耗材'){
                                if(null!=mpMap.get(nObj.H_OCM_man_province_HP__c).ET_DataWindow__c && !''.equals(mpMap.get(nObj.H_OCM_man_province_HP__c).ET_DataWindow__c) && nObj.Ownerid !=mpMap.get(nObj.H_OCM_man_province_HP__c).ET_DataWindow__c){
                                    ConsumableTargetManage__Share tmsshare = new ConsumableTargetManage__Share(
                                    ParentId = nObj.Id,
                                    RowCause = rowCause,
                                    UserOrGroupId = mpMap.get(nObj.H_OCM_man_province_HP__c).ET_DataWindow__c,
                                    AccessLevel = 'read');
                                    imssharlist.add(tmsshare);
                                }
                                if(null!=mpMap.get(nObj.H_OCM_man_province_HP__c).ET_BusinessWindow__c && !''.equals(mpMap.get(nObj.H_OCM_man_province_HP__c).ET_BusinessWindow__c) && nObj.Ownerid !=mpMap.get(nObj.H_OCM_man_province_HP__c).ET_BusinessWindow__c){
                                    ConsumableTargetManage__Share tmsshare = new ConsumableTargetManage__Share(
                                    ParentId = nObj.Id,
                                    RowCause = rowCause,
                                    UserOrGroupId = mpMap.get(nObj.H_OCM_man_province_HP__c).ET_BusinessWindow__c,
                                    AccessLevel = 'read');
                                    imssharlist.add(tmsshare);
                                } 
                                if(null!=mpMap.get(nObj.H_OCM_man_province_HP__c).ET_Assistant1__c && !''.equals(mpMap.get(nObj.H_OCM_man_province_HP__c).ET_Assistant1__c) && nObj.Ownerid !=mpMap.get(nObj.H_OCM_man_province_HP__c).ET_Assistant1__c){
                                    ConsumableTargetManage__Share tmsshare = new ConsumableTargetManage__Share(
                                    ParentId = nObj.Id,
                                    RowCause = rowCause,
                                    UserOrGroupId = mpMap.get(nObj.H_OCM_man_province_HP__c).ET_Assistant1__c,
                                    AccessLevel = 'read');
                                    imssharlist.add(tmsshare);
                                }
                                if(null!=mpMap.get(nObj.H_OCM_man_province_HP__c).ET_Assistant2__c && !''.equals(mpMap.get(nObj.H_OCM_man_province_HP__c).ET_Assistant2__c) && nObj.Ownerid !=mpMap.get(nObj.H_OCM_man_province_HP__c).ET_Assistant2__c){
                                    ConsumableTargetManage__Share tmsshare = new ConsumableTargetManage__Share(
                                    ParentId = nObj.Id,
                                    RowCause = rowCause,
                                    UserOrGroupId = mpMap.get(nObj.H_OCM_man_province_HP__c).ET_Assistant2__c,
                                    AccessLevel = 'read');
                                    imssharlist.add(tmsshare);
                                }
                              }else{//ENG 
                                if(null!=mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_DataWindow__c && !''.equals(mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_DataWindow__c) && nObj.Ownerid !=mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_DataWindow__c){
                                    ConsumableTargetManage__Share tmsshare = new ConsumableTargetManage__Share(
                                    ParentId = nObj.Id,
                                    RowCause = rowCause,
                                    UserOrGroupId = mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_DataWindow__c,
                                    AccessLevel = 'read');
                                    imssharlist.add(tmsshare);
                                }
                                if(null!=mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_BusinessWindow__c && !''.equals(mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_BusinessWindow__c) && nObj.Ownerid !=mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_BusinessWindow__c){
                                    ConsumableTargetManage__Share tmsshare = new ConsumableTargetManage__Share(
                                    ParentId = nObj.Id,
                                    RowCause = rowCause,
                                    UserOrGroupId = mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_BusinessWindow__c,
                                    AccessLevel = 'read');
                                    imssharlist.add(tmsshare);
                                }
                                if(null!=mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_Assistant1__c && !''.equals(mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_Assistant1__c) && nObj.Ownerid !=mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_Assistant1__c){
                                    ConsumableTargetManage__Share tmsshare = new ConsumableTargetManage__Share(
                                    ParentId = nObj.Id,
                                    RowCause = rowCause,
                                    UserOrGroupId = mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_Assistant1__c,
                                    AccessLevel = 'read');
                                    imssharlist.add(tmsshare);
                                }
                                if(null!=mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_Assistant2__c && !''.equals(mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_Assistant2__c) && nObj.Ownerid !=mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_Assistant2__c){
                                    ConsumableTargetManage__Share tmsshare = new ConsumableTargetManage__Share(
                                    ParentId = nObj.Id,
                                    RowCause = rowCause,
                                    UserOrGroupId = mpMap.get(nObj.H_OCM_man_province_HP__c).ENG_Assistant2__c,
                                    AccessLevel = 'read');
                                    imssharlist.add(tmsshare);
                                }
                                
                              }
                              deletetemsharlist.add(nObj.Id);
                           }
                         
                       }
                    }    
                    
                }
                  // 先 Delete 后 Insert
                if (deletetemsharlist.size() > 0) {
                    List<ConsumableTargetManage__Share> deleteList = [SELECT Id
                        FROM ConsumableTargetManage__Share
                        WHERE RowCause = :rowCause
                          AND ParentId IN :deletetemsharlist
                    ];
                    delete deleteList;
                }
                if(null!=imssharlist){
                    insert imssharlist;
                }
        }		
}