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

    public UpdateContractAimAmountHandler() {
        this.newMap = (Map<Id, Account>) Trigger.newMap;
        this.oldMap = (Map<Id, Account>) Trigger.oldMap;
        this.newList = (List<Account>) Trigger.new;
        this.oldList = (List<Account>) Trigger.old;
    }
    protected override void beforeUpdate() {
        changeAssume();
        //SetAwaitToSendAWS();//new
        CustomizePageJudge();//20221121 lt
    }
    

    protected override void afterInsert() {
        createAgencyTarget();
        SetAwaitToSendAWS();

    }

    protected override void afterUpdate() {
        createAgencyTarget();
        // LHJ KWAG-BQMA89 202006 Start
        updateAgencyAccout();
        // LHJ KWAG-BQMA89 202006 End
        SetAwaitToSendAWS();//old
    }
    

    private void createAgencyTarget() {
        //  LD 20200807 优化account record type ID 读取方法 Start
        //新逻辑
        Id rtId = '012100000006KW8AAM';
        // 原逻辑
        // Id rtId = [select Id,DeveloperName from RecordType where IsActive = true and SobjectType = 'Agency_Opportunity__c' and DeveloperName = 'Target'].Id;
        //  LD 20200807 优化account record type ID 读取方法 End

        List<Agency_Opportunity__c> upsertList = new List<Agency_Opportunity__c>();
        for (Account nObj : newList) {
            //01210000000QjCNAA0 契約
            if (nObj.RecordTypeId != '01210000000QjCNAA0') continue;
            if (nObj.Aim_Price_GIR__c != null || nObj.Aim_Price_ET__c != null || nObj.Aim_Price_SP__c != null) {
                Account old = null;
                if (oldMap != null && oldMap.containsKey(nObj.Id)) {
                    old = oldMap.get(nObj.Id);
                }
                //List<Agency_Opportunity__c> aopps = [select Id, Department_Cateogy_l__c, Aim_Price__c, OCM_Term__c, Agency__c, RecordTypeId
                //  from Agency_Opportunity__c
                //  where Agency_Hospital_Target__c = null and Agency__c = :nObj.ParentId and OCM_Term__c = :nObj.Contract_Fiscal_Period__c and RecordTypeId = :rtId];
                
                //Map<String, Agency_Opportunity__c> dclMap = new Map<String, Agency_Opportunity__c>();
                //if (aopps.size() > 0) {
                //  for (Agency_Opportunity__c aopp : aopps) {
                //      dclMap.put(aopp.Department_Cateogy_l__c, aopp);
                //  }
                //}
                
                if (nObj.Aim_Price_GIR__c != null && (old == null || nObj.Aim_Price_GIR__c != old.Aim_Price_GIR__c)) {
                    Agency_Opportunity__c aopp;
                    //if (dclMap.containsKey('GIR')) {
                    //  aopp = dclMap.get('GIR');
                    //} else {
                    aopp = new Agency_Opportunity__c();
                    aopp.Agency__c = nObj.ParentId;
                    aopp.OCM_Term__c = nObj.Contract_Fiscal_Period__c;
                    aopp.RecordTypeId = rtId;
                    aopp.Name = '目标::'+aopp.OCM_Term__c+':'+nObj.Name+' GIR';
                    aopp.Department_Cateogy_l__c = 'GIR';
                    aopp.TargetInputKey__c='AmtTarget:GIR:'+aopp.OCM_Term__c+nObj.Id;
                    //}

                    aopp.Aim_Price__c = nObj.Aim_Price_GIR__c;

                    upsertList.add(aopp);
                }

                if (nObj.Aim_Price_ET__c != null && (old == null || nObj.Aim_Price_ET__c != old.Aim_Price_ET__c)) {
                    Agency_Opportunity__c aopp;
                    //if (dclMap.containsKey('ET')) {
                    //  aopp = dclMap.get('ET');
                    //} else {
                    aopp = new Agency_Opportunity__c();
                    aopp.Agency__c = nObj.ParentId;
                    aopp.OCM_Term__c = nObj.Contract_Fiscal_Period__c;
                    aopp.RecordTypeId = rtId;
                    aopp.Name = '目标::'+aopp.OCM_Term__c+':'+nObj.Name+' ET';
                    aopp.Department_Cateogy_l__c = 'ET';
                    aopp.TargetInputKey__c='AmtTarget:ET:'+aopp.OCM_Term__c+nObj.Id;
                    //}

                    aopp.Aim_Price__c = nObj.Aim_Price_ET__c;

                    upsertList.add(aopp);
                }

                if (nObj.Aim_Price_SP__c != null && (old == null || nObj.Aim_Price_SP__c != old.Aim_Price_SP__c)) {
                    Agency_Opportunity__c aopp;
                    //if (dclMap.containsKey('SP')) {
                    //  aopp = dclMap.get('SP');
                    //} else {
                    aopp = new Agency_Opportunity__c();
                    aopp.Agency__c = nObj.ParentId;
                    aopp.OCM_Term__c = nObj.Contract_Fiscal_Period__c;
                    aopp.RecordTypeId = rtId;
                    aopp.Name = '目标::'+aopp.OCM_Term__c+':'+nObj.Name+' SP';
                    aopp.Department_Cateogy_l__c = 'SP';
                    aopp.TargetInputKey__c='AmtTarget:SP:'+aopp.OCM_Term__c+nObj.Id;
                    //}

                    aopp.Aim_Price__c = nObj.Aim_Price_SP__c;

                    upsertList.add(aopp);
                }
            }
        }
        if (upsertList.size() > 0) {
            upsert upsertList TargetInputKey__c;
        }
    }
    // LHJ KWAG-BQMA89 202006 Start
    private void updateAgencyAccout() {

        List<Id> accList = new List<Id>();
        List<Agency_Hospital_Link__c> agencyAccList = new List<Agency_Hospital_Link__c>();
        List<Agency_Hospital_Link__c> updAgenAccList = new List<Agency_Hospital_Link__c>();

        for (Account nObj : newList) {
            if (oldMap.get(nObj.Id).Is_Active__c == '有効' && nObj.Is_Active__c != '有効'  ) {
                accList.add(nObj.Id);
            }
        }
        if (accList.size() > 0) {
            agencyAccList = [select id, Agency_Campaign_Obj__c from Agency_Hospital_Link__c where Hospital__c in :accList];
            for (Agency_Hospital_Link__c agenAcc : agencyAccList) {
                if(agenAcc.Agency_Campaign_Obj__c == true){
                    agenAcc.Agency_Campaign_Obj__c = false; 
                    updAgenAccList.add(agenAcc);
                }
            }
            if (updAgenAccList.size() > 0 ) {
                update updAgenAccList;
            }
        }
    }
    // LHJ KWAG-BQMA89 202006 End
    // fxk 担当人改变后担当发生变化给他‘√’上 2021/7/21 Start
    public void changeAssume() {
        for (Account Accs : newList) {
            if (Accs.GI_Main__c != null && Accs.GI_Main__c != oldMap.get(Accs.Id).GI_Main__c) {
                Accs.Assume_Change__c = true;
            }
            if (Accs.BF_owner__c != null && Accs.BF_owner__c != oldMap.get(Accs.Id).BF_owner__c) {
                Accs.Assume_Change__c = true;
            }
            if (Accs.ET_owner__c != null && Accs.ET_owner__c != oldMap.get(Accs.Id).ET_owner__c) {
                Accs.Assume_Change__c = true;
            }
            if (Accs.SP_Main__c != null && Accs.SP_Main__c != oldMap.get(Accs.Id).SP_Main__c) {
                Accs.Assume_Change__c = true;
            }
            if (Accs.URO_owner_ID__c != null && Accs.URO_owner_ID__c != oldMap.get(Accs.Id).URO_owner_ID__c) {
                Accs.Assume_Change__c = true;
            }
            if (Accs.GYN_owner__c != null && Accs.GYN_owner__c != oldMap.get(Accs.Id).GYN_owner__c) {
                Accs.Assume_Change__c = true;
            }
            if (Accs.ENT_owner_ID__c != null && Accs.ENT_owner_ID__c != oldMap.get(Accs.Id).ENT_owner_ID__c) {
                Accs.Assume_Change__c = true;
            }
            if (Accs.Energy_LeaderStr__c != null && Accs.Energy_LeaderStr__c != oldMap.get(Accs.Id).Energy_LeaderStr__c) {
                Accs.Assume_Change__c = true;
            }
        }
    }
    // fxk 担当人改变后担当发生变化给他‘√’上 2021/7/21 End
    // 
    public static Map<Id,Id> NFM601_IdMap = new Map<Id,Id>();
    private void SetAwaitToSendAWS(){
        Map<String,String> recordTypeIdMap = new Map<String,String>();
        recordTypeIdMap.put('01210000000QfmbAAC', '');//其他
        recordTypeIdMap.put('01210000000QfmRAAS', '');//呼吸科
        recordTypeIdMap.put('01210000000QfmMAAS', '');//妇科
        recordTypeIdMap.put('01210000000QfmHAAS', '');//普外科
        recordTypeIdMap.put('01210000000QfmCAAS', '');//泌尿科
        recordTypeIdMap.put('01210000000Qfm7AAC', '');//消化科
        recordTypeIdMap.put('01210000000Qfm2AAC', '');//耳鼻喉科
        recordTypeIdMap.put('01210000000Qem1AAC', '');//经销商
        recordTypeIdMap.put('01210000000QemGAAS', '');//医院

        List < String > queueableAccountIdList = new List < String > ();
        List<String>    interfaceUserUpsertAccount = new List<String>();
        // 判断当前用户是否是接口用户和系统管理员
        
        for (Account acc : newList) {

            String developerId = acc.RecordTypeId;
            if (recordTypeIdMap.containsKey(developerId) && ('有效'.equals(acc.Is_Active_Formula__c) || '无效'.equals(acc.Is_Active_Formula__c))) {
                Account old = null;

                if (oldMap != null && oldMap.containsKey(acc.Id)) {
                    old = oldMap.get(acc.Id);
                }
                if (old == null) {// 新增医院/科室/经销商
                    if (!NFM601_IdMap.containsKey(acc.Id)) {
                        // 判断是否是接口用户
                        if(UserInfo.getUserId().equals(System.Label.interfaceUserID)){
                            interfaceUserUpsertAccount.add(acc.Id);
                        } else {
                            queueableAccountIdList.add(acc.Id); 
                        }
                        
                        NFM601_IdMap.put(acc.Id, acc.Id);  
                    }
                } else {
                    if (acc.Name != old.Name //名称变更
                        || acc.Salesdepartment_HP__c != old.Salesdepartment_HP__c //销售本部
                        || acc.State_Master__c  != old.State_Master__c //省
                        || acc.City_Master__c  != old.City_Master__c //市
                        || acc.Is_Active__c  != old.Is_Active__c // 有效/无效
                        || acc.Site  != old.Site //别名1
                        || acc.Alias_Name2__c  != old.Alias_Name2__c //别名2
                        || acc.Abbreviation__c  != old.Abbreviation__c //简称
                        || acc.Phone  != old.Phone //电话
                        || acc.Postal_Code__c  != old.Postal_Code__c //邮编
                        || acc.Address__c  != old.Address__c //地址
                        //LLIU-CGRCGK LY 20220728 start
                        || (developerId == '01210000000QemGAAS' && //医院
                           (acc.OCM_Category__c  != old.OCM_Category__c //OCSM分类(医院)
                            || acc.Grade__c  != old.Grade__c ) )//政府等级
                        //LLIU-CGRCGK LY 20220728 end
                        || (developerId == '01210000000Qem1AAC' && //经销商
                            (acc.Business_Paper_Expiration_Date__c  != old.Business_Paper_Expiration_Date__c || //营业执照有效期限  
                                acc.Tax_Practice_Expiration_Date__c  != old.Tax_Practice_Expiration_Date__c || //税务登记证有效期限  
                                acc.Medical_Equipment_Expiration_Date__c  != old.Medical_Equipment_Expiration_Date__c || //医疗器械经营企业许可证有效期限    
                                acc.DGLicenseTo__c  != old.DGLicenseTo__c || //危险化学品经营许可证效期至
                                acc.SPO_ApplicationNo__c  != old.SPO_ApplicationNo__c))// SPO申请单号   
                        ) {
                        if (!NFM601_IdMap.containsKey(acc.Id)) {
                            if(UserInfo.getUserId().equals(System.Label.interfaceUserID)){
                                interfaceUserUpsertAccount.add(acc.Id);
                            } else {
                                queueableAccountIdList.add(acc.Id);
                            } 
                            NFM601_IdMap.put(acc.Id, acc.Id);  
                        }
                    }

                }
            }
    
        }
        //Before : 
        //if(!System.Test.isRunningTest()){
        //After : to avoid mutiple execute
        //if(!(System.Test.isRunningTest()||System.isFuture()||System.isBatch())){
        //Update by Li Jun for PIPL 20220304
        if(!(System.Test.isRunningTest())){

            if (queueableAccountIdList.size() > 0) {
                NFM601Controller.callout('', queueableAccountIdList);
            }
            if (interfaceUserUpsertAccount.size() > 0) {
                NFM601Controller.executefuture('', interfaceUserUpsertAccount);
            }
        }

    }

    //20221121 lt LLIU-CKB5H9【委托】【医院】医院新建申请和变更系统化 start
    public void CustomizePageJudge(){

        for (Account acc : newList){          
            System.debug('lt123-----new审批步骤-----'+acc.ApprovalSteps__c);
            System.debug('lt123-----old审批步骤-----'+oldMap.get(acc.Id).ApprovalSteps__c);     
            if(acc.ApprovalSteps__c != oldMap.get(acc.Id).ApprovalSteps__c){
                System.debug('lt123-----审批步骤改变-----');
                if(acc.CustomizePageFlg__c == true){
                    System.debug('lt123-----acc.CustomizePageFlg__c-----'+acc.CustomizePageFlg__c);
                    acc.CustomizePageFlg__c = false;
                }else{
                    System.debug('lt123-----else,acc.CustomizePageFlg__c-----'+acc.CustomizePageFlg__c);
                     acc.addError('请点击进入客户详情页面，在‘批准历史’栏目下进行批准或拒绝操作');
                }
            }
        }
    }

    //20221121 lt LLIU-CKB5H9【委托】【医院】医院新建申请和变更系统化 end

}