public without sharing class TenderOpportunityLinkHandler extends Oly_TriggerHandler {
private Map<Id, Tender_Opportunity_Link__c> newMap;
private Map<Id, Tender_Opportunity_Link__c> oldMap;
private List<Tender_Opportunity_Link__c> newList;
private List<Tender_Opportunity_Link__c> oldList;

public TenderOpportunityLinkHandler() {
    this.newMap = (Map<Id, Tender_Opportunity_Link__c>) Trigger.newMap;
    this.oldMap = (Map<Id, Tender_Opportunity_Link__c>) Trigger.oldMap;
    this.newList = (List<Tender_Opportunity_Link__c>) Trigger.new;
    this.oldList = (List<Tender_Opportunity_Link__c>) Trigger.old;
}
 
protected override void afterInsert() {
    // 判断是否跳过
    updateTerminateTender(this.newList);  //lt 20230419 项目终止流程开发 add
    if (!StaticParameter.EscapeTOLinkTrigger) {
        updateTender(this.newList);
        updateOppotunityByInsert(this.newList);      
    }
}

protected override void afterDelete() {
    // 判断是否跳过
    if (!StaticParameter.EscapeTOLinkTrigger) {
        updateTender(this.oldList);
        updateOppotunityByDelete(this.oldList);
    }
}
protected override void beforeDelete() {
    // 判断是否跳过
    if (!StaticParameter.EscapeTOLinkTrigger) {
        updateOppotunityBeforeDelete(this.oldList);
    }
}

protected override void beforeInsert() {
    if (this.newList != null && this.newList.size() > 0) {
        for (Tender_Opportunity_Link__c link : this.newList) {
            if (link.Tender_Opportunity_Uniq__c == null || link.Tender_Opportunity_Uniq__c == '') {
                link.Tender_Opportunity_Uniq__c = link.Tender_information__c + '' + link.Opportunity__c;
            }
        }
    }
}
//DB202306372336  you start
public void UpdateStrategic_department_Opp(List<Tender_Opportunity_Link__c> tenderList,List<Tender_information__c> UpdateTenders){
    Map<String, Set<String>> updateTenMap = new Map<String, Set<String>>();//招标项目id，战略科室分类
    //String partment_Opp='';
        if(tenderList.size() > 0){
            for (Tender_Opportunity_Link__c tender : tenderList){
                 if(String.isNotBlank(tender.Opportunity__r.Department_Class__r.Department_Class_Label__c)){
                    //String ten_Opp =tender.Opportunity__r.Department_Class__r.name.split(' ')[1];
                    //if(tender.Opportunity__r.Department_Class__r.name.split(' ').size() ==3 ){
                    //   ten_Opp =tender.Opportunity__r.Department_Class__r.name.split(' ')[2];
                    //}
                    String ten_Opp =tender.Opportunity__r.Department_Class__r.Department_Class_Label__c;
                    Set<String> temp = new Set<String>();
                    if(ten_Opp.indexOf('其他') == -1){
                        if(updateTenMap.containsKey(tender.Tender_information__c)){
                            temp= updateTenMap.get(tender.Tender_information__c);
                            temp.add(ten_Opp);
                        } else{
                            temp.add(ten_Opp);
                        }
                    }else{//其他归普外
                        if(updateTenMap.containsKey(tender.Tender_information__c)){
                            temp= updateTenMap.get(tender.Tender_information__c);
                            temp.add('普外科');
                        } else{
                            temp.add('普外科');
                        }
                    }
                    updateTenMap.put(tender.Tender_information__c,temp);  
                    system.debug(tender.Opportunity__r.Department_Class__r.Department_Class_Label__c+'==temp=='+temp);
                }
                
            }

            if(null!=updateTenMap && updateTenMap.size()>0){
                 for(String ksy :updateTenMap.keySet()){
                    String partment_Opp=String.join(new List<String>(updateTenMap.get(ksy)), ';'); 
                    system.debug('=====partment_Opp='+partment_Opp); 
                    partment_Opp=partment_Opp.replaceAll(',', ';');
                    if(null ==UpdateTenders || UpdateTenders.size()==0){
                      Tender_information__c tin1 =new Tender_information__c();
                      tin1.id=ksy;
                      tin1.Strategic_department_Opp__c = partment_Opp;
                      UpdateTenders.add(tin1);
                    }else{
                      for (Tender_information__c up : UpdateTenders){
                        if(up.id== ksy){
                           up.Strategic_department_Opp__c = partment_Opp; 
                        }else{
                          Tender_information__c tin2 =new Tender_information__c();
                          tin2.id=ksy;
                          tin2.Strategic_department_Opp__c = partment_Opp;
                          UpdateTenders.add(tin2); 
                        }

                      }
                    }

                 }
                }
        }



        //if(tenderList.size() > 0){
        //    for (Tender_Opportunity_Link__c tender : tenderList){ 
        //       if(String.isNotBlank(partment_Opp)){
        //           partment_Opp.substring(0, partment_Opp.length()-1);
        //           if(null ==UpdateTenders || UpdateTenders.size()==0){
        //              Tender_information__c tin1 =new Tender_information__c();
        //              tin1.id=tender.Tender_information__c;
        //              tin1.Strategic_department_Opp__c = partment_Opp;
        //              UpdateTenders.add(tin1);
        //           }else{
        //              for (Tender_information__c up : UpdateTenders){
        //                if(up.id== tender.Tender_information__c){
        //                   up.Strategic_department_Opp__c = partment_Opp; 
        //                }else{
        //                  Tender_information__c tin2 =new Tender_information__c();
        //                  tin2.id=tender.Tender_information__c;
        //                  tin2.Strategic_department_Opp__c = partment_Opp;
        //                  UpdateTenders.add(tin2); 
        //                }

        //              }
        //           }
        //        }
        //    }
        //}
}    
 //DB202306372336  you end
//lt 20230419 项目终止流程开发 终止申请状态清除 add
//项目终止流程开发 -- 清除招标项目终止申请的信息，项目重启标识打勾
public void updateTerminateTender(List<Tender_Opportunity_Link__c> records){
    if (records != null && records.size() > 0){
        List<String> tenders = new List<String>();//DB202305552102 you 关联取消的询价 项目不重启  取一条link
        List<String> tenlinks = new List<String>();//DB202306372336  you start  取当前招标下所有link
        Set<Id> oppIdSet = new Set<Id>(); //DB202307367354 lt 【招标项目】漏单计算逻辑修改 20231115 add

        // 获得要更新的招标项目
        for (Tender_Opportunity_Link__c record: records) {
            String lhid=record.Tender_information__c+''+record.Opportunity__c;
            if (!tenders.contains(lhid)) {
                tenders.add(lhid);
            }
            //DB202306372336  you start
            if(!tenlinks.contains(record.Tender_information__c)){
                tenlinks.add(record.Tender_information__c);
            }
            //DB202306372336  you end

            //DB202307367354 lt 【招标项目】漏单计算逻辑修改 20231115 start
            oppIdSet.add(record.Opportunity__c);
            //DB202307367354 lt 【招标项目】漏单计算逻辑修改 20231115 end

            /**
             if (!tenders.contains(record.Tender_information__c)) {
                tenders.add(record.Tender_information__c);
            }
            **/
        }

        //DB202307367354 lt 【招标项目】漏单计算逻辑修改 20231115 start
        if(oppIdSet.Size() > 0){
            TenderUtil.UpdLeakageNum(oppIdSet);
        }
        //DB202307367354 lt 【招标项目】漏单计算逻辑修改 20231115 end
        
        /**
        List<Tender_information__c> UpdateTenders = new List<Tender_information__c>();
        if (tenders.size() > 0){
            List<Tender_information__c> tenderList = [SELECT id, status__c, TerminateReason__c, IsTerminate__c,
                                                             TerminateApprovalStatus__c, TerminateApprovalTime__c,
                                                             ProjectRestartFLG__c,subInfoType__c
                                                      FROM Tender_information__c 
                                                      WHERE id in :tenders];

            if(tenderList.size() > 0){
                for (Tender_information__c tender : tenderList){
                    //if(tender.status__c == '09.终止' && tender.TerminateReason__c != '经销商原因' && tender.subInfoType__c != '3-1：废标公告' && tender.subInfoType__c != '3-2：流标公告')
                    if(tender.status__c == '09.终止'){
                        tender.ProjectRestartFLG__c = true;
                        tender.IsTerminate__c = null;
                        tender.TerminateApprovalTime__c = null;
                        tender.TerminateApprovalStatus__c = null;
    
                        UpdateTenders.add(tender);
                    }
                }
            }
        }
        **/
        //DB202305552102 you start
        List<Tender_information__c> UpdateTenders = new List<Tender_information__c>();
        List<Tender_Opportunity_Link__c> tolList = new List<Tender_Opportunity_Link__c>();
        if (tenders.size() > 0) {
           tolList =  [select id, Opportunity__r.stagename,Opportunity__r.Department_Class__r.Department_Class_Label__c, Tender_information__c,Tender_information__r.status__c,Tender_information__r.ProjectRestartFLG__c,Tender_information__r.IsTerminate__c,Tender_information__r.TerminateApprovalTime__c,Tender_information__r.TerminateApprovalStatus__c from Tender_Opportunity_Link__c where Tender_Opportunity_Uniq__c in :tenders];
        }  
        if(tolList.size() > 0){
                for (Tender_Opportunity_Link__c tender : tolList){
                    system.debug(tenders+'======='+tender.Tender_information__r.status__c+'=====终止===='+tender.Opportunity__r.stagename);
                    if(tender.Tender_information__r.status__c == '09.终止' && tender.Opportunity__r.stagename !='削除'){
                        Tender_information__c tin =new Tender_information__c();
                        tin.id=tender.Tender_information__c;
                        tin.ProjectRestartFLG__c = true;
                        tin.IsTerminate__c = null;
                        tin.TerminateApprovalTime__c = null;
                        tin.TerminateApprovalStatus__c = null;
                        UpdateTenders.add(tin);

                    }
                    
                }
        }    
        //DB202305552102 you end
        //DB202306372336  you start
        List<Tender_Opportunity_Link__c> tenderList = new List<Tender_Opportunity_Link__c>();
        if (tenlinks.size() > 0){
            tenderList = [SELECT id, Opportunity__r.Department_Class__r.Department_Class_Label__c,Tender_information__c
                                                      FROM Tender_Opportunity_Link__c 
                                                      WHERE Tender_information__c in :tenlinks];
        }
        if(tenderList.size() > 0){
          UpdateStrategic_department_Opp(tenderList,UpdateTenders);
        }
        system.debug('==需要更新的==='+UpdateTenders);        
        //DB202306372336  you end
        if(UpdateTenders.size() > 0){
            StaticParameter.EscapeTenderInformationUpdate =false;
            update UpdateTenders;
            StaticParameter.EscapeTenderInformationUpdate =true;
        }
    }
}

// 更新招标信息
public void updateTender(List<Tender_Opportunity_Link__c> records) {
    if (records != null && records.size() > 0) {
        List<String> tenders = new List<String>();
        // 获得要更新的招标项目
        for (Tender_Opportunity_Link__c record: records) {
            if (!tenders.contains(record.Tender_information__c)) {
                tenders.add(record.Tender_information__c);
            }
        }
        if (tenders.size() > 0) {
            List<Tender_information__c> tender_list = [select id, OpportunityNum__c, RelateOppTime__c, IsRelateProject__c, Hospital__c, Hospital1__c, Hospital2__c, Hospital3__c, Hospital4__c, OwnerId, NotBidApprovalStatus__c from Tender_information__c where id in :tenders];
            if (tender_list != null && tender_list.size() > 0) {
            
                // 不应标申请中的时候 调回申请修改 20210907 start
                List<Id> approval_tenders = new List<Id>();
                    for (Tender_information__c tender : tender_list) {
                        if (tender.NotBidApprovalStatus__c != null && tender.NotBidApprovalStatus__c == '申请中') {
                            approval_tenders.add(tender.Id);
                        }
                    }
                    if (approval_tenders.size() > 0) {
                        List<Approval.ProcessWorkitemRequest> requests = new List<Approval.ProcessWorkitemRequest> ();
                        List<ProcessInstance> pis = [Select Id, SubmittedById, TargetObjectId from ProcessInstance where TargetObjectId in :approval_tenders and Status = 'Pending'];
                        if (pis != null && pis.size() > 0) {
                            List<Id> pi_ids = new List<Id>();
                            for (ProcessInstance pi : pis) {
                                pi_ids.add(pi.Id);
                            }
                            for(ProcessInstanceWorkItem wi : [Select Id, ProcessInstanceId from ProcessInstanceWorkItem where ProcessInstanceId IN :pi_ids]){
                                Approval.ProcessWorkitemRequest req2 = new Approval.ProcessWorkitemRequest();
                                for (ProcessInstance pi : pis) {
                                    if (pi.Id.equals(wi.ProcessInstanceId)) {
                                        for (Tender_information__c tender : tender_list) {
                                            if (tender.Id.equals(pi.TargetObjectId)) {
                                                if (pi.SubmittedById.equals(Userinfo.getUserId())) {
                                                    req2.setAction('Removed');
                                                    tender.NotBidApprovalStatus__c = '草案中';
                                                  } else {
                                                    req2.setAction('Reject');
                                                    tender.NotBidApprovalStatus__c = '驳回';
                                                    tender.IsBid__c = null;
                                                  }
                                                break;
                                            }
                                        }
                                        break;
                                    }
                                }
                                req2.setWorkitemId(wi.Id);
                                requests.add(req2);
                            }
                            system.debug('==requests.size()=='+requests.size());
                            if (requests.size() > 0) {
                                Approval.ProcessResult[] processResults = null;
                                processResults = Approval.process(requests, true);
                                system.debug('==调回结果=='+processResults);
                            }
                        }
                    }
                // 不应标申请中的时候 调回申请修改 20210907 end
                
                // 更新招标项目的阶段、关联询价时间和关联医院
                List<AggregateResult> sum_list = [select count(id) cnt, Tender_information__c from Tender_Opportunity_Link__c where Tender_information__c in :tenders group by Tender_information__c];
                Map<String, Integer> sum_map = new Map<String, Integer>();
                if (sum_list != null && sum_list.size() > 0) {
                    for (AggregateResult result : sum_list) {
                        sum_map.put(String.valueOf(result.get('Tender_information__c')), Integer.valueOf(result.get('cnt')));
                    }
                }
                // 仅新增关联询价时判断是否要写入医院
                List<Tender_Opportunity_Link__c> links = null;
                if (Trigger.isAfter && Trigger.isInsert) {
                    links = [select id, Tender_information__c, Opportunity__c, Opportunity__r.Hospital__c, Opportunity__r.OwnerId from Tender_Opportunity_Link__c where Tender_information__c in :tenders];
                }
                for (Tender_information__c tender : tender_list) {
                    // 新增或删除关联时，要写入反映询价标签
                    tender.IsReactionOpp__c = true;
                    // 写入/清空关联询价时间和是否相关状态
                    tender.OpportunityNum__c = sum_map.get(tender.id) != null ? sum_map.get(tender.id) : 0;
                    if (tender.IsRelateProject__c != '是') {
                        tender.IsRelateProject__c = '是';
                        tender.RelateOppTime__c = datetime.now();
                        tender.irrelevantReasons__c = null;
                        tender.irrelevantReasonOther__c = null;
                    } else if (tender.OpportunityNum__c == 0) {
                        tender.RelateOppTime__c = null;
                        // tender.IsRelateProject__c = null;
                    }
                    if (Trigger.isAfter && Trigger.isInsert && links != null && links.size() > 0) {
                        system.debug('links等于【'+links+'】结束'+links.size());
                        // 招标项目的医院
                        Map<String,String> fiveHospitalMap = new Map<String,String>();
                        fiveHospitalMap.put('Hospital__c', tender.Hospital__c);
                        fiveHospitalMap.put('Hospital1__c', tender.Hospital1__c);
                        fiveHospitalMap.put('Hospital2__c', tender.Hospital2__c);
                        fiveHospitalMap.put('Hospital3__c', tender.Hospital3__c);
                        fiveHospitalMap.put('Hospital4__c', tender.Hospital4__c);
                        // 整理所有的所有人
                        List<String> owners = new List<String>();
                        for (Tender_Opportunity_Link__c link : links) {
                            owners.add(link.Opportunity__r.OwnerId);
                        }
                        for(Integer i = 0; i < links.size(); i++) {
                            // 不是同一个招标项目的跳过
                            if (!tender.Id.equals(links.get(i).Tender_information__c)) {
                                continue;
                            }
                            // 新增时还要判断所有人问题
                            if (tender.OwnerId == null || System.label.tender_3.equals(tender.OwnerId) || (owners.size() > 0 && !owners.contains(tender.OwnerId))) {
                                tender.OwnerId = links.get(i).Opportunity__r.OwnerId;
                            }
                            //当招投标项目的五个医院赋值完成后不再赋值
                            Boolean HospitalIsNeedBreak = false;
                            for(String ApiName :fiveHospitalMap.keySet()) {
                                HospitalIsNeedBreak = fiveHospitalMap.get(ApiName)==null?false:true;
                            }
                            if(HospitalIsNeedBreak) {
                                break;
                            }
                            //给招投标项目的5个医院设值
                            for(String ApiName : fiveHospitalMap.keySet()) {
                                String tempTenderHospId = fiveHospitalMap.get(ApiName)==null?'':fiveHospitalMap.get(ApiName);
                                String oppHospId = links.get(i).Opportunity__r.Hospital__c;
                                //如果招标项目已经有该医院就判断下一个询价的医院
                                system.debug('tempTenderHospId等于【'+tempTenderHospId+'】结束');
                                system.debug('oppHospId等于【'+oppHospId+'】结束');
                                if(tempTenderHospId.contains(oppHospId)) {
                                    break;
                                }

                                //医院为空,赋值医院(赋值之后进行赋值下一个医院)
                                if(fiveHospitalMap.get(ApiName) == null || String.isBlank( fiveHospitalMap.get(ApiName) )) {
                                    fiveHospitalMap.put(ApiName,oppHospId);
                                    break;
                                }
                            }
                        }
                        tender.Hospital__c = fiveHospitalMap.get('Hospital__c');
                        tender.Hospital1__c = fiveHospitalMap.get('Hospital1__c');
                        tender.Hospital2__c = fiveHospitalMap.get('Hospital2__c');
                        tender.Hospital3__c = fiveHospitalMap.get('Hospital3__c');
                        tender.Hospital4__c = fiveHospitalMap.get('Hospital4__c');
                    }
                }
                StaticParameter.EscapeTenderInformationUpdate = false;
                if (Trigger.isAfter && Trigger.isDelete) {   
                    StaticParameter.EscapeOtherUpdateTenOwner = false;
                    update tender_list;
                    StaticParameter.EscapeOtherUpdateTenOwner = true;                    
                } else {
                    update tender_list;
                }
                StaticParameter.EscapeTenderInformationUpdate = true;
            }
        }
    }
}

// 更新询价信息
public void updateOppotunityByInsert(List<Tender_Opportunity_Link__c> records) {   
    if (records != null && records.size() > 0) {
        List<String> oppIds = new List<String>();
        Set<Id> oppIdsSet = new Set<Id>();// 20221028 ljh SWAG-CKL5UC
        //SWAG-CHL67J 【委托】【FY23询价改善】-询价页面/招标项目增加统计字段 fy start 
        // List<String> TenderIds = new List<String>();
        //SWAG-CHL67J 【委托】【FY23询价改善】-询价页面/招标项目增加统计字段 fy end
        // 获得要更新的询价
        for (Tender_Opportunity_Link__c record: records) {
            if (!oppIds.contains(record.Opportunity__c)) {
                oppIds.add(record.Opportunity__c);
                // 20221028 ljh SWAG-CKL5UC add start
                system.debug('zheli00:'+record.IsLeakage__c);
                system.debug('zheli00:'+record.IsLeakage_New__c);
                if(record.IsLeakage_New__c){   //DB202307367354 lt 【招标项目】漏单计算逻辑修改 20231115 update  IsLeakage__c-->IsLeakage_New__c  
                    oppIdsSet.add(record.Opportunity__c);
                }
                // 20221028 ljh SWAG-CKL5UC add end
            }
            //SWAG-CHL67J 【委托】【FY23询价改善】-询价页面/招标项目增加统计字段 fy start 
            // if (!TenderIds.contains(record.Tender_information__c)) {
            //     TenderIds.add(record.Tender_information__c);
            // }
            //SWAG-CHL67J 【委托】【FY23询价改善】-询价页面/招标项目增加统计字段 fy end
            
        }
        if (oppIds.size() > 0) {
            List<String> tenIds = new List<String>();//20220715 you 招标项目插入时，是否需要发送询价任务 新的招标项目
            //20220615 you SWAG-CFD4SU 改造 start 始终显示最新的 ① 3：结果,② 4：变更,③ 2：公告,④ 1：预告,⑤ 5：其他 
            // 20221028 ljh SWAG-CKL5UC 查询增加 LeakageNumber__c  , TenderBeginDate_Text__c
            //20231218 lt add DB202311665664 【重要紧急课题】询价中的“项目：招标日”和漏单数修改 - 查询增加,TenderBeginDate_New__c
            List<Opportunity> opportunities = [select id,Tender_Number__c, Bidding_Project_Name_Bid__c, Bidding_Project_Name_Bid__r.InfoType__c, InfoTypeBid_text__c,Opp_Order__c,LeakageNumber__c,TenderBeginDate_New__c from Opportunity where id in :oppIds ];//and Bidding_Project_Name_Bid__r.InfoType__c != '3：结果'];
            if (opportunities.size() > 0) {
                List<Tender_Opportunity_Link__c> links = [select id, Opportunity__c, Tender_information__c, Tender_information__r.InfoType__c, Tender_information__r.TenderBeginTime__c,Tender_information__r.TenderDate__c,Tender_information__r.Tender_Order__c,Tender_information__r.subInfoType__c from Tender_Opportunity_Link__c where Opportunity__c in :oppIds order by Opportunity__c,Tender_information__r.Tender_Order__c desc, Tender_information__r.relativeTime_F__c desc];
                for (Opportunity opp : opportunities) {
                    for (Tender_Opportunity_Link__c link : links) {
                        boolean defaultFlag = false;
                        if (opp.Id.equals(link.Opportunity__c)) {
                            /**
                             if (opp.Bidding_Project_Name_Bid__c == null || ''.equals(opp.Bidding_Project_Name_Bid__c)) {
                                opp.Bidding_Project_Name_Bid__c = link.Tender_information__c;
                                opp.TenderBeginDate_Text__c = link.Tender_information__r.TenderBeginTime__c;
                                opp.InfoTypeBid_text__c = link.Tender_information__r.InfoType__c;
                            }
                            
                            if ('3：结果'.equals(link.Tender_information__r.InfoType__c)) {
                                opp.Bidding_Project_Name_Bid__c = link.Tender_information__c;
                                if (opp.TenderBeginDate_Text__c == null) {
                                    opp.TenderBeginDate_Text__c = link.Tender_information__r.TenderBeginTime__c;
                                }
                                if (opp.InfoTypeBid_text__c == null) {
                                    opp.InfoTypeBid_text__c = link.Tender_information__r.InfoType__c;
                                }
                                break;
                            }
                            **/

                            if(opp.Opp_Order__c <= link.Tender_information__r.Tender_Order__c){
                              opp.Bidding_Project_Name_Bid__c = link.Tender_information__c;
                              //opp.TenderBeginDate_Text__c =  link.Tender_information__r.TenderDate__c;//更改询价状态2时，引用超20，link.Tender_information__r.TenderBeginTime__c;
                              opp.InfoTypeBid_text__c = link.Tender_information__r.InfoType__c;
                              //20220715 you 招标项目 start
                              if(String.isNotBlank(link.Tender_information__r.InfoType__c) && link.Tender_information__r.InfoType__c=='3：结果' && String.isNotBlank(link.Tender_information__r.subInfoType__c) && (link.Tender_information__r.subInfoType__c=='3-5：中标通知' || link.Tender_information__r.subInfoType__c=='3-6：合同公告')){
                                tenIds.add(link.Opportunity__c); //符合条件生成任务
                              }
                              //20220715 you 招标项目 end
                              break;
                            }

                        }
                    }
                    //20220829 you SWAG-CHL67J start
                    Integer returncount =0;
                     for (Tender_Opportunity_Link__c link : links) {
                        if (opp.Id.equals(link.Opportunity__c)) {
                            //20231218 lt DB202311665664 【重要紧急课题】询价中的“项目：招标日”和漏单数修改 start
                            System.debug('lt123---opp.TenderBeginDate_New__c'+String.valueOf(opp.TenderBeginDate_New__c));
                            if(String.isNotBlank(String.valueOf(opp.TenderBeginDate_New__c))){
                                if(opp.TenderBeginDate_New__c > link.Tender_information__r.TenderDate__c){
                                    opp.TenderBeginDate_New__c = link.Tender_information__r.TenderDate__c;
                                }
                            }else{
                                opp.TenderBeginDate_New__c = link.Tender_information__r.TenderDate__c;
                            }
                            //20231218 lt DB202311665664 【重要紧急课题】询价中的“项目：招标日”和漏单数修改 end

                            if(String.isNotBlank(link.Tender_information__r.InfoType__c) && link.Tender_information__r.InfoType__c!='1：预告' && String.isNotBlank(link.Tender_information__r.subInfoType__c) && link.Tender_information__r.subInfoType__c!='3-1：废标公告' && link.Tender_information__r.subInfoType__c!='3-2：流标公告'){
                                system.debug('test1进来了');
                                  returncount += 1;
                              }
                        }
                    }
                    opp.Tender_Number__c =returncount;
                    //20220829 you SWAG-CHL67J end
                    // 20221028 ljh SWAG-CKL5UC add start
                    if(oppIdsSet.contains(opp.Id) && opp.LeakageNumber__c != 1){
                        opp.LeakageNumber__c = 1;
                    }
                    // 20221028 ljh SWAG-CKL5UC add end                    
                }
                update opportunities;
            }
            //20220615 you SWAG-CFD4SU 改造 end
            //20220715 you 招标任务 start
                             
            if (tenIds !=null && tenIds.size() > 0) {
              Database.executeBatch(new TenderResultConfirmTaskBatch(tenIds));
            }
            //20220715 you 招标任务 end
        }
        //SWAG-CHL67J 【委托】【FY23询价改善】-询价页面/招标项目增加统计字段 fy start 
        // if (TenderIds.size() > 0) {
        //     updateTender(TenderIds);
        // }
        //SWAG-CHL67J 【委托】【FY23询价改善】-询价页面/招标项目增加统计字段 fy end
    }
}

//SWAG-CHL67J 【委托】【FY23询价改善】-询价页面/招标项目增加统计字段 fy start 
//跟新招标项目的中标数和应标数
// public void updateTender(List<String> TenderIds) {
//     List<Tender_Opportunity_Link__c> TenderOpportunityLinkList2 = [select Tender_information__c,Opportunity__r.NumberOfBids__c,Opportunity__r.BidWinningNumber__c from Tender_Opportunity_Link__c where Tender_information__c in:TenderIds];
//     Map<String,Tender_information__c> TenderinformationMap = new Map<String,Tender_information__c>();
//     if(TenderOpportunityLinkList2.size()>0){
//         for(Tender_Opportunity_Link__c TenderOpportunity2 :TenderOpportunityLinkList2){
//             if(TenderinformationMap.containsKey(TenderOpportunity2.Tender_information__c)){
//                 Tender_information__c Tender_informationvalue = new Tender_information__c();
//                 Tender_informationvalue = TenderinformationMap.get(TenderOpportunity2.Tender_information__c);
//                 Tender_informationvalue.NumberOfBids__c=Tender_informationvalue.NumberOfBids__c+TenderOpportunity2.Opportunity__r.NumberOfBids__c;
//                 Tender_informationvalue.BidWinningNumber__c=Tender_informationvalue.BidWinningNumber__c+TenderOpportunity2.Opportunity__r.BidWinningNumber__c;
//                 TenderinformationMap.put(TenderOpportunity2.Tender_information__c, Tender_informationvalue);
//             }else{
//                 Tender_information__c Tender_informationvalue = new Tender_information__c();
//                 Tender_informationvalue.Id=TenderOpportunity2.Tender_information__c;
//                 Tender_informationvalue.NumberOfBids__c=TenderOpportunity2.Opportunity__r.NumberOfBids__c;
//                 Tender_informationvalue.BidWinningNumber__c=TenderOpportunity2.Opportunity__r.BidWinningNumber__c;
//                 TenderinformationMap.put(TenderOpportunity2.Tender_information__c, Tender_informationvalue);
//             }
//         }
//     }
//     if(TenderinformationMap.size()>0){
//         List<Tender_information__c> Tender_informationList = new List<Tender_information__c>();
//         for (Tender_information__c value : TenderinformationMap.values()) {
//             Tender_informationList.add(value);
//         }
//         update Tender_informationList;
//     }
// }
//SWAG-CHL67J 【委托】【FY23询价改善】-询价页面/招标项目增加统计字段 fy end 
//20220718 you 询价任务 start
//删除link时，任务取消，清空询价中标信息
public void updateOppotunityBeforeDelete(List<Tender_Opportunity_Link__c> records) {
    //DB202306372336  you start 
    List<String> tenlinks = new List<String>();// 取当前招标下所有link
    List<String> tenlink = new List<String>();// 取当前删除的link
    if (records != null && records.size() > 0) {
       for (Tender_Opportunity_Link__c record: records) {
           if(!tenlinks.contains(record.Tender_information__c)){
                tenlinks.add(record.Tender_information__c);
            }  
            if(!tenlink.contains(record.id)){
                tenlink.add(record.id);
            } 
       } 
    }  
    List<Tender_information__c> UpdateTenders = new List<Tender_information__c>();  
    List<Tender_Opportunity_Link__c> tenderList = new List<Tender_Opportunity_Link__c>();
    if (tenlinks.size() > 0){
        tenderList = [SELECT id, Opportunity__r.Department_Class__r.Department_Class_Label__c,Tender_information__c
                                                  FROM Tender_Opportunity_Link__c 
                                                  WHERE Tender_information__c in :tenlinks and id not in :tenlink];
     }
    
    if(tenderList.size() > 0){
       UpdateStrategic_department_Opp(tenderList,UpdateTenders);
     } else{
        //删除招标项目最后一条link
        List<Tender_Opportunity_Link__c> tenderList1 = [SELECT id, Opportunity__r.Department_Class__r.Department_Class_Label__c,Tender_information__c
                                                  FROM Tender_Opportunity_Link__c 
                                                  WHERE id in :tenlink];
        system.debug(tenderList1.size()+'==当前删除得link=='+tenlink);
        if(null!=tenderList1 && tenderList1.size()>0){
            for(Tender_Opportunity_Link__c ti :tenderList1){
                  Tender_information__c tin1 =new Tender_information__c();
                  tin1.id=ti.Tender_information__c;
                  tin1.Strategic_department_Opp__c = '';
                  system.debug('删除进来了');
                  UpdateTenders.add(tin1); 
            }
         
        }                                          
        
     }
     system.debug('=====UpdateTenders====='+UpdateTenders);
    if(UpdateTenders.size() > 0){
       StaticParameter.EscapeTenderInformationUpdate =false;
       update UpdateTenders;
       StaticParameter.EscapeTenderInformationUpdate =true;
    }   
    
//DB202306372336  you end 



    if (records != null && records.size() > 0) {
        Set<String> oppTens = new Set<String>();//询价，招标项目 拼接
        List<String> oppIds = new List<String>();
        // 获得要更新的询价
        for (Tender_Opportunity_Link__c record: records) {
            String oppid =String.valueOf(record.Opportunity__c);
            String tenid =String.valueOf(record.Tender_information__c);
            oppTens.add(oppid.subString(0,15)+tenid.subString(0,15));
           if (!oppIds.contains(record.Opportunity__c)) {
                oppIds.add(record.Opportunity__c);
            }
        }
        if (null!=oppTens && oppTens.size()>0) {
          //20221208 you DB202211594688 有确认任务的询价不清空中标信息 taskStatus__c <> '完成'
          //,TenderBeginDate_New__c add lt DB202311665664  【重要紧急课题】询价中的“项目：招标日”和漏单数修改
          List<Opportunity> opportunities = [select id, Bidding_Project_Name_Bid__c,Opp_Order__c,TenderBeginDate_New__c from Opportunity where id in :oppIds];
           List<task__c> taskList = [select id,taskStatus__c,RecordType.Name,Tender_information_Task__c,OpportunityId__c from task__c where ((RecordType.Name ='失单报告任务' and OpportunityId__c in:oppIds) or (RecordType.Name ='中标结果确认' and Opp_Tender__c in :oppTens)) and taskStatus__c <> '03 完成'];
            for(task__c tsk : taskList){
                if(tsk.RecordType.Name =='失单报告任务' && oppIds.contains(tsk.OpportunityId__c) && tsk.taskStatus__c !='03 完成'){
                  //不做操作
                }else{
                  tsk.taskStatus__c = '04 取消';
                  tsk.cancelDate__c = date.today();
                  tsk.cancelReasonSelect__c = '取消询价关联';  
                }
                
            }
             update taskList;
            if(taskList.size() > 0){
                for (task__c tlink : taskList) {
                    for (Opportunity opp : opportunities) {
                        if (opp.Id == tlink.OpportunityId__c) {
                            if(tlink.RecordType.Name =='失单报告任务' && tlink.taskStatus__c !='03 完成'){
                              //不做操作
                            }else{
                                //20220718 you 询价任务 start
                                opp.ConfirmationofAward__c = null;
                                opp.Task_createTime__c = null;
                                opp.ConfirmationofAward_createTime__c =null;
                                opp.LostTask_comfirmTime__c =null;
                                opp.Is_ConfirmationofAward__c =null;
                                opp.LostTask_createTime__c =null;
                                //opp.Closing_Bid_Date__c = null;
                                //20220718 you 询价任务 end
                            }
                       }  
                    }
                }
            } 
            update opportunities;   
        }
            
    }
}    
//20220718 you 询价任务 end

// 更新询价信息
public void updateOppotunityByDelete(List<Tender_Opportunity_Link__c> records) {
    Set<Id> oppIdSet = new Set<Id>(); //DB202307367354 lt 【招标项目】漏单计算逻辑修改 20231115 add
    
    if (records != null && records.size() > 0) {
        List<String> oppIds = new List<String>();
        //SWAG-CHL67J 【委托】【FY23询价改善】-询价页面/招标项目增加统计字段 fy start 
        // List<String> TenderIds = new List<String>();
        //SWAG-CHL67J 【委托】【FY23询价改善】-询价页面/招标项目增加统计字段 fy end
        // 获得要更新的询价
        for (Tender_Opportunity_Link__c record: records) {
            if (!oppIds.contains(record.Opportunity__c)) {
                oppIds.add(record.Opportunity__c);
            }
            //SWAG-CHL67J 【委托】【FY23询价改善】-询价页面/招标项目增加统计字段 fy start 
            // if (!TenderIds.contains(record.Tender_information__c)) {
            //     TenderIds.add(record.Tender_information__c);
            // }
            //SWAG-CHL67J 【委托】【FY23询价改善】-询价页面/招标项目增加统计字段 fy end

        }
        if (oppIds.size() > 0) {
            List<String> tenIds = new List<String>();//20220715 you 招标项目插入时，是否需要发送询价任务 新的招标项目
            //20220615 you SWAG-CFD4SU 改造 增加查询条件
            //lt 20231116 lt 漏单 add DirectLossFLG__c 
            //,TenderBeginDate_New__c add lt DB202311665664  【重要紧急课题】询价中的“项目：招标日”和漏单数修改
            List<Opportunity> opportunities = [select id, Bidding_Project_Name_Bid__c,Tender_Number__c,Opp_Order__c,DirectLossFLG__c,TenderBeginDate_New__c from Opportunity where id in :oppIds];
            
            if (opportunities.size() > 0) {
                //20220615 you SWAG-CFD4SU 改造 增加查询条件
                //DB202311665664  【重要紧急课题】询价中的“项目：招标日”和漏单数修改 lt add ,Opportunity__r.TenderBeginDate_New__c
                List<Tender_Opportunity_Link__c> links = [select id, Opportunity__c, Tender_information__c, Tender_information__r.InfoType__c,Tender_information__r.subInfoType__c,Tender_information__r.Tender_Order__c,Tender_information__r.TenderBeginTime__c,Tender_information__r.TenderDate__c,Opportunity__r.TenderBeginDate_New__c from Tender_Opportunity_Link__c where Opportunity__c in :oppIds order by Opportunity__c,Tender_information__r.Tender_Order__c desc, Tender_information__r.relativeTime_F__c desc];
                List<AggregateResult> sum_list = [select count(id) cnt, Opportunity__c from Tender_Opportunity_Link__c where Opportunity__c in :oppIds group by Opportunity__c];
                Map<String, Integer> sum_map = new Map<String, Integer>();
               
                if (sum_list != null && sum_list.size() > 0) {
                    for (AggregateResult result : sum_list) {
                        sum_map.put(String.valueOf(result.get('Opportunity__c')), Integer.valueOf(result.get('cnt')));
                    }
                }
                for (Opportunity opp : opportunities) {
                    if (sum_map.get(opp.Id) == null || sum_map.get(opp.Id) == 0) {
                        opp.Bidding_Project_Name_Bid__c = null;
                        //opp.TenderBeginDate_Text__c = null;
                        opp.InfoTypeBid_text__c = null;
                        /** 20221208 you DB202211594688 无任务询价，不清空招标信息
                        //20220718 you 询价任务 start
                        opp.ConfirmationofAward__c = null;
                        opp.Task_createTime__c = null;
                        opp.ConfirmationofAward_createTime__c =null;
                        opp.LostTask_comfirmTime__c =null;
                        opp.Is_ConfirmationofAward__c =null;
                        opp.Closing_Bid_Date__c = null;
                        //20220718 you 询价任务 end
                        **/
                        // 20221028 ljh SWAG-CKL5UC start
                        //1.SWAG-CKL5UC add
                        //2.DB202306421819 注释
                        //3.DB202307367354 取消注释增加条件 lt 20231115 -- 删除link漏单清空（删没了）
                        // if(!opp.DirectLossFLG__c){  //2023-11-22 需求，取消看直接失单
                            opp.LeakageNumber__c = null;  //lt 20230625 DB202306421819 【BUG】漏单数有误 update
                        // }
                        // 20221028 ljh SWAG-CKL5UC end

                           opp.TenderBeginDate_New__c = null; //20231218 lt DB202311665664 【重要紧急课题】询价中的“项目：招标日”和漏单数修改 add
                    } else {
                        for (Tender_Opportunity_Link__c link : links) {
                            if (opp.Id == link.Opportunity__c) {
                                //20220615 you SWAG-CFD4SU 改造 start 
                                /** 
                                opp.Bidding_Project_Name_Bid__c = link.Tender_information__c;
                                if ('3：结果'.equals(link.Tender_information__r.InfoType__c)) {
                                    opp.Bidding_Project_Name_Bid__c = link.Tender_information__c;
                                    break;
                                }
                                **/

                                //records[0].addError(opp.Opp_Order__c+'ceshi==='+links.size()+'==='+link.Tender_information__r.Tender_Order__c);
                                if(opp.Opp_Order__c >= link.Tender_information__r.Tender_Order__c){
                                  opp.Bidding_Project_Name_Bid__c = link.Tender_information__c;
                                  //opp.TenderBeginDate_Text__c = link.Tender_information__r.TenderDate__c;//更改询价状态2时，引用超20，link.Tender_information__r.TenderBeginTime__c;
                                  opp.InfoTypeBid_text__c = link.Tender_information__r.InfoType__c;
                                  //20220718 you 招标项目 start
                                  if(String.isNotBlank(link.Tender_information__r.InfoType__c) && link.Tender_information__r.InfoType__c=='3：结果' && String.isNotBlank(link.Tender_information__r.subInfoType__c) && (link.Tender_information__r.subInfoType__c=='3-5：中标通知'  || link.Tender_information__r.subInfoType__c=='3-6：合同公告')){
                                    tenIds.add(link.Opportunity__c); //符合条件生成任务
                                  }
                                  //20220718 you 招标项目 end
                                  break;
                                }
                                //20220615 you SWAG-CFD4SU 改造 end 
                            }
                        }
                        //DB202307367354 lt 【招标项目】漏单计算逻辑修改 20231115 start
                        for (Tender_Opportunity_Link__c link : links){
                            oppIdSet.add(link.Opportunity__c);
                        }
                        //DB202307367354 lt 【招标项目】漏单计算逻辑修改 20231115 end
                    }

                    //DB202307367354 lt 【招标项目】漏单计算逻辑修改 20231115 start
                    if(oppIdSet.Size() > 0){
                        TenderUtil.UpdLeakageNum(oppIdSet);
                    }
                    //DB202307367354 lt 【招标项目】漏单计算逻辑修改 20231115 end

                    //20220829 you SWAG-CHL67J start
                    Integer returncount =0;
                    for (Tender_Opportunity_Link__c link1 : links) {
                        if (opp.Id == link1.Opportunity__c) {
                            if(String.isNotBlank(link1.Tender_information__r.InfoType__c) && link1.Tender_information__r.InfoType__c!='1：预告' && String.isNotBlank(link1.Tender_information__r.subInfoType__c) && link1.Tender_information__r.subInfoType__c!='3-1：废标公告' && link1.Tender_information__r.subInfoType__c!='3-2：流标公告'){
                                system.debug('jinlaile');     
                                returncount += 1;
                              }
                            
                         }
                    } 
                    opp.Tender_Number__c= returncount;
                    //20220829 you SWAG-CHL67J end 
                }
                update opportunities;

            }
            //20220718 you 招标任务 start               
            if (tenIds !=null && tenIds.size() > 0) {
              Database.executeBatch(new TenderResultConfirmTaskBatch(tenIds));
            }
            //20220718 you 招标任务 end
        }
        //SWAG-CHL67J 【委托】【FY23询价改善】-询价页面/招标项目增加统计字段 fy start 
        // if (TenderIds.size() > 0) {
        //     updateTender(TenderIds);
        // }
        //SWAG-CHL67J 【委托】【FY23询价改善】-询价页面/招标项目增加统计字段 fy end
    }
}
 @TestVisible
    public static void testI() {
        
    }
}