public without sharing class MeetingDelayApplyTriggerHandler extends Oly_TriggerHandler {

    private List<meeting_delay_apply__c> newList;
    private Map<Id,meeting_delay_apply__c> oldMap;
    private Map<Id,meeting_delay_apply__c> newMap;

    public MeetingDelayApplyTriggerHandler() {
        this.newList = (List<meeting_delay_apply__c>) Trigger.new;
        this.oldMap = (Map<Id,meeting_delay_apply__c>) Trigger.oldMap;
        this.newMap = (Map<Id,meeting_delay_apply__c>) Trigger.newMap;
    }


    protected override void beforeUpdate() {
        setColumn();
    }

    protected override void afterUpdate() {
        addColumn();
        //lt  p【学会取消合并】  20231027 start
        BPTips();
    }

    protected override void afterInsert() {
        BPTips();
    }

    //会议状态是备品申请中时，允许增加和修改决裁信息。会议时间不允许变更
    private void BPTips(){
        List<String> camIdList = new List<String>();
        //<学会Id，会议状态>
        Map<String,String> camstaMap = new Map<String,String>();
        //<学会Id，开始日期>
        Map<String,Date> camstadateMap = new Map<String,Date>();
        //<学会Id，结束日期>
        Map<String,Date> camenddateMap = new Map<String,Date>();

        for (meeting_delay_apply__c mda :newList ){
            camIdList.add(mda.campaign__c);
        }

        List<Campaign> camList = [Select Id,Name,CampaignStatus__c,StartDate,EndDate from Campaign
                                  Where Id in:camIdList];

        if(camList.Size() > 0){
            for(Campaign cam : camList){
                if(!camstaMap.containsKey(cam.Id)){
                    camstaMap.put(cam.Id,cam.CampaignStatus__c);
                    camstadateMap.put(cam.Id,cam.StartDate);
                    camenddateMap.put(cam.Id,cam.EndDate);
                }
            }
        }
        
        System.debug('202309212012---1');
        String meetingDealyRecordId = Schema.SObjectType.meeting_delay_apply__c.getRecordTypeInfosByDeveloperName().get('MeetingPostpone').getRecordTypeId();
        for (meeting_delay_apply__c mda :newList ){
            System.debug('202309212012---2:'+mda.campaign__c);
            if(camstaMap.get(mda.campaign__c) == '备品已申请' && mda.RecordTypeId == meetingDealyRecordId){
                if(mda.meeting_start_date__c != camstadateMap.get(mda.campaign__c)){
                    mda.meeting_start_date__c.addError('备品已申请,会议时间不允许变更。');
                }
                if(mda.meeting_end_date__c != camenddateMap.get(mda.campaign__c)){
                    mda.meeting_end_date__c.addError('备品已申请,会议时间不允许变更。');
                }
            }
        }
    }
    //lt  p【学会取消合并】  20231027 end
    
    //当审批流程走完时 更新 市场活动相关字段
    private void addColumn(){
        List<Campaign> clist = new List<Campaign>();
        Map<Id,Campaign> cmap = new Map<Id,Campaign>();
        List<Id> cids = new List<Id>();
        List<Id> raids = new List<Id>(); //20230711 lt DB202306243540 P:学会取消合并  add
        //kk  死id优化   如果报错说没有此方法，就是类的api版本不够  start
        String meetingDealyRecordId = Schema.SObjectType.meeting_delay_apply__c.getRecordTypeInfosByDeveloperName().get('MeetingPostpone').getRecordTypeId();
        String meetingCancleRecordId = Schema.SObjectType.meeting_delay_apply__c.getRecordTypeInfosByDeveloperName().get('CancelApplication').getRecordTypeId();
        String camServiceEngineerTrainingId = Schema.SObjectType.Campaign.getRecordTypeInfosByDeveloperName().get('ServiceEngineerTraining').getRecordTypeId();
        //kk  死id优化   如果报错说没有此方法，就是类的api版本不够  end
        for (meeting_delay_apply__c mda :newList ) {
            //判断更新前后的状态是否不同 若不同,则判断更新后的状态是否为'已完成'
            //20230711 lt DB202306243540 P:学会取消合并  add   && mda.RecordTypeId == meetingDealyRecordId
            if ((mda.status__c != oldMap.get(mda.Id).status__c) && mda.status__c == '已完成'  && mda.RecordTypeId == meetingDealyRecordId) {
                String camId = mda.campaign__c  ;

                Campaign cam = new Campaign();

                cam.Id = camId;
                cam.StartDate = mda.meeting_start_date__c;
                cam.EndDate = mda.meeting_end_date__c;
                cam.PlanBackData__c = mda.dismantling_date__c;
                cam.Meeting_Cooperate__c = mda.Meeting_Cooperate1__c;
                cam.Meeting_Type__c = mda.Meeting_Type__c;
                cam.HostName__c = mda.HostName__c;
                cam.cooperatorCompany__c = mda.cooperatorCompany__c;
                cam.Meeting_Cooperate2__c = mda.Meeting_Cooperate2__c;
                cam.Meeting_Cooperate3__c = mda.Meeting_Cooperate3__c;
                cam.Meeting_Cooperate4__c = mda.Meeting_Cooperate4__c;
                cam.Status = mda.campaign_status__c;
                //OBPM LY 20211221 start
                cam.IF_Approved__c = mda.IF_Approved__c;//是否申请决裁
                cam.Meeting_Approved_No__c = mda.MeetingApproved__c;//会议决裁申请
                if (String.isBlank(mda.MeetingApproved__c)) {
                    cam.MeetingApprovedNo__c = null;
                } else {
                    cam.MeetingApprovedNo__c = mda.MeetingApproved__r.MeetingApprovedNo__c;
                }

                // cam.Test_Status__c = mda.campaign_status__c;
                //OBPM LY 20211221 end
                clist.add(cam);

            }
            //update by rentx 2021-01-20 SWAG-BXF5JV start  在提交申请后撤回时,回滚学会的状态
            // else if ((mda.status__c != oldMap.get(mda.Id).status__c) && mda.status__c == '驳回' ) {
            //20230711 lt DB202306243540 P:学会取消合并  add   && mda.RecordTypeId == meetingDealyRecordId
            else if ((mda.status__c != oldMap.get(mda.Id).status__c) && (mda.status__c == '驳回'  || mda.status__c == '草案中') && mda.RecordTypeId == meetingDealyRecordId) {
            //update by rentx 2021-01-20 SWAG-BXF5JV end

                Campaign cam = new Campaign();
                cam.Id = mda.campaign__c;
                cam.Status = mda.campaign_status__c;
                clist.add(cam);
            }

            //20230711 lt DB202306243540 P:学会取消合并  start
            if((mda.Status__c != oldMap.get(mda.Id).Status__c) && mda.Status__c == '已完成' && mda.RecordTypeId == meetingCancleRecordId){
                String camId = mda.campaign__c  ;

                Campaign cam = new Campaign();

                if(mda.campaign__r.Status == '公开中' && mda.campaign__r.RecordTypeId != camServiceEngineerTrainingId){
                    raids.add(camId);
                    // cam.Status = '取消申请中';
                }
                if(mda.campaign__r.RecordTypeId == camServiceEngineerTrainingId){
                    cam.Mailflg_Cancel_Service__c = true;
                }
                
                cam.Id = camId;
                cam.CancelDay__c = Date.today();
                cam.CancleReason__c = mda.CancleReason__c;
                cam.cancelApprovalDate__c = Date.today();
                cam.Status = '取消';
                clist.add(cam);
            }else if((mda.Status__c != oldMap.get(mda.Id).Status__c) && mda.Status__c == '审批中' && mda.RecordTypeId == meetingCancleRecordId){
                String camId = mda.campaign__c  ;

                Campaign cam = new Campaign();

                cam.Id = camId;
                if(mda.campaign__r.RecordTypeId == camServiceEngineerTrainingId){
                    cam.CancelDate__c = Date.today();
                }else{
                    cam.canelApplyDate__c = Date.today();
                    cam.Status = '取消申请中';
                }
                
                clist.add(cam);
            }else if(((mda.Status__c != oldMap.get(mda.Id).Status__c) && mda.Status__c == '驳回' && mda.RecordTypeId == meetingCancleRecordId)
                  || ((mda.Status__c != oldMap.get(mda.Id).Status__c) && mda.Status__c == '草案中' && mda.RecordTypeId == meetingCancleRecordId)) {
                String camId = mda.campaign__c  ;
                Campaign cam = new Campaign();
                cam.Id = camId;
                cam.canelApplyDate__c = null;
                if(mda.campaign__r.RecordTypeId == camServiceEngineerTrainingId){
                    cam.CancelDate__c = null;
                }
                if(mda.campaign__r.RecordTypeId == camServiceEngineerTrainingId && mda.campaign__r.Status == '草案中'){
                    cam.Status = '草案中';
                }else{
                    cam.Status = '公开中';
                }
                
                clist.add(cam);
            }
            //20230711 lt DB202306243540 P:学会取消合并  end
        }

        //20230711 lt DB202306243540 P:学会取消合并  start
        //备品借出申请
        if(raids.size() > 0){
            List<Rental_Apply__c> raObjs = [select Id, CancelDay__c, Campaign__c, CancelApplyDay__c
                                        FROM Rental_Apply__c
                                        where Campaign__c in :raids];
            for(Rental_Apply__c ra : raObjs){
                ra.CancelApplyDay__c = Date.today();
            }
            update raObjs;
        }
        //20230711 lt DB202306243540 P:学会取消合并  end
        if (clist.size() > 0) {
            update clist;
        }
    }


    //设置字段  经理 & 部长
    //提交时设置old字段的值
    private void setColumn(){
        List<String> camIds = new List<String>();
        List<meeting_delay_apply__c> mlist = new List<meeting_delay_apply__c>();
        List<Id> uids = new List<Id>();
        //kk  死id优化  如果报错说没有此方法，就是类的api版本不够 start
        String meetingDealyRecordId = Schema.SObjectType.meeting_delay_apply__c.getRecordTypeInfosByDeveloperName().get('MeetingPostpone').getRecordTypeId();
        //kk  死id优化   如果报错说没有此方法，就是类的api版本不够 start
        for (meeting_delay_apply__c mda :newList ) {
            //判断更新前后的状态是否不同 若不同,则判断更新后的状态是否为'审批中'
            //20230711 lt DB202306243540 P:学会取消合并  add   && mda.RecordTypeId == meetingDealyRecordId
            if ((mda.status__c != oldMap.get(mda.Id).status__c) && mda.status__c == '审批中'  && mda.RecordTypeId == meetingDealyRecordId) {
                //获取当前会议延期申请对象的对应人
                uids.add(mda.CreatedById);
                mlist.add(mda);
                camIds.add(mda.campaign__c  );
            }
        }
        if (camIds.size() == 0) {
            return;
        }else{
                Map<String,Campaign> camMap = new Map<String,Campaign>();
                List<Campaign> statusList = [SELECT Id,
                                                Status,StartDate,EndDate,PlanBackData__c,
                                                Meeting_Cooperate__c,Meeting_Type__c,HostName__c,
                                                cooperatorCompany__c,Meeting_Cooperate2__c,Meeting_Cooperate3__c,Meeting_Cooperate4__c,
                                                IF_Approved__c,Meeting_Approved_No__c 
                                                 FROM Campaign WHERE id in :camIds];
                for (Campaign c :statusList ) {
                    camMap.put(c.Id, c);
                }
                
                Map<Id, User> userMap = new Map<Id, User>();
                List<user> userList = New List<user>();

                userList = [SELECT Id, SalesManager__c, BuchangApprovalManagerSales__c FROM user WHERE id in :uids];

                for (User u : userList) {
                    userMap.put(u.Id, u);
                }


                for (meeting_delay_apply__c mda : mlist) {
                    mda.meeting_start_date_Old__c = camMap.get(mda.campaign__c).StartDate;
                    mda.meeting_end_date_Old__c = camMap.get(mda.campaign__c).EndDate;
                    mda.dismantling_date_Old__c = camMap.get(mda.campaign__c).PlanBackData__c;
                    mda.Meeting_Cooperate1_Old__c = camMap.get(mda.campaign__c).Meeting_Cooperate__c;
                    mda.Meeting_Type_Old__c = camMap.get(mda.campaign__c).Meeting_Type__c == '主办会' ? '自办会' : camMap.get(mda.campaign__c).Meeting_Type__c;
                    mda.HostName_Old__c = camMap.get(mda.campaign__c).HostName__c;
                    mda.cooperatorCompany_Old__c = camMap.get(mda.campaign__c).cooperatorCompany__c;
                    mda.Meeting_Cooperate2_Old__c = camMap.get(mda.campaign__c).Meeting_Cooperate2__c;
                    mda.Meeting_Cooperate3_Old__c = camMap.get(mda.campaign__c).Meeting_Cooperate3__c;
                    mda.Meeting_Cooperate4_Old__c = camMap.get(mda.campaign__c).Meeting_Cooperate4__c;
                    mda.IF_Approved_Old__c = camMap.get(mda.campaign__c).IF_Approved__c;
                    mda.MeetingApproved_Old__c = camMap.get(mda.campaign__c).Meeting_Approved_No__c;

                    if (String.isNotBlank(mda.CreatedById)) {
                        mda.manager__c = userMap.get(mda.CreatedById).SalesManager__c == null ? mda.CreatedById : userMap.get(mda.CreatedById).SalesManager__c;
                        mda.minister__c = userMap.get(mda.CreatedById).BuchangApprovalManagerSales__c == null ? mda.CreatedById : userMap.get(mda.CreatedById).BuchangApprovalManagerSales__c;
                    }
                    mda.campaign_status__c = camMap.get(mda.campaign__c).Status;
                }

                /*if (shareList.size() > 0) {
                    insert shareList;   
                }*/

                for (Campaign c : statusList) {
                    c.Status = '变更申请中';
                }
            update statusList;   
        }

    }
}