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() {
    // 判断是否跳过
    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 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;
            }
        }
    }
}

// 更新招标信息
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 || '00510000000gmxH'.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');
                    }
                }
                if (Trigger.isAfter && Trigger.isDelete) {
                    StaticParameter.EscapeOtherUpdateTenOwner = false;
                    update tender_list;
                    StaticParameter.EscapeOtherUpdateTenOwner = true;
                } else {
                    update tender_list;
                }
            }
        }
    }
}

// 更新询价信息
public void updateOppotunityByInsert(List<Tender_Opportunity_Link__c> records) {
    if (records != null && records.size() > 0) {
        List<String> oppIds = new List<String>();
        // 获得要更新的询价
        for (Tender_Opportunity_Link__c record: records) {
            if (!oppIds.contains(record.Opportunity__c)) {
                oppIds.add(record.Opportunity__c);
            }
        }
        if (oppIds.size() > 0) {
            List<Opportunity> opportunities = [select id, Bidding_Project_Name_Bid__c, Bidding_Project_Name_Bid__r.InfoType__c, TenderBeginDate_Text__c, InfoTypeBid_text__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 from Tender_Opportunity_Link__c where Opportunity__c in :oppIds];
                for (Opportunity opp : opportunities) {
                    for (Tender_Opportunity_Link__c link : links) {
                        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;
                            }
                        }
                    }
                    
                }
                update opportunities;
            }
        }
    }
}

// 更新询价信息
public void updateOppotunityByDelete(List<Tender_Opportunity_Link__c> records) {
    if (records != null && records.size() > 0) {
        List<String> oppIds = new List<String>();
        // 获得要更新的询价
        for (Tender_Opportunity_Link__c record: records) {
            if (!oppIds.contains(record.Opportunity__c)) {
                oppIds.add(record.Opportunity__c);
            }
        }
        if (oppIds.size() > 0) {
            List<Opportunity> opportunities = [select id, Bidding_Project_Name_Bid__c, TenderBeginDate_Text__c from Opportunity where id in :oppIds];
            if (opportunities.size() > 0) {
                List<Tender_Opportunity_Link__c> links = [select id, Opportunity__c, Tender_information__c, Tender_information__r.InfoType__c from Tender_Opportunity_Link__c where Opportunity__c in :oppIds];
                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;
                    } else {
                        for (Tender_Opportunity_Link__c link : links) {
                            if (opp.Id == link.Opportunity__c) {
                                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;
                                }
                            }
                        }
                    }
                }
                update opportunities;
            }
        }
    }
}
}