public without sharing class TaskObjectTriggerHandle {
    public TaskObjectTriggerHandle() {
        
    }

    public void afterUpdateTask(List<task__c> newList,List<task__c> oldList,Map<Id,task__c> newMap,Map<Id,task__c> oldMap){
        List<task__c> updList = new List<task__c>();
        List<Id> compeleteIdList = new List<Id>();
        List<Id> cancelIdList = new List<Id>();
        List<Id> closeIdList = new List<Id>();
        List<Id> postponeIdList = new List<Id>();
        List<Id> unexecutedIdList = new List<Id>();
        List<Id> takeIdList = new List<Id>();
        // 【FY24大及巨大课题】北京新法规项目对应 DB202307428742 20230801 by lc Start
        List<Id> changeIdList = new List<Id>();
        // assignee的Id List
        List<Id> assigneeIdList = new List<Id>();
        // 盘点检查计划
        List<RecordType> inventoryTaskId = [select Id from RecordType where SobjectType = 'task__c' AND Name = '盘点检查计划'];
        // 温湿度检查计划
        List<RecordType> temperatureHumidityTaskId = [select Id from RecordType where SobjectType = 'task__c' AND Name = '温湿度检查计划'];
        // 【FY24大及巨大课题】北京新法规项目对应 DB202307428742 20230801 by lc End

        for(task__c tsk : newList){
            if(tsk.taskStatus__c != oldMap.get(tsk.Id).taskStatus__c){
                if(tsk.taskStatus__c == '03 完成'){
                    compeleteIdList.add(tsk.Id);
                }else if(tsk.taskStatus__c == '04 取消'){
                    cancelIdList.add(tsk.Id);
                }else if(tsk.taskStatus__c == '05 延期'){
                    postponeIdList.add(tsk.Id);
                }else if(tsk.taskStatus__c == '06 关闭'){
                    closeIdList.add(tsk.Id);
                }else if(tsk.taskStatus__c == '07 未执行'){
                    unexecutedIdList.add(tsk.Id);
                }else if(tsk.taskStatus__c == '02 接受'){
                    takeIdList.add(tsk.Id);
                }

                // 【FY24大及巨大课题】北京新法规项目对应 DB202307428742 20230801 by lc Start
                // 盘点计划或者温湿度盘点，同备品中心或者办事处，有一个任务状态发生改变，其余别的任务自动关闭
                if (tsk.RecordTypeId == inventoryTaskId[0].Id || tsk.RecordTypeId == temperatureHumidityTaskId[0].Id) {
                    changeIdList.add(tsk.Id);
                    assigneeIdList.add(tsk.assignee__c);
                }
                // 【FY24大及巨大课题】北京新法规项目对应 DB202307428742 20230801 by lc End
            }
        }

        // 【FY24大及巨大课题】北京新法规项目对应 DB202307428742 20230801 by lc Start
        if (!changeIdList.isEmpty()) {
            Map<Id, User> assigneeIdMap = new Map<Id, User>([
                    SELECT Id, Profile.Name, RoleName_wave__c, Work_Location__c 
                    FROM User WHERE IsActive = true AND Id IN: assigneeIdList]);

            List<task__c> updTaskList = new List<task__c>();
            for (Id ids : changeIdList) {
                task__c newTaskObj = newMap.get(ids);
                User assigneeObj = assigneeIdMap.get(newTaskObj.assignee__c);

                if (assigneeObj.Profile.Name == '2B2_备品中心检测&仓库管理(照片)') {
                    String roleName = assigneeObj.RoleName_wave__c;
                    // 备品中心
                    List<task__c> sameTask = [SELECT Id FROM task__c WHERE taskStatus__c = '01 分配' AND RecordTypeId =: newTaskObj.RecordTypeId AND assignee__r.Profile.Name = '2B2_备品中心检测&仓库管理(照片)' AND assignee__r.RoleName_wave__c =: roleName];

                    for (task__c t : sameTask) {
                        task__c newObj = new task__c();
                        newObj.Id = t.Id;
                        newObj.taskStatus__c = '06 关闭';
                        updTaskList.add(newObj);
                    }
                } else {
                    String workLocation = assigneeObj.Work_Location__c;
                    // 办事处
                    List<task__c> sameTask = [SELECT Id FROM task__c WHERE taskStatus__c = '01 分配' AND RecordTypeId =: newTaskObj.RecordTypeId AND assignee__r.Work_Location__c =: workLocation];

                    for (task__c t : sameTask) {
                        task__c newObj = new task__c();
                        newObj.Id = t.Id;
                        newObj.taskStatus__c = '06 关闭';
                        updTaskList.add(newObj);
                    }
                }
            }

            if (!updTaskList.isEmpty()) {
                FixtureUtil.withoutUpdate(updTaskList);
            }
        }
        // 【FY24大及巨大课题】北京新法规项目对应 DB202307428742 20230801 by lc End

        /*List<task__c> compeleteList = [select Id,taskStatus__c,mergeTaskMain__c from task__c where    mergeTaskMain__c in :compeleteIdList];
        
        if(compeleteList != null){
            for(task__c tsk : compeleteList){
                tsk.taskStatus__c = '03 完成';
            }
            update compeleteList;
        }*/

        /*
        2021-12-28  注释处理不同类型任务合并内容，只上线相同类型任务合并
        List<task__c> cancelList = [select Id,taskStatus__c,mergeTaskMain__c from task__c where     mergeTaskMain__c in :cancelIdList];
        if(cancelList != null){
            for(task__c tsk : cancelList){
                tsk.mergeTaskMain__c = null;
            }
            update cancelList;
        }

        List<task__c> postponeList = [select Id,taskStatus__c,mergeTaskMain__c from task__c where   mergeTaskMain__c in :postponeIdList];
        if(postponeList != null){
            for(task__c tsk : postponeList){
                tsk.mergeTaskMain__c = null;
            }
            update postponeList;
        }

        List<task__c> takeList = [select Id,taskStatus__c,mergeTaskMain__c from task__c where   mergeTaskMain__c in :takeIdList];
        if(takeList != null){
            for(task__c tsk : takeList){
                tsk.taskStatus__c = '02 接受';
                tsk.ConfirmDate__c = newMap.get(tsk.mergeTaskMain__c).ConfirmDate__c;
            }
            update takeList;
        }*/


        /*List<task__c> closeList = [select Id,taskStatus__c,mergeTaskMain__c from task__c where    mergeTaskMain__c in :closeIdList];
        if(closeList != null){
            for(task__c tsk : closeList){
                tsk.taskStatus__c = '06 关闭';
            }
            update closeList;
        }

        List<task__c> unexecutedList = [select Id,taskStatus__c,mergeTaskMain__c from task__c where     mergeTaskMain__c in :unexecutedIdList];
        
        if(unexecutedList != null){
            for(task__c tsk : unexecutedList){
                tsk.taskStatus__c = '07 未执行';
            }
            update unexecutedList;
        }*/
        
    }

    //2021-11-04  mzy  任务管理改善 start
    //当任务新建时,任务名称为*时,根据规则重新修改任务名称
    public void updateTaskNameAndOwner(List<task__c> newList,List<task__c> oldList,Map<Id,task__c> newMap,Map<Id,task__c> oldMap){
        System.debug('进入任务触发器');
        //定义变量保存记录类型
        
        Schema.DescribeFieldResult fieldResult = task__share.RowCause.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();

        Id Hcen_TaskId = Schema.SObjectType.task__c.getRecordTypeInfosByDeveloperName().get('HAccountVisit').getRecordTypeId();
        Map<String,String> taskPREMap = gettaskPREMap();
        List<Task__c> needUpdate = new List<Task__c>();
        Set<String> searchTaskId = new Set<String>();
        Set<String> tempSet = new Set<String>(); //2022-01-12  mzy  上级分配的记录类型为其他 的任务可能没有客户,需要把名称变为 其他:任务名称
        Set<String> OtherLeadAssig = new Set<String>();  //2022-01-12  mzy  上级分配的记录类型为其他 的任务可能没有客户,需要把名称变为 其他:任务名称
        String rowCause = 'SharingRecordCollection';//2022-5-10 yjk SWAG-CEA5AM
        for(Task__c task :newList){
            if(task.Id!=null){
                //任务名称为*时,且客户不为空时
                if('*'.equals(task.Name)&&task.account__c!=null){
                    searchTaskId.add(task.Id);
                }

                //2022-01-12 mzy  上级分配的记录类型为其他 的任务可能没有客户,需要把名称变为 其他:任务名称

                if('上级分配任务'.equals(task.TaskDifferent__c)&&task.account__c == null){
                    tempSet.add(task.Id);
                    
                }
            }
        } 
        //2022-01-12 mzy  上级分配的记录类型为其他 的任务可能没有客户,需要把名称变为 其他:任务名称  start
        if(tempSet.size()>0){
            List<Task__c> tempResult = [SELECT Id,TaskDifferent__c,RecordType.Name FROM Task__c WHERE Id in :tempSet];

            if(tempResult.size()>0){
                for(Task__c t:tempResult){
                    if('上级分配任务'.equals(t.TaskDifferent__c)&&'其他'.equals(t.RecordType.Name)){
                        searchTaskId.add(t.id);
                        OtherLeadAssig.add(t.id);
                    }
                }
            }
        }
        //2022-01-12 mzy  上级分配的记录类型为其他 的任务可能没有客户,需要把名称变为 其他:任务名称  end
        System.debug('进入任务触发器的任务:'+searchTaskId);
        if(searchTaskId.size()>0){
           List<Task__c> taskResult = [SELECT Id,Name,TaskDifferent__c,OpportunityId__c,RecordType.Name,taskType__c,OwnerId,account__c,assignee__c,account__r.Name,account__r.OCM_Category__c FROM Task__c WHERE Id in :searchTaskId];
           if(taskResult.size()>0){
                for(Task__c t :taskResult){
                    System.debug('类型:'+t.RecordType.Name);
                    System.debug('任务类型:'+taskPREMap.get(t.RecordType.Name));
                    //2022-01-12 mzy  上级分配的记录类型为其他 的任务可能没有客户,需要把名称变为 其他:任务名称
                    if(taskPREMap.get(t.RecordType.Name)!=null&&(!OtherLeadAssig.contains(t.Id))){
                        Task__c tempTsk = new Task__c();
                        tempTsk.Id = t.Id;
                        //任务的原所有人变为分配者
                        tempTsk.Assignmenter__c = t.OwnerId;
                        //被分配者变为任务的所有人
                        if(t.assignee__c!=null){
                            tempTsk.OwnerId = t.assignee__c;
                        }

                        //2022-5-10 yjk SWAG-CEA5AM
                        Task__Share aos = new Task__Share(
                         RowCause = rowCause,
                         ParentId = tempTsk.Id,
                         UserOrGroupId = t.OwnerId,
                         AccessLevel = 'Edit');
                        insert aos;

                        //如果页面选择询价了,则将询价的以下字段赋值给任务                        
                        //询价等级（分配）：记录分配时点的询价等级
                        //预测OCSM签约日（分配）：记录分配时点的预测签约日
                        //询价状态 (分配) : 记录分配时点的询价状态
                        //询价创建日 (分配) : 记录分配时点的询价创建日
                        //询价招标日 (分配) : 记录分配时点的询价招标日
                        //询价中标日 (分配) : 记录分配时点的询价中标日
                        if(t.OpportunityId__c != null){                         
                            Opportunity op = [SELECT Id,Competitor__c,Close_Forecasted_Date__c,Created_Day__c,StageName__c,
                            Bid_Date__c,Closing_Bid_Date__c FROM Opportunity WHERE Id  = :t.OpportunityId__c];
                            if(op!=null){
                                tempTsk.OppCompetitorDbt__c = op.Competitor__c;
                                tempTsk.CloseForecastedDateDbt__c = op.Close_Forecasted_Date__c;
                                tempTsk.OpportunityStatusDbt__c = op.StageName__c;
                                tempTsk.OppCreateDateDbt__c =op.Created_Day__c;
                                tempTsk.Bid_DateDbt__c =op.Bid_Date__c;
                                tempTsk.Closing_Bid_DateDbt__c =op.Closing_Bid_Date__c;
                            }
                        }
                        //任务类型(如果任务类型为日常拜访时,后台自动判断是否修改为H层拜访)
                        String typetask = t.RecordType.Name;
                        String OCMCategory = t.account__r.OCM_Category__c;
                        if('日常拜访'.equals(typetask)&&('H1'.equals(OCMCategory)||'H0'.equals(OCMCategory))){
                            tempTsk.RecordTypeId = Hcen_TaskId;
                        }
                        //任务状态
                        tempTsk.taskStatus__c = '01 分配';
                        //是否需要反馈
                        if('上级分配任务'.equals(t.TaskDifferent__c)){
                            tempTsk.NeedFeedback__c = true;
                        }
                        //任务名称
                        String tempAcName = t.account__r.Name;
                        tempTsk.Name = taskPREMap.get(typetask).replace('AccountName',tempAcName);
                        needUpdate.add(tempTsk);
                    }
                    //2022-01-12 mzy  上级分配的记录类型为其他 的任务可能没有客户,需要把名称变为 其他:任务名称
                    if (taskPREMap.get(t.RecordType.Name)!=null&&OtherLeadAssig.contains(t.Id)){
                        //需要变为 其他:任务名称
                        Task__c tempTsk = new Task__c();
                        tempTsk.Id = t.Id;
                        //任务的原所有人变为分配者
                        tempTsk.Assignmenter__c = t.OwnerId;
                        //被分配者变为任务的所有人
                        if(t.assignee__c!=null){
                            tempTsk.OwnerId = t.assignee__c;
                        }

                        //2022-5-10 yjk SWAG-CEA5AM
                        Task__Share aos = new Task__Share(
                            RowCause = rowCause,
                            ParentId = tempTsk.Id,
                            UserOrGroupId = t.OwnerId,
                            AccessLevel = 'Edit');
                        insert aos;

                        //如果页面选择询价了,则将询价的以下字段赋值给任务                        
                        //询价等级（分配）：记录分配时点的询价等级
                        //预测OCSM签约日（分配）：记录分配时点的预测签约日
                        //询价状态 (分配) : 记录分配时点的询价状态
                        //询价创建日 (分配) : 记录分配时点的询价创建日
                        //询价招标日 (分配) : 记录分配时点的询价招标日
                        //询价中标日 (分配) : 记录分配时点的询价中标日
                        if(t.OpportunityId__c != null){                         
                            Opportunity op = [SELECT Id,Competitor__c,Close_Forecasted_Date__c,Created_Day__c,StageName__c,
                            Bid_Date__c,Closing_Bid_Date__c FROM Opportunity WHERE Id  = :t.OpportunityId__c];
                            if(op!=null){
                                tempTsk.OppCompetitorDbt__c = op.Competitor__c;
                                tempTsk.CloseForecastedDateDbt__c = op.Close_Forecasted_Date__c;
                                tempTsk.OpportunityStatusDbt__c = op.StageName__c;
                                tempTsk.OppCreateDateDbt__c =op.Created_Day__c;
                                tempTsk.Bid_DateDbt__c =op.Bid_Date__c;
                                tempTsk.Closing_Bid_DateDbt__c =op.Closing_Bid_Date__c;
                            }
                        }
                        //任务状态
                        tempTsk.taskStatus__c = '01 分配';
                        //是否需要反馈
                        if('上级分配任务'.equals(t.TaskDifferent__c)){
                            tempTsk.NeedFeedback__c = true;
                        }
                        //任务名称
                        String tempTskName = '其他:' + t.Name;
                        tempTsk.Name = tempTskName;
                        needUpdate.add(tempTsk);
                    }
                }
                if(needUpdate.size()>0){
                  update needUpdate;
                }
           }
        }
    }
    @TestVisible
    private Map<String,String> gettaskPREMap(){
        Map<String,String> taskPREMap = new Map<String,String>();
        taskPREMap.put('多年保修任务',' 多年保修消费率预警任务（AccountName）');
        taskPREMap.put('询价跟进','用户拜访:AccountName');
        taskPREMap.put('H层拜访','用户拜访:AccountName');
        taskPREMap.put('OPD','用户拜访:AccountName');
        taskPREMap.put('SLA报告书任务','服务合同发放报告书任务（AccountName)');
        taskPREMap.put('经销商支持','经销商支持:AccountName');
        taskPREMap.put('学术会议跟进','学术会议:CampaignName');
        taskPREMap.put('服务季报','用户拜访:AccountName');
        taskPREMap.put('目标客户拜访','用户拜访:AccountName');
        taskPREMap.put('维修合同任务','用户拜访:AccountName');
        taskPREMap.put('日常拜访','用户拜访:AccountName');
        taskPREMap.put('其他','其他:AccountName');
        return taskPREMap;
    }
    //2021-11-04  mzy  任务管理改善  end
    //2021-11-17  mzy  任务管理改善  start    
    public void updateOverFeedback(List<task__c> newList,List<task__c> oldList,Map<Id,task__c> newMap,Map<Id,task__c> oldMap){
        //需要反馈并且反馈内容不为空,则算反馈完成

        Id OPDID = Schema.SObjectType.task__c.getRecordTypeInfosByDeveloperName().get('OPD').getRecordTypeId();
        List<Id> taskIdList = new List<Id>();//2021-12-14 Yjk 完成反馈任务id集合
        for(task__c tsk : newList){
            if(tsk.NeedFeedback__c&&tsk.FeedbackDescription__c!=null&&tsk.OverFeedback__c != true){
                tsk.OverFeedback__c = true;
                
                taskIdList.add(tsk.id);
            }
            //是否需要反馈
            if('上级分配任务'.equals(tsk.TaskDifferent__c)){
                tsk.NeedFeedback__c = true;
            }


            //2021-11-17 yjk opd类型新建时给产品明细赋值
            if(OPDID.equals(tsk.RecordTypeId) && '上级分配任务'.equals(tsk.TaskDifferent__c) && tsk.HopeCompletionDate__c != null && tsk.PlanProdDetail__c != null){
                Integer hopeMonth = tsk.HopeCompletionDate__c.month();
                String[] details = tsk.PlanProdDetail__c.split(';');
                String prodectDetail = '';
                for(String dtl : details){
                    prodectDetail =prodectDetail+dtl +':'+hopeMonth+'月;';
                }
                tsk.ProductDetails__c  = prodectDetail;
            }

            

        }

        //发送邮件
        List<Messaging.SingleEmailMessage> sendMails = new List<Messaging.SingleEmailMessage>();
        if(taskIdList.size() > 0){
            List<task__c> newTaskList = [select id,Name,TaskDifferent__c,PlanProdDetail__c,HopeCompletionDate__c,taskType__c,Assignmenter__r.email,NeedFeedback__c ,FeedbackDescription__c,OverFeedback__c from task__c where id in :taskIdList];

            for(task__c tsk : newTaskList){
                
                String title = '';
                String body = '';
                title = tsk.name + ' 任务已反馈';
                body += '您好:<br/>';
                body += '任务名为"'+tsk.name+'"的任务已反馈，<br/>';              
                //body += System.Label.OPD_Report;
                body += '具体结果请查阅链接，<a href="' + URL.getSalesforceBaseUrl().toExternalForm() + Label.feedbackTaskId+'">'
                        +URL.getSalesforceBaseUrl().toExternalForm() + Label.feedbackTaskId+ '</a><br/>'; 
                body += '谢谢！';
        
                Messaging.SingleEmailMessage messageNEW = new Messaging.SingleEmailMessage();
                messageNEW.setSubject(title);
                messageNEW.setHtmlBody(body);
                messageNEW.setCharset('UTF-8');
                System.debug('用户邮箱112212:'+tsk.Assignmenter__r.Email);
                messageNEW.setToAddresses(new list<String>{tsk.Assignmenter__r.Email}); 
                //messageNEW.setCcAddresses(new list<String>{'yangjieke@prec-tech.com','miaoziyang@prec-tech.com'});
                //setCcAddresses
                if(tsk.Assignmenter__r.Email != null){
                    sendMails.add(messageNEW);
                }

            }
        }
        if (sendMails.size() > 0) {
            Messaging.Email[] allMails = new Messaging.Email[]{};
            for(Integer j = 0; j < sendMails.size(); j++) {
                allMails.add(sendMails.get(j));
            }
            
            System.debug('所有邮件:'+allMails);
            Messaging.SendEmailResult[] results = Messaging.sendEmail(allMails);
            System.debug('results 结果 :'+results);

            for (Integer i = 0; i < results.size(); i++) {
                if (results[i].success == false) {
                    system.debug('=====send mail error:' + results[i].errors[0].message);
                }   
            }
        }
        
    }
    //2021-11-17  mzy  任务管理改善  end

    //2021-11-29  mzy  任务管理改善  start
    public void BeforeCheck(List<task__c> newList,List<task__c> oldList,Map<Id,task__c> newMap,Map<Id,task__c> oldMap){
        //分配者：
        //  对当前医院有权限的人（主担当，产品担当，FSE），保存检查是否有权限  ——   请协助确认是否只能选科室担当人
        //客户Id
        Set<String> accountIdset = new Set<String>();
        //客户List
        List<Account> alist = new List<Account>();
        //客户Map
        //key:科室Id v:担当
        Map<String,List<String>> amap = new Map<String,List<String>>();
        //key:科室Id v:产品担当
        Map<String,List<String>> amap_product = new Map<String,List<String>>();
        //key:科室Id v:产品担当文本名
        Map<String,Set<String>> amap_productSet = new Map<String,Set<String>>();
        //定义Set存放所有产品担当文本名
        Set<String> largeSet = new Set<String>();
        //科室
        //key:科室Id v:科室
        Map<String,Account> amap_Act = new Map<String,Account>();
        for(task__c tsk : newList){
            if('上级分配任务'.equals(tsk.TaskDifferent__c)&&tsk.account__c != null){
                accountIdset.add(tsk.account__c);
            }
            if('上级分配任务'.equals(tsk.TaskDifferent__c)){
                tsk.distributeReason__c = '上级分配';
            }
        }
        //查询当前客户的主担当,产品担当,FSE
        if(accountIdset.size()>0){              
            alist = [SELECT Id,Hospital__c,Hospital__r.OwnerId,Hospital__r.GI_Main__c,Hospital__r.GI_Main__r.isActive,
            Hospital__r.BF_owner__c,Hospital__r.BF_owner__r.isActive ,Hospital__r.ET_owner__c ,Hospital__r.ET_owner__r.isActive ,
            Hospital__r.SP_Main__c ,Hospital__r.SP_Main__r.isActive,Hospital__r.URO_owner_ID__c,Hospital__r.URO_owner_ID__r.isActive ,
            Hospital__r.GYN_owner__c,Hospital__r.GYN_owner__r.isActive,Hospital__r.ENT_owner_ID__c,Hospital__r.ENT_owner_ID__r.isActive,
            Hospital__r.FSE_SP_Main_Leader__c,Hospital__r.FSE_SP_Main_Leader__r.isActive,
            Hospital__r.FSE_GI_Main_Leader__c,Hospital__r.FSE_GI_Main_Leader__r.isActive ,Department_Class__c,Department_Class__r.Department_Class_Label__c,
            Hospital__r.GI_Product_Leader__c,Hospital__r.BF_Product_Leader__c,Hospital__r.ET_Product_Leader__c,
            Hospital__r.GS_Product_Leader__c,Hospital__r.URO_Produc_Leader__c,Hospital__r.Energy_LeaderStr__c,
            Hospital__r.GYN_Product_Leader__c,Hospital__r.ENT_Product_Leader__c,Hospital__r.FSE_SP_Vice_Leader__c,
            Hospital__r.FSE_GI_Vice_Leader__c 
            FROM Account WHERE Id in :accountIdset];

            if(alist.size()>0){

                for(Account tempa:alist){
                    String deptlabel = tempa.Department_Class__r.Department_Class_Label__c;
                    List<String> tempAlist = new List<String>();

                    if('消化科'.equals(deptlabel)){
                        //用户启用
                        if(tempa.Hospital__r.GI_Main__r.isActive){
                            tempAlist.add(tempa.Hospital__r.GI_Main__c);
                        }
                        String tempProd = tempa.Hospital__r.GI_Product_Leader__c;
                        if(String.isNotBlank(tempProd)){
                            if(tempProd.contains(',')){
                                largeSet.addAll(tempProd.split(','));
                            }else{
                                largeSet.add(tempProd);
                            }
                        }
                    }
                    if('呼吸科'.equals(deptlabel)){
                        //用户启用
                        if(tempa.Hospital__r.BF_owner__r.isActive){
                            tempAlist.add(tempa.Hospital__r.BF_owner__c); 
                        }
                        String tempProd = tempa.Hospital__r.BF_Product_Leader__c;
                        if(String.isNotBlank(tempProd)){
                            if(tempProd.contains(',')){
                                largeSet.addAll(tempProd.split(','));
                            }else{
                                largeSet.add(tempProd);
                            }
                        }
                    }
                    if('普外科'.equals(deptlabel)){
                        //用户启用
                        if(tempa.Hospital__r.SP_Main__r.isActive){
                            tempAlist.add(tempa.Hospital__r.SP_Main__c); 
                        }
                        String tempProd = tempa.Hospital__r.GS_Product_Leader__c;
                        if(String.isNotBlank(tempProd)){
                            if(tempProd.contains(',')){
                                largeSet.addAll(tempProd.split(','));
                            }else{
                                largeSet.add(tempProd);
                            }
                        }
                    }
                    if('泌尿科'.equals(deptlabel)){
                        //用户启用
                        if(tempa.Hospital__r.URO_owner_ID__r.isActive){
                            tempAlist.add(tempa.Hospital__r.URO_owner_ID__c);
                        }
                        String tempProd = tempa.Hospital__r.URO_Produc_Leader__c;
                        if(String.isNotBlank(tempProd)){
                            if(tempProd.contains(',')){
                                largeSet.addAll(tempProd.split(','));
                            }else{
                                largeSet.add(tempProd);
                            }
                        }
                    }
                    if('妇科'.equals(deptlabel)){
                        //用户启用
                        if(tempa.Hospital__r.GYN_owner__r.isActive){
                            tempAlist.add(tempa.Hospital__r.GYN_owner__c);
                        }
                        String tempProd = tempa.Hospital__r.GYN_Product_Leader__c;
                        if(String.isNotBlank(tempProd)){
                            if(tempProd.contains(',')){
                                largeSet.addAll(tempProd.split(','));
                            }else{
                                largeSet.add(tempProd);
                            }
                        }
                    }
                    if('耳鼻喉科'.equals(deptlabel)){
                        //用户启用
                        if(tempa.Hospital__r.ENT_owner_ID__r.isActive){
                            tempAlist.add(tempa.Hospital__r.ENT_owner_ID__c);
                        }
                        String tempProd = tempa.Hospital__r.ENT_Product_Leader__c;
                        if(String.isNotBlank(tempProd)){
                            if(tempProd.contains(',')){
                                largeSet.addAll(tempProd.split(','));
                            }else{
                                largeSet.add(tempProd);
                            }
                        }
                    }
                    if('ET'.equals(deptlabel)){
                        //用户启用
                        if(tempa.Hospital__r.ET_owner__r.isActive){
                            tempAlist.add(tempa.Hospital__r.ET_owner__c);
                        }
                        String tempProd = tempa.Hospital__r.ET_Product_Leader__c;
                        if(String.isNotBlank(tempProd)){
                            if(tempProd.contains(',')){
                                largeSet.addAll(tempProd.split(','));
                            }else{
                                largeSet.add(tempProd);
                            }
                        }
                    }
                    tempAlist.add(tempa.Hospital__r.OwnerId); 
                    // if(tempa.Hospital__r.FSE_SP_Main_Leader__r.isActive){
                    //  tempAlist.add(tempa.Hospital__r.FSE_SP_Main_Leader__c); 
                    // }
                    amap.put(tempa.Id,tempAlist);
                    amap_Act.put(tempa.Id,tempa);
                }

                if(largeSet.size()>0){
                    //根据别名查询启用的用户
                    List<User> uselist = [SELECT Id,Alias FROM User Where IsActive = true and Alias in :largeSet];
                    if(uselist.size()>0){                           
                        for(Account tempa:alist){                           
                            String deptlabel = tempa.Department_Class__r.Department_Class_Label__c;
                            List<String> uids = new List<String>();
                            for(User u :uselist){
                                if('消化科'.equals(deptlabel)
                                && tempa.Hospital__r.GI_Product_Leader__c.contains(u.Alias) ){
                                    uids.add(u.Id);
                                }
                                if('呼吸科'.equals(deptlabel)
                                &&tempa.Hospital__r.BF_Product_Leader__c.contains(u.Alias)){
                                    uids.add(u.Id);
                                }
                                if('普外科'.equals(deptlabel)
                                &&tempa.Hospital__r.GS_Product_Leader__c.contains(u.Alias)){
                                    uids.add(u.Id);
                                }
                                if('泌尿科'.equals(deptlabel)
                                &&tempa.Hospital__r.URO_Produc_Leader__c.contains(u.Alias)){
                                    uids.add(u.Id);
                                }
                                if('妇科'.equals(deptlabel)
                                &&tempa.Hospital__r.GYN_Product_Leader__c.contains(u.Alias)){
                                    uids.add(u.Id);
                                }
                                if('耳鼻喉科'.equals(deptlabel)
                                &&tempa.Hospital__r.ENT_Product_Leader__c.contains(u.Alias)){
                                    uids.add(u.Id);
                                }
                                if('ET'.equals(deptlabel)
                                &&tempa.Hospital__r.ET_Product_Leader__c.contains(u.Alias)){
                                    uids.add(u.Id);
                                }
                            }

                            if(amap.get(tempa.Id)!=null){
                                List<String> tempList = amap.get(tempa.Id);
                                if(uids.size()>0){
                                    tempList.addAll(uids);
                                }
                                amap.put(tempa.Id,tempList);
                            }
                        }
                    }
                }
            }
        }
        for(task__c tsk : newList){
            if('上级分配任务'.equals(tsk.TaskDifferent__c)&&tsk.account__c != null){
                if(amap_Act.get(tsk.account__c)!=null){
                    List<String> ActlistV= amap.get(tsk.account__c);
                    if(!ActlistV.contains(tsk.assignee__c)){
                        tsk.assignee__c.addError('请选择对当前科室有权限的人员进行分配!');
                        break;
                    }
                }
            }
        }

    }
    //2021-11-29  mzy  任务管理改善  end
    //20220720 you 中标任务 you start
    public void BeforeTaskOlympus(List<task__c> newList,List<task__c> oldList,Map<Id,task__c> newMap,Map<Id,task__c> oldMap){
       List<Date> cd = new List<Date>();
       List<Task__c> TaskOlyUpdate = new List<Task__c>();
       for(task__c tsk : newList){
            String datestr =String.valueOf(tsk.CreatedDate);
            cd.add( Date.valueOf(datestr.substring(0,10)) );
        }
        System.debug(LoggingLevel.INFO, '*** cd: ' + cd);
        Map<Date,Date> lm = new Map<Date,Date>();

       for(OlympusCalendar__c oc:[SELECT Id,Date__c,After_3_WorkDay__c FROM OlympusCalendar__c WHERE Date__c IN:cd]){
            lm.put(oc.Date__c,oc.After_3_WorkDay__c);     
       }
       System.debug(LoggingLevel.INFO, '*** map赋值: ' + lm);

       for(task__c tsk : newList){
            String datestr =String.valueOf(tsk.CreatedDate);
            Date dt = lm.get(Date.valueOf(datestr.substring(0,10)));
            Task__c tempTsk = new Task__c();
            //if(Trigger.isInsert){空更新数据
            tempTsk.Id = tsk.Id;
            tempTsk.Task_After_3_WorkDay__c = dt;
            TaskOlyUpdate.add(tempTsk);
            System.debug(LoggingLevel.INFO, '*** 任务奥林巴斯赋值: ' + tsk.Task_After_3_WorkDay__c);
            //}else{
            //tsk.Task_After_3_WorkDay__c = dt;
            //}
        }
        if(TaskOlyUpdate.size()>0){
          update TaskOlyUpdate;
        }
            
    }    
    //20220720 you 中标任务 you end

}