/**
 * Select Id From Contact Where RecordTypeId = '01210000000QfWdAAK' and Strategic_dept_Class__c != null
 */
public without sharing class ContactTriggerHandler extends Oly_TriggerHandler {
    private Map<Id, Contact> newMap;
    private Map<Id, Contact> oldMap;
    private List<Contact> newList;
    private List<Contact> oldList;
    public ContactTriggerHandler() {
        this.newMap = (Map<Id, Contact>) Trigger.newMap;
        this.oldMap = (Map<Id, Contact>) Trigger.oldMap;
        this.newList = (List<Contact>) Trigger.new;
        this.oldList = (List<Contact>) Trigger.old;
    }

    protected override void afterInsert() {
        syncToAgencyContact();
        updateDealerNum();
    }

    protected override void afterUpdate() {
        syncToAgencyContact();
        updateDealerNum();

    }
    protected override void beforeUpdate() {
        // 服务技师 2018/12/24  Start
        UpdateProcessingWork();
        // 服务技师 2018/12/24  end
       
    }


    protected override void afterDelete() {
        syncToAgencyContactDelete();
        updateDealerNum();
    }

    //
    /**
     * @author 张玉山
     * @DateTime 2019-03-11T13:49:10+0800
     * 根据服务技师填写情况更新客户人员上的开展工作字段
     */
    private void UpdateProcessingWork() {
        for ( Contact temContact : newList) {
            if (System.label.UpdateServiceHistory.equals('true')) {

                string ProcessingWork = '';
                string ProcessingWorkWithoutNumber = '';
                if (temContact.ServiceBookInput__c != 0) {
                    ProcessingWork += '维修委托书填写' + temContact.ServiceBookInput__c + '次';
                    ProcessingWorkWithoutNumber +=  '维修委托书填写';

                }
                if (temContact.InspectTime__c != 0) {
                    if (String.isBlank(ProcessingWork)) {
                        ProcessingWork += '点检' + temContact.InspectTime__c + '次';
                        ProcessingWorkWithoutNumber +=  '点检';
                    } else {
                        ProcessingWork += '，点检' + temContact.InspectTime__c + '次';
                        ProcessingWorkWithoutNumber +=  '，点检';

                    }
                }
                if (temContact.InspectEquipmentTime__c != 0) {
                    if (String.isBlank(ProcessingWork)) {
                        ProcessingWork += '点检设备' + temContact.InspectEquipmentTime__c + '个';
                        ProcessingWorkWithoutNumber +=  '点检设备';
                    } else {
                        ProcessingWork += '，点检设备' + temContact.InspectEquipmentTime__c + '个';
                        ProcessingWorkWithoutNumber +=  '，点检设备';
                    }

                }
                if (temContact.VisitTime__c != 0) {
                    if (String.isBlank(ProcessingWork)) {
                        ProcessingWork += '上门' + temContact.VisitTime__c + '次';
                        ProcessingWorkWithoutNumber +=  '上门';
                    } else {
                        ProcessingWork += '，上门' + temContact.VisitTime__c + '次';
                        ProcessingWorkWithoutNumber +=  '，上门';
                    }

                }
                if (temContact.pollingTime__c != 0) {
                    if (String.isBlank(ProcessingWork)) {
                        ProcessingWork += '巡检' + temContact.pollingTime__c + '次';
                        ProcessingWorkWithoutNumber +=  '巡检';
                    } else {
                        ProcessingWork += '，巡检' + temContact.pollingTime__c + '次';
                        ProcessingWorkWithoutNumber +=  '，巡检';
                    }

                }
                if (temContact.TeachingTime__c != 0) {
                    if (String.isBlank(ProcessingWork)) {
                        ProcessingWork += '培训次数' + temContact.TeachingTime__c + '次';
                        ProcessingWorkWithoutNumber +=  '培训次数';
                    } else {
                        ProcessingWork += '，培训次数' + temContact.TeachingTime__c + '次';
                        ProcessingWorkWithoutNumber +=  '，培训次数';
                    }
                }
                //if (!String.isBlank(ProcessingWork)) {
                //    ProcessingWork += '。';
                //    ProcessingWorkWithoutNumber += '。';
                //}
                temContact.ProcessingWork__c = ProcessingWork;
                temContact.ProcessingWorkWithoutNumber__c = ProcessingWorkWithoutNumber;


            }
        }

    }
    // 服务技师 2018/12/24  end
    private void syncToAgencyContact() {
        Map<Id, Agency_Contact__c> targetContactMap = new Map<Id, Agency_Contact__c>();
        for (Contact nObj : newList) {
            if (nObj.RecordTypeId == '01210000000QfWdAAK'                // Doctor
                    && String.isBlank(nObj.Strategic_dept_Class__c) == false
               ) {
                if (Trigger.isInsert
                        || (Trigger.isUpdate
                            //                        && (
                            //                            oldMap.get(nObj.Id).LastName                != nObj.LastName
                            //                         || oldMap.get(nObj.Id).FirstName               != nObj.FirstName
                            //                         || oldMap.get(nObj.Id).Strategic_dept_Class__c != nObj.Strategic_dept_Class__c
                            //                         || oldMap.get(nObj.Id).Type__c                 != nObj.Type__c
                            //                         || oldMap.get(nObj.Id).Doctor_Division1__c     != nObj.Doctor_Division1__c
                            //                        )
                           )
                   ) {
                    Agency_Contact__c acObj = new Agency_Contact__c(Agency_ID__c = '000000000000000'
                            , Contact__c          = nObj.Id
                                                    , ContactId18__c      = nObj.Id
                                                            , Agency_Hospital__c  = null
                                                                    , Name                = nObj.LastName + ((String.isBlank(nObj.FirstName) == false) ? ' ' + nObj.FirstName : '')
                                                                            , Department_Class__c = nObj.Strategic_dept_Class__c
                                                                                    , Type__c             = nObj.Type__c
                                                                                            , Doctor_Division1__c = nObj.Doctor_Division1__c
                                                                   );
                    targetContactMap.put(nObj.Id, acObj);
                }
            }
        }
        if (targetContactMap.size() > 0) {
            upsert targetContactMap.values() ContactId18__c;
        }
    }

    private void syncToAgencyContactDelete() {
        List<Id> cIdList = new List<Id>();
        for (Contact oObj : oldList) {
            cIdList.add(oObj.Id);
        }
        if (cIdList.size() > 0) {
            List<Agency_Contact__c> acList = [Select Id From Agency_Contact__c
                                              Where Contact__c = :null and Agency_ID__c = '000000000000000'];
            if (acList.size() > 0) {
                delete acList;
            }
        }
    }

    //更新经销商用户人数字段 精琢技术 pk 2021-08-26 start
    private void updateDealerNum(){
        Set<Id> accountSet = new Set<Id>();
        Map<Id,Account> acMap = new Map<Id,Account>();
            if(Trigger.isUpdate){
               for(Contact contactnew : newList){
                    if(contactnew.Agency_User__c != oldMap.get(contactnew.Id).Agency_User__c || (System.Label.onlyUpdate == '1' && UserInfo.getUserId() == '00510000005sEEMAA2')){
                        accountSet.add(contactnew.AccountId);
                    }
               }
            }

            if(Trigger.isInsert){
                for(Contact contactnew : newList){
                    if(contactnew.Agency_User__c){
                        accountSet.add(contactnew.AccountId);
                    }
                }
            }
        
        
        if(Trigger.isDelete){
            for(Contact contactold : oldList){
                if(contactold.Agency_User__c){
                    accountSet.add(contactold.AccountId);
                }
            }
        }
       
        if(accountSet.size()>0){
            List<AggregateResult> contactList = [select count(id) ctn ,AccountId accid from Contact where Agency_User__c = true and AccountId = :accountSet and RecordTypeId = '01210000000QfWi' group by AccountId];
            for(AggregateResult ar : contactList){
                String accid = (String)ar.get('accid');
                Account account = new Account();
                account.id = accid;
                account.Dealer_Num__c = (Integer)ar.get('ctn');
                acMap.put(accid, account);
            }

            for (Id accountId : accountSet) {
                if (!acMap.containsKey(accountId)) {
                    Account account = new Account();
                    account.id = accountId;
                    account.Dealer_Num__c = 0;
                    acMap.put(accountId, account);
                }
            }
            
            if(acMap.size() > 0){
              update acMap.values();
            }
        }


    }
     //更新经销商用户人数字段 精琢技术 pk 2021-08-26 end
}