public without sharing class AssetHandlerMEBG extends Oly_TriggerHandler {

    private Map<Id, Asset> newMap;
    private Map<Id, Asset> oldMap;
    private List<Asset> newList;
    private List<Asset> oldList;
    // @TestVisible private static Set<String> testTargetDepts;
    // @TestVisible private static Id Account_Asset_Id;
    // public static Boolean disabled = false;

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

    protected override void beforeInsert() {

        assetImageBeforeTrigger();

        assetRecordTypeUpd();

    }
    protected override void beforeUpdate() {

            assetHpDeptUpd();

            assetImageBeforeTrigger();

            assetRecordTypeUpd();
        
    }

    protected override void beforeDelete() {

            assetRecordTypeUpd();
        
    }

    private void assetHpDeptUpd() {

        List<String> accIds = new List<String>();

        for(Asset a : newList) {
            Asset olda = oldMap.get(a.Id);
            if (olda.AccountId != a.AccountId
                    || a.AccountParentId__c != a.Department_Class__c
                    || a.AccountParentParentId__c != a.Hospital__c) {
                if (!String.isBlank(a.AccountId)) {
                    accIds.add(a.AccountId);
                }
            }
        }

        if (accIds.size() > 0) {
            // 診療科レコードタイプ
            String[] deptTypes = new String[] {'病院', '診療科 その他', '診療科 呼吸科', '診療科 婦人科', '診療科 普外科', '診療科 泌尿科', '診療科 消化科', '診療科 耳鼻喉科'};
            List<RecordType> deptRects = [select Id, Name from RecordType where IsActive = true and SobjectType = 'Account' and Name IN :deptTypes];
            Map<String, String> deptRectMap = new Map<String, String>();
            for (RecordType rect : deptRects) {
                deptRectMap.put(rect.Id, rect.Name);
            }
            // TODO 販売店のレコードタイプのMapを生成

            Map<Id, Account> accMap = new Map<Id, Account>();
            List<Account> accs = ControllerUtil.selectAccountForTrigger(accIds);
            for(Account acc : accs) {
                accMap.put(acc.Id, acc);
            }
            
            for(Asset a : newList) {
                // 「診療科」に診療科を選択する場合
                Account acc = accMap.get(a.AccountId);
                if (acc != null
                        && deptRectMap.get(acc.RecordTypeId) != null
                        && acc.Management_Code__c != '9999900'
                ) {
                    if (deptRectMap.get(acc.RecordTypeId) == '病院') {
                        a.Department_Class__c = null;
                        a.Hospital__c = acc.Id;
                    } else {
                        a.Department_Class__c = acc.ParentId;
                        a.Hospital__c = acc.Parent.ParentId;
                    }
                }
                // TODO 「販売店」の更新
            }
        }
    }

    private void assetImageBeforeTrigger(){

        if (StaticParameter.EscapeVMCTrigger) {
        return ;
        }
        if (trigger.isBefore) {
            for(Asset newS : newList) {
                if (Trigger.isUpdate && newS.Status == '使用中'
                        && String.isBlank(((Asset) Trigger.oldMap.get(newS.Id)).ImageAsset__c)
                        && !String.isBlank(newS.ImageAsset__c)
                ) {
                    newS.ImageAssetUploadedTime__c = Datetime.now();
                    newS.ImageAssetUploadedBy__c = UserInfo.getUserId();
                }
                if (Trigger.isUpdate && newS.Status == '使用中'
                            && String.isBlank(((Asset) Trigger.oldMap.get(newS.Id)).ImageSerial__c)
                        && !String.isBlank(newS.ImageSerial__c)
                ) {
                    newS.ImageSerialUploadedTime__c = Datetime.now();
                    newS.ImageSerialUploadedBy__c = UserInfo.getUserId();
                }

                 System.debug('-------->Start');
                if(Trigger.isUpdate && !String.isBlank(((Asset)Trigger.oldMap.get(newS.Id)).Reson_Can_not_Warranty__c)){
                    String reason = ((Asset)Trigger.oldMap.get(newS.Id)).Reson_Can_not_Warranty__c;

                    System.debug('oldreason'+reason);
                    System.debug('reason'+newS.Reson_Can_not_Warranty__c);
                    System.debug('Asset_Owner__c'+newS.Asset_Owner__c);
                    if(newS.Asset_Owner__c != '病院資産'){
                        if(newS.Reson_Can_not_Warranty__c != null){
                            if(!newS.Reson_Can_not_Warranty__c.contains('备品')){
                                // newS.Reson_Can_not_Warranty__c = reason + '备品';
                                newS.Reson_Can_not_Warranty__c = newS.Reson_Can_not_Warranty__c + '备品';
                            }
                        }else{
                            newS.Reson_Can_not_Warranty__c = '备品';
                        }
                        
                    }else{
                        if(newS.Reson_Can_not_Warranty__c != null){
                            if(newS.Reson_Can_not_Warranty__c.contains('备品')){
                                //newS.Reson_Can_not_Warranty__c = reason.replace('备品', '');
                                newS.Reson_Can_not_Warranty__c = newS.Reson_Can_not_Warranty__c.replace('备品', '');
                            }
                        }
                    }
                    if(newS.Final_Examination_Date__c != null){
                        if(Date.today().addDays(-90) > newS.Final_Examination_Date__c){
                            if(!reason.contains('点检')){
                                newS.Reson_Can_not_Warranty__c = reason + '点检';
                            }
                        }else{
                            if(reason.contains('点检')){
                                newS.Reson_Can_not_Warranty__c = reason.replace('点检', '');
                            }
                        }
                    }else{
                        if(reason.contains('点检')){
                            newS.Reson_Can_not_Warranty__c = reason.replace('点检', '');
                        }
                    }
                    
                }else if(Trigger.isInsert || Trigger.isUpdate && String.isBlank(((Asset)Trigger.oldMap.get(newS.Id)).Reson_Can_not_Warranty__c)){
                    if(newS.Asset_Owner__c != '病院資産'){
                        newS.Reson_Can_not_Warranty__c = '备品';
                    }else{
                        if(newS.Reson_Can_not_Warranty__c != null){
                            if(newS.Reson_Can_not_Warranty__c.contains('备品')){
                                //newS.Reson_Can_not_Warranty__c = reason.replace('备品', '');
                                newS.Reson_Can_not_Warranty__c = newS.Reson_Can_not_Warranty__c.replace('备品', '');
                            }
                        }
                    }
                    if(newS.Final_Examination_Date__c != null){
                        if(Date.today().addDays(-90) > newS.Final_Examination_Date__c){
                            newS.Reson_Can_not_Warranty__c = '点检';
                        }
                    }

                }
                System.debug('-------->End');
            }
        }
    }

    private void assetRecordTypeUpd(){

        if (StaticParameter.EscapeVMCTrigger) {
        return ;
        }
        //add by gzw 20210729 end
        List<String> cdList = new List<String>();
        if (trigger.isBefore && (trigger.isInsert || trigger.isUpdate)) {
            for(Asset ass : newList) {
                ass.RecordTypeID__c = ass.RecordTypeId;
                // 注残设置
                if (!String.isBlank(ass.Order_No__c) && ass.Backorder__c == null) {
                    cdList.add(ass.Order_No__c);
                }

                // HWAG-AWLAU6 2018/3/7 "是否多年保修"的值拷贝到"是否多年保修（文本）"中
                if (trigger.isUpdate && ((Asset)Trigger.oldMap.get(ass.Id)).IS_Extend_Gurantee_Txt__c != ass.IS_Extend_Gurantee_Txt__c) {
                    ass.Extend_Gurantee_Txt_Manual__c = true;
                } else {
                    if (ass.IS_Extend_Gurantee__c != ass.IS_Extend_Gurantee_Txt__c && ass.Extend_Gurantee_Txt_Manual__c == false) {
                        ass.IS_Extend_Gurantee_Txt__c = ass.IS_Extend_Gurantee__c;
                    }
                }
            }
        }

        if (cdList.size() > 0) {
            List<Statu_Achievements__c> saList = [select Id, Name, ContractNO__c from Statu_Achievements__c where ContractNO__c IN : cdList AND Valid_Statu_Achievements__c = 1];
            if (saList != null && saList.size() > 0) {
                Map<String, String> saMap = new Map<String, String>();
                for (Statu_Achievements__c sa : saList) {
                    saMap.put(sa.ContractNO__c, sa.Id);
                }
                for (Asset a : newList) {
                    for (String s : saMap.keySet()) {
                        if (a.Order_No__c == s) {
                            a.Backorder__c = saMap.get(s);
                        }
                    }
                }
            }
        }

        if (trigger.isBefore && trigger.isDelete) {
            cdList = new List<String>();
            Map<String, String> delMap = new Map<String, String>();
            for (Asset delId : oldList) {
                cdList.add(delId.Id);
            }
            if (cdList.size() > 0) {
                List<AggregateResult> mcList = [select Max(Id) Id, Asset__c 
                            from Maintenance_Contract_Asset__c  where Asset__c In : cdList group by Asset__c];
                List<AggregateResult> reList = [select Max(id) Id, Delivered_Product__c from Repair__c 
                            where Status1__c != '0.删除' and Delivered_Product__c In : cdList group by Delivered_Product__c];
                List<AggregateResult> qisList = [select Max(Id) Id, nonyushohin__c from QIS_Report__c 
                            where nonyushohin__c In : cdList group by nonyushohin__c];
                if (mcList != null && mcList.size() > 0) {
                    for (AggregateResult mc : mcList) {
                        delMap.put(String.valueOf(mc.get('Asset__c')), String.valueOf(mc.get('Asset__c')));
                    }
                }
                if (reList != null && reList.size() > 0) {
                    for (AggregateResult re : reList) {
                        delMap.put(String.valueOf(re.get('Delivered_Product__c')), String.valueOf(re.get('Delivered_Product__c')));
                    }
                }
                if (qisList != null && qisList.size() > 0) {
                    for (AggregateResult qis : qisList) {
                        delMap.put(String.valueOf(qis.get('nonyushohin__c')), String.valueOf(qis.get('nonyushohin__c')));
                    }
                }
            }
            for (Asset adel : oldList) {
                if (delMap.containsKey(adel.Id)) {
                     adel.addError('该设备存在维修合同、修理或QIS，不能删除。');
                }
            }
        }

    }
    
}