public without sharing class AgencyOppUpdHandler extends Oly_TriggerHandler {

    private Map<Id, Opportunity> newMap;
    private Map<Id, Opportunity> oldMap;
    private List<Opportunity> newList;
    private List<Opportunity> oldList;

    public AgencyOppUpdHandler() {
        this.newMap = (Map<Id, Opportunity>) Trigger.newMap;
        this.oldMap = (Map<Id, Opportunity>) Trigger.oldMap;
        this.newList = (List<Opportunity>) Trigger.new;
        this.oldList = (List<Opportunity>) Trigger.old;
    }

    private static Map<Id, Agency_Opportunity__c> updAgencyOpportunityMap = new Map<Id, Agency_Opportunity__c>();

    protected override void beforeInsert() {
        //OLY_OCM-334
        //以下のロジックはなくしてください。（金額の入力は不要）
        //OCSM询价.病院契約金額_元(Dealer_Final_Price__c) = 经销商询价. 医院合同金额(含税)
        //OCSM询价.OCM预测成交金额(含税)_元(Wholesale_Price__c) = 经销商询价.订货金额(含税)
        //insertOppFromAgencyOpportunity();
    }

    protected override void afterInsert() {
        set_AgencyOpportunity_ChangeToOpportunity();
        set_AgencyOpportunity_OCSMOwner();

        if (updAgencyOpportunityMap.size() > 0) {
            update updAgencyOpportunityMap.values();
        }
    }

    protected override void afterUpdate() {
        set_AgencyOpportunity_Amount();
        set_AgencyOpportunity_OCSMOwner();

        if (updAgencyOpportunityMap.size() > 0) {
            update updAgencyOpportunityMap.values();
        }

        updateTask(); // 2022-6-27 yjk  询价任务
    }


    //2022-6-27 yjk  询价任务 start
    private void updateTask() {
        List<Id> oppIds = new List<Id>();
        List<Id> canceloppIds = new List<Id>();//20221208 you DB202211594688

        List<Opportunity> opList = new List<Opportunity>();
        for(Opportunity opp : newList){
            //if(opp.IF_Submit__c == true && oldMap.get(opp.id).IF_Submit__c ==false){
            if(opp.Assistant_Applied_Date__c != null && oldMap.get(opp.id).Assistant_Applied_Date__c == null){
                oppIds.add(opp.id);
                Opportunity op = new Opportunity();
                op.Id = opp.Id;
                op.ConfirmationofAward_createTime__c = (opp.Task_createTime__c !=null || opp.ifOpenBid__c =='非公开招标') ? Date.today() : null; //20220823 you
                op.ConfirmationofAward__c = 'OLY中标';
                opList.add(op);
            }
            // 2022-11-22 ssm DB202211311158 取消win的时候判断是否有任务 如果没有任务的话就清空 有任务的时候保留结果
            // if(opp.Assistant_Applied_Date__c == null && oldMap.get(opp.id).Assistant_Applied_Date__c != null){//取消合同申请日，字段清空
            if(opp.Assistant_Applied_Date__c == null && oldMap.get(opp.id).Assistant_Applied_Date__c != null && 
                !(!opp.SAP_Send_OK__c && oldMap.get(opp.id).SAP_Send_OK__c && oldMap.get(opp.id).Task_createTime__c != null)){
                Opportunity op = new Opportunity();
                op.Id = opp.Id;
                op.ConfirmationofAward_createTime__c = null;
                op.ConfirmationofAward__c = '';
                opList.add(op);
            }
            if(opp.ConfirmationofAward__c != null && oldMap.get(opp.id).ConfirmationofAward__c == null){
                oppIds.add(opp.id);
            }
            //20221208 you DB202211594688  取消 未完成的失单报告任务
            if(opp.ConfirmationofAward__c != null && oldMap.get(opp.id).ConfirmationofAward__c !=null && oldMap.get(opp.id).ConfirmationofAward__c=='竞争对手中标' && opp.ConfirmationofAward__c=='OLY中标' && opp.LostTask_createTime__c !=null && opp.LostTask_comfirmTime__c ==null){
               canceloppIds.add(opp.id);
            }

        }
        
        List<task__c> taskList = [select id,taskStatus__c ,OpportunityId__c,RecordType.Name from task__c where ((RecordType.Name in ('中标结果确认')  and OpportunityId__c in :oppIds) OR (RecordType.Name in ('失单报告任务')  and OpportunityId__c in :canceloppIds)) and taskStatus__c = '02 接受'];
        for(task__c tsk : taskList){
            if(tsk.RecordType.Name=='失单报告任务'){
                tsk.taskStatus__c = '04 取消';
                tsk.cancelDate__c = date.today();
                tsk.cancelReasonSelect__c = '修改中标结果';  
                Opportunity op = new Opportunity();
                op.Id = tsk.OpportunityId__c;
                op.LostTask_createTime__c =null;
                opList.add(op);
            }else{
                tsk.taskStatus__c = '03 完成';
            }
			
		}
        if(null!=opList && opList.size()>0){
           update opList;
        }

		update taskList;
    }

    //2022-6-27 yjk  询价任务 end

    //private void insertOppFromAgencyOpportunity() {
    //    for(Opportunity nObj : newList) {
    //        if(nObj.Agency_Opportunity__c != null) {
    //            nObj.Dealer_Final_Price__c = nObj.AgencyOpp_Amount__c;
    //            nObj.Wholesale_Price__c = nObj.AgencyOpp_OCMSale_Price__c;
    //        }
    //    }
    //}

    // .询价 Copy 到 询价、.询价.Change_To_Opportunity__c = oppIds.get(ao.Id)
    private void set_AgencyOpportunity_ChangeToOpportunity() {
        Map<Id, Id> oppIds = new Map<Id, Id>();
        for(Opportunity nObj : newList) {
            if(nObj.Agency_Opportunity__c != null) {
                oppIds.put(nObj.Agency_Opportunity__c, nObj.Id);
            }
        }
        if (oppIds.size() > 0) {
            List<Agency_Opportunity__c> aoList = [select Id, Name, Change_To_Opportunity__c from Agency_Opportunity__c where Id in :oppIds.keySet()];
            for(Agency_Opportunity__c ao : aoList) {
                if (false == updAgencyOpportunityMap.containsKey(ao.Id)) {
                    updAgencyOpportunityMap.put(ao.Id, ao);
                }
                ao = updAgencyOpportunityMap.get(ao.Id);
                ao.Change_To_Opportunity__c = oppIds.get(ao.Id);
            }
        }
    }

    // 询价 Win 的时候 更新 .询价 的 Amount__c = oppMap.get(ao.Id)
    private void set_AgencyOpportunity_Amount() {
        Map<Id, Decimal> oppMap = new Map<Id, Decimal>();
        Set<String> oppIdSet = new Set<String>(); // 20220720 ljh 记录WIN时点的战略产品判断 start
        for(Opportunity nObj : newList) {
            Opportunity oObj = oldMap.get(nObj.Id);
            // 20220720 ljh 记录WIN时点的战略产品判断 start
            // if(nObj.Agency_Opportunity__c != null && nObj.AgencyOpp_FromOCM__c == true && oObj.SAP_Send_OK__c == false && nObj.SAP_Send_OK__c == true) {
            //     oppMap.put(nObj.Agency_Opportunity__c, nObj.Dealer_Final_Price__c);
            // }
            if( oObj.SAP_Send_OK__c == false && nObj.SAP_Send_OK__c == true) {
                if(nObj.Agency_Opportunity__c != null && nObj.AgencyOpp_FromOCM__c == true){
                    oppMap.put(nObj.Agency_Opportunity__c, nObj.Dealer_Final_Price__c);
                }
                oppIdSet.add(nObj.Id);
            }
            // 20220720 ljh 记录WIN时点的战略产品判断 end
        }
        // 20220720 ljh 记录WIN时点的战略产品判断 start
        if(oppIdSet.size() > 0 ){
            List<OpportunityLineItem> OppLIlist = [select Id,Key_product_147P_Text__c,Key_product_147P__c from OpportunityLineItem  where OpportunityId in :oppIdSet];
            for(OpportunityLineItem oli : OppLIlist){
                oli.Key_product_147P_Text__c = oli.Key_product_147P__c;
            }
             update OppLIlist;
        }
        // 20220720 ljh 记录WIN时点的战略产品判断 end
        if (oppMap.size() > 0) {
            List<Agency_Opportunity__c> aoList = [select Id, Name, Amount__c from Agency_Opportunity__c where Id in :oppMap.keySet()];
            for(Agency_Opportunity__c ao : aoList) {
                if (false == updAgencyOpportunityMap.containsKey(ao.Id)) {
                    updAgencyOpportunityMap.put(ao.Id, ao);
                }
                ao = updAgencyOpportunityMap.get(ao.Id);
                ao.Amount__c = oppMap.get(ao.Id);
            }
        }
    }

    // 询价新規 or Owner変更 的时候 更新 .询价 的 OCSM_Owner__c = nObj.OwnerId;
    private void set_AgencyOpportunity_OCSMOwner() {
        for(Opportunity nObj : newList) {
            Opportunity oObj;
            if (oldMap != null) {
                oObj = oldMap.get(nObj.Id);
            }
            if(nObj.Agency_Opportunity__c != null
                && (oObj == null || nObj.OwnerId != oObj.OwnerId)
            ) {
                Agency_Opportunity__c ao = new Agency_Opportunity__c(Id = nObj.Agency_Opportunity__c);
                if (false == updAgencyOpportunityMap.containsKey(ao.Id)) {
                    updAgencyOpportunityMap.put(ao.Id, ao);
                }
                ao = updAgencyOpportunityMap.get(ao.Id);
                ao.OCSM_Owner__c = nObj.OwnerId;
            }
        }

    }
        @TestVisible
    public static void testI() {
        integer i = 0;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
    }
}