public without sharing class AttachmentTriggerHandler {

    public static void fileCheck(List<Attachment> newList, Map<Id, Attachment> newMap, List<Attachment> oldList, Map<Id, Attachment> oldMap) {
        List<String> orderIdList = new List<String>();
        List<String> orderIdList2 = new List<String>();
        for (Attachment newAtt : newList) {
            String parentId = newAtt.parentId;
            String name = newAtt.Name;
            if (parentId.startsWith('801') && name.startsWith('ORDER-')) {
                orderIdList.add(newAtt.parentId);
            }
            if (parentId.startsWith('801')) {
                orderIdList2.add(newAtt.parentId);
            }
        }

        Map<String, String> isUploadMap = new Map<String, String>();
        Map<String, String> draftMap = new Map<String, String>();
        Map<String, String> submitMap = new Map<String, String>();
        Map<String, String> passMap = new Map<String, String>();
        if (orderIdList.size() > 0) {
            List<Order> orderList = [select id,IsUpload__c,ApproveStatus__c from Order where id = :orderIdList];
            for (Order o : orderList) {
                if (o.IsUpload__c) {
                    isUploadMap.put(o.Id, o.Id);
                }
                if (o.ApproveStatus__c == 'Draft' || o.ApproveStatus__c == 'Completed' || o.ApproveStatus__c == 'Reject') {
                    draftMap.put(o.Id, o.Id);
                }
            }
        }
        if (orderIdList2.size() > 0) {
            List<Order> orderList2 = [select id,IsUpload__c,ApproveStatus__c,IsOrderPassed__c from Order where id = :orderIdList2];
            for (Order o : orderList2) {
                if (o.ApproveStatus__c == 'Submit' || o.ApproveStatus__c == 'OrderSubmit') {
                    submitMap.put(o.Id, o.Id);
                }
                if (o.IsOrderPassed__c) {
                    passMap.put(o.Id, o.Id);
                }
            }
        }
        //新的获取人员简档ID 获取到的ID是15位
        // String profileId = UserInfo.getProfileId().substring(0, 15);
        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
        for (Attachment newAtt : newList) {
//            if (UserInfo.getProfileId() != System.Label.SystemAdmin && passMap.containsKey(newAtt.parentId)
//                && UserInfo.getProfileId() != System.Label.Business_department) {
//                newAtt.addError('合同批准后不能更改附件。');
//            }
             
            if (new_profileId != System.Label.Business_department && new_profileId != System.Label.SystemAdmin 
                && submitMap.containsKey(newAtt.parentId)) {
                newAtt.addError('合同被锁定，不能上传附件。');
            }
            if (isUploadMap.containsKey(newAtt.parentId)) {
                newAtt.addError('合同附件已经存在，不能上传多个。');
            }
            if (draftMap.containsKey(newAtt.parentId)) {
                newAtt.addError('请先审批完特殊条件再提交合同文件。');
            }
        }
    }
    //禁止上传多个收货确认单和装机确认单
    public static void fileCheck5(List<Attachment> newList, Map<Id, Attachment> newMap, List<Attachment> oldList, Map<Id, Attachment> oldMap) {
        List<String> lacIdList1 = new List<String>();
        List<String> lacIdList2 = new List<String>();
        List<String> lacIdList3 = new List<String>();
        List<String> lacIdList4 = new List<String>();
        for (Attachment newAtt : newList) {
            String parentId = newAtt.parentId;
            String name = newAtt.Name;
            if (parentId.startsWith('a0Q') && name.startsWith('收货确认-')) {
                lacIdList1.add(newAtt.parentId);
            }
            if(parentId.startsWith('a0Q') && name.startsWith('装机确认')){
                lacIdList2.add(newAtt.parentId);
            }
            if(parentId.startsWith('a0Q') && (name.startsWith('借用协议') || name.startsWith('借用单') || name.startsWith('DeliveryConfirmPDF'))){
                lacIdList3.add(newAtt.parentId);
            }
            if(parentId.startsWith('a0Q') && name.startsWith('转借确认')){
                lacIdList4.add(newAtt.parentId);
            }

        }
        Map<String,String> isUploadMap1 = new Map<String,String>();
        Map<String,String> isUploadMap2 = new Map<String,String>();
        Map<String,String> isUploadMap3 = new Map<String,String>();
        Map<String,String> isUploadMap4 = new Map<String,String>();
        if(lacIdList1.size()>0){
            List<loaner_application__c> lacList1 = [select id,Receipt_Attachment__c from loaner_application__c where id = :lacIdList1];
            for(loaner_application__c lac :lacList1){
                if(lac.Receipt_Attachment__c){
                    isUploadMap1.put(lac.Id, lac.Id);
                }
            }
        }
        if(lacIdList2.size()>0){
            List<loaner_application__c> lacList2 = [select id,Installation_Qualification_Attachment__c from loaner_application__c where id = :lacIdList2];
            for(loaner_application__c lac : lacList2){
                if(lac.Installation_Qualification_Attachment__c){
                    isUploadMap2.put(lac.Id, lac.Id);
                }
            }
        }
        if(lacIdList3.size()>0){
            List<loaner_application__c> lacList3 = [select id,Loaner_AgreementPDF__c from loaner_application__c where id = :lacIdList3];
            for(loaner_application__c lac : lacList3){
                if(lac.Loaner_AgreementPDF__c){
                    isUploadMap3.put(lac.Id, lac.Id);
                }
            }
        }
        if(lacIdList4.size()>0){
            List<loaner_application__c> lacList4 = [select id,Loaner_Confirm_Photo__c from loaner_application__c where id = :lacIdList4];
            for(loaner_application__c lac : lacList4){
                if(lac.Loaner_Confirm_Photo__c){
                    isUploadMap4.put(lac.Id, lac.Id);
                }
            }
        }
        for(Attachment newAtt : newList){
            if(isUploadMap1.containsKey(newAtt.parentId)){
                newAtt.addError('收货确认附件已经存在，不能上传多个。');
            }
            if(isUploadMap2.containsKey(newAtt.parentId)){
                newAtt.addError('装机确认附件已经存在，不能上传多个。');
            }
            if(isUploadMap3.containsKey(newAtt.parentId)){
                newAtt.addError('借用协议附件已经存在，不能上传多个。');
            }
            if(isUploadMap4.containsKey(newAtt.parentId)){
                newAtt.addError('转借确认附件已经存在，不能上传多个。');
            }
        }

    }
    //装机确认后,禁止删除确认单
    public static void fileCheck6(List<Attachment> newList, Map<Id, Attachment> newMap, List<Attachment> oldList, Map<Id, Attachment> oldMap) {

        List<String> lacIdList = new List<String>();
        List<String> lacIdList1 = new List<String>();
        for(Attachment oldAtt : oldList){
            String parentId = oldAtt.parentId;
            String name = oldAtt.Name;
            if(parentId.startsWith('a0Q') && name.startsWith('装机确认')){
                lacIdList.add(parentId);
            }
            if(parentId.startsWith('a0Q') && (name.startsWith('借用协议') || name.startsWith('借用单') || name.startsWith('DeliveryConfirmPDF'))){
                lacIdList1.add(parentId);
            }
        }

        Map<String,String> deleteMap = new Map<String,String>();
        Map<String,String> deleteMap1 = new Map<String,String>();
        if(lacIdList.size()>0){
            List<loaner_application__c> lacList = [select id,HP_Received_Sign_Date__c from loaner_application__c where id = :lacIdList];
            for(loaner_application__c lac : lacList){
                if(lac.HP_Received_Sign_Date__c != null){
                    deleteMap.put(lac.id,lac.id);
                }
            }
        }
        if(lacIdList1.size() >0 ){
            List<loaner_application__c> lacList1 = [select id,Bollow_Date__c from loaner_application__c where id = :lacIdList1];
            for(loaner_application__c lac: lacList1){
                if(lac.Bollow_Date__c != null){
                    deleteMap1.put(lac.id,lac.id);
                }
            }
        }
        for(Attachment oldAtt : oldList){
            if(deleteMap.containsKey(oldAtt.parentId)){
                oldAtt.addError('已装机确认,不能删除装机确认附件');
            }
            if(deleteMap1.containsKey(oldAtt.parentId)){
                oldAtt.addError('已出库指示,不能删除借用协议附件');
            }
        }

    }

    public static void uploadContract(List<Attachment> newList, Map<Id, Attachment> newMap, List<Attachment> oldList, Map<Id, Attachment> oldMap) {
        List<Order> orderList = new List<Order>();
       
        for (Attachment newAtt : newList) {
            String parentId = newAtt.parentId;
            String name = newAtt.Name;
            if (parentId.startsWith('801') && name.startsWith('ORDER-')) {
                Order ord = new Order();
                ord.Id = parentId;
                //ord.Name = name.substring(6, name.indexOf('.'));
                ord.Upload_IsChanged__c = true;
                ord.IsUpload__c = true;

                orderList.add(ord);
            }
        }

        if (orderList.size() > 0) {
            update orderList;
        }

    }

    // Added by HANCHAO 20170123
    public static void AfterPassUpload(List<Attachment> newList, Map<Id, Attachment> newMap, List<Attachment> oldList, Map<Id, Attachment> oldMap) {
        List<Order> orderList = new List<Order>();

        for (Attachment newAtt : newList) {
            String parentId = newAtt.parentId;
            if (parentId.startsWith('801')) {
                Order ord1 = [select id,IsUpload__c,ApproveStatus__c,IsOrderPassed__c from Order where id = :parentId];
                if (ord1.IsOrderPassed__c) {
                    Order ord = new Order();
                    ord.Id = parentId;
                    ord.AfterPassAttachmentUpload__c = true;
                    orderList.add(ord);
                }
            }
        }

        if (orderList.size() > 0) {
            update orderList;
        }

    }
    //添加确认单时添加对应标记
    public static void fileCheck4(List<Attachment> newList, Map<Id, Attachment> newMap, List<Attachment> oldList, Map<Id, Attachment> oldMap){

        List<loaner_application__c> lacList = new List<loaner_application__c>();

        for (Attachment newAtt : newList) {
            String parentId = newAtt.parentId;
            String name = newAtt.Name;
            //判断是否上传收货确认附件和安装确认附件
            if(parentId.startsWith('a0Q')){
                if(name.startsWith('收货确认-')){
                    loaner_application__c lac = new loaner_application__c();
                    lac.id = parentId;
 //                    [select id,Receipt_Attachment__c from loaner_application__c where id = :parentId];
                    lac.Receipt_Attachment__c = true;
                    lacList.add(lac);
                }
                if(name.startsWith('装机确认')){
                    loaner_application__c lac =new loaner_application__c();
                    lac.id = parentId;
 //                   [select id,Installation_Qualification_Attachment__c from loaner_application__c where id = :parentId];
                    lac.Installation_Qualification_Attachment__c = true;
                    lacList.add(lac);  
                }
                if(name.startsWith('借用协议') || name.startsWith('借用单') || name.startsWith('DeliveryConfirmPDF')){
                    loaner_application__c lac = new loaner_application__c();
                    lac.id = parentId;
                    lac.Loaner_AgreementPDF__c = true;
                    lacList.add(lac);
                }
                 if(name.startsWith('转借确认')){
                    loaner_application__c lac = new loaner_application__c();
                    lac.id = parentId;
                    lac.Loaner_Confirm_Photo__c = true;
                    lacList.add(lac);
                }
            }
        }


        if(lacList.size() > 0){
            try{
                update lacList;
            }catch(Exception ex){
                newList[0].addError(ex.getMessage().mid((ex.getMessage().indexOf('first error:') + 12),ex.getMessage().length()));
            }
        }

    }

    public static void fileCheck2(List<Attachment> newList, Map<Id, Attachment> newMap, List<Attachment> oldList, Map<Id, Attachment> oldMap) {
        List<String> orderIdList = new List<String>();

        for (Attachment oldAtt : oldList) {
            String parentId = oldAtt.parentId;
            if (parentId.startsWith('801')) {
                orderIdList.add(oldAtt.parentId);
            }
        }

        Map<String, String> submitMap = new Map<String, String>();
        Map<String, Order> passMap = new Map<String, Order>();

        if (orderIdList.size() > 0) {
            List<Order> orderList = [select id,IsUpload__c,ApproveStatus__c,IsOrderPassed__c, Is_Already_Splited__c from Order where id = :orderIdList];
            for (Order o : orderList) {
                if (o.ApproveStatus__c == 'Submit' || o.ApproveStatus__c == 'OrderSubmit') {
                    submitMap.put(o.Id, o.Id);
                }
                if (o.IsOrderPassed__c) {
                    passMap.put(o.Id, o);
                }
            }
        }
        //新的获取人员简档ID 获取到的ID是15位
        // String profileId = UserInfo.getProfileId().substring(0, 15);
        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
        for (Attachment oldAtt : oldList) {
            /*if (UserInfo.getProfileId() != System.Label.SystemAdmin && submitMap.containsKey(oldAtt.parentId)) {
                oldAtt.addError('合同被锁定，不能更改附件。');
            }
            if (UserInfo.getProfileId() != System.Label.SystemAdmin && passMap.containsKey(oldAtt.parentId)
                && UserInfo.getProfileId() != System.Label.Business_department && passMap.get(oldAtt.parentId).Is_Already_Splited__c == false) {
                oldAtt.addError('合同批准后不能更改附件。');
            }*/
            if (new_profileId != System.Label.SystemAdmin
                && submitMap.containsKey(oldAtt.parentId)) {
                oldAtt.addError('合同被锁定，不能更改附件。');
            }
            if (new_profileId != System.Label.SystemAdmin && passMap.containsKey(oldAtt.parentId)
                && new_profileId != System.Label.Business_department && passMap.get(oldAtt.parentId).Is_Already_Splited__c == false) {
                oldAtt.addError('合同批准后不能更改附件。');
            }
        }
    }

    public static void fileCheck3(List<Attachment> newList, Map<Id, Attachment> newMap, List<Attachment> oldList, Map<Id, Attachment> oldMap) {
        List<String> orderIdList = new List<String>();

        for (Attachment newAtt : newList) {
            String parentId = newAtt.parentId;
            if (parentId.startsWith('801')) {
                orderIdList.add(newAtt.parentId);
            }
        }

        Map<String, String> submitMap = new Map<String, String>();
        Map<String, Order> passMap = new Map<String, Order>();

        if (orderIdList.size() > 0) {
            List<Order> orderList = [select id,IsUpload__c,ApproveStatus__c,IsOrderPassed__c, Is_Already_Splited__c from Order where id = :orderIdList];
            for (Order o : orderList) {
                if (o.ApproveStatus__c == 'Submit' || o.ApproveStatus__c == 'OrderSubmit') {
                    submitMap.put(o.Id, o.Id);
                }
                if (o.IsOrderPassed__c) {
                    passMap.put(o.Id, o);
                }
            }
        }
        //新的获取人员简档ID 获取到的ID是15位
        // String profileId = UserInfo.getProfileId().substring(0, 15);
        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
        /*for (Attachment newAtt : newList) {
            if (UserInfo.getProfileId() != System.Label.SystemAdmin && submitMap.containsKey(newAtt.parentId)) {
                newAtt.addError('合同被锁定，不能更改附件。');
            }
            if (UserInfo.getProfileId() != System.Label.SystemAdmin && passMap.containsKey(newAtt.parentId)
                && UserInfo.getProfileId() != System.Label.Business_department && passMap.get(newAtt.parentId).Is_Already_Splited__c == false) {
                newAtt.addError('合同批准后不能更改附件。');
            }
        }*/
        for (Attachment newAtt : newList) {
            if (new_profileId != System.Label.SystemAdmin  
                && submitMap.containsKey(newAtt.parentId)) {
                newAtt.addError('合同被锁定，不能更改附件。');
            }
            if (new_profileId != System.Label.SystemAdmin && passMap.containsKey(newAtt.parentId)
                && new_profileId != System.Label.Business_department && passMap.get(newAtt.parentId).Is_Already_Splited__c == false) {
                newAtt.addError('合同批准后不能更改附件。');
            }
        }
    }

    public static void deleteContract(List<Attachment> newList, Map<Id, Attachment> newMap, List<Attachment> oldList, Map<Id, Attachment> oldMap) {
        List<Order> orderList = new List<Order>();

        for (Attachment oldAtt : oldList) {
            String parentId = oldAtt.parentId;
            String name = oldAtt.Name;
            if (parentId.startsWith('801') && name.startsWith('ORDER-')) {
                Order ord = new Order();
                ord.Id = parentId;
                //ord.Name = '';
                ord.Upload_IsChanged__c = true;
                ord.IsUpload__c = false;

                orderList.add(ord);
            }
        }

        if (orderList.size() > 0) {
            update orderList;
        }
    }

    //删除确认单时取消对应标记;
    public static void deleteconfirm(List<Attachment> newList, Map<Id, Attachment> newMap, List<Attachment> oldList, Map<Id, Attachment> oldMap){
        List<loaner_application__c> lacList = new List<loaner_application__c>();

        for (Attachment oldAtt : oldList) {
            String parentId = oldAtt.parentId;
            String name = oldAtt.Name;
            //判断是否删除收货确认附件和安装确认附件
            if(parentId.startsWith('a0Q')){
                if(name.startsWith('收货确认-')){
                    loaner_application__c lac = new loaner_application__c();
                    lac.id = parentId;
//                    [select id,Receipt_Attachment__c from loaner_application__c where id = :parentId];
                    lac.Receipt_Attachment__c = false;
                    lacList.add(lac);
                }
                if(name.startsWith('装机确认')){
                    loaner_application__c lac = new loaner_application__c();
                    lac.id = parentId;
//                    [select id,Installation_Qualification_Attachment__c from loaner_application__c where id = :parentId];
                    lac.Installation_Qualification_Attachment__c = false;
                    lacList.add(lac);  
                }
                if(name.startsWith('借用协议') || name.startsWith('借用单') || name.startsWith('DeliveryConfirmPDF')){
                    loaner_application__c lac = new loaner_application__c();
                    lac.id = parentId;
                    lac.Loaner_AgreementPDF__c = false;
                    lacList.add(lac);
                }
                if(name.startsWith('转借确认')){
                    loaner_application__c lac = new loaner_application__c();
                    lac.id = parentId;
                    lac.Loaner_Confirm_Photo__c = false;
                    lacList.add(lac);
                }
            }
        }
        if(lacList.size() > 0){
            update lacList;
        }        
    }

    //业务活动上传附件完成之后将附件克隆至相关联的用户信息上面
    public static void AfterUploadToUserFaultInfo(List<Attachment> newList, Map<Id, Attachment> newMap, List<Attachment> oldList, Map<Id, Attachment> oldMap) {
        List<String> selectBAIdList = new List<String>();
        String firstThreeDigitCode= System.label.FirstThreeDigitCode;
        for (Attachment newAtt : newList) {
            String parentId = newAtt.parentId;
            if (parentId.startsWith(firstThreeDigitCode)) {
                selectBAIdList.add(parentId);
            }
        }
        
        if (selectBAIdList.size() > 0) {
            List<BusinessActivity__c> businessActivityList = TSRepairUtil.GetBusinessActivityList(null,null, selectbaIdList,null,null,'');

            String userFaultInfoId = businessActivityList[0].User_FaultInfo__c;
            System.debug('userFaultInfoId---->'+userFaultInfoId);
            if (String.isNotBlank(userFaultInfoId)) {
                    
                    // 获取用户/故障信息的附件
                    List<String> selectUfIdList = new List<String>();
                    selectUfIdList.add(userFaultInfoId);
                    List<Attachment> ufAttachmentList = TSRepairUtil.GetAttachmentList(selectUfIdList);

                    if (ufAttachmentList.size() >0){
                        //删除用户/故障信息的附件
                        delete ufAttachmentList;
                        
                    }

                    //将业务活动下的附件克隆至 用户/故障信息
                    TSRepairUtil.insertattachmentCloneList(selectBAIdList,userFaultInfoId);
                    
                }

        }
    }
    //王鹏伟 贸易管理客户申请表 合同已提交 不允许修改贸易管理客户申请表附件 
    public static void updateTradeCustomerManagerFile(List<Attachment> newList, Map<Id, Attachment> newMap, List<Attachment> oldList, Map<Id, Attachment> oldMap){
        for(Attachment accach : newList){
            String parentId = accach.parentId;
            String tradeCustomerManagerStart = System.label.TradeCustomerManagerStart;
            if(parentId.startsWith(tradeCustomerManagerStart)){
                TradeCustomerManager__c trade = [select Id,order__c,isHaveLink__c from TradeCustomerManager__c where Id =: parentId];
                if(trade!=null){
                    Order order = [select Id,applicationForm__c,ApproveStatus__c from Order where id=:trade.order__c];
                    if(order !=null){
                        if(order.ApproveStatus__c == 'OrderPass' || order.ApproveStatus__c == 'OrderSubmit'){
                            accach.addError('合同已提交，申请表附件不可修改！');
                            return;
                        }
                    }
                }
            }
        }
    }
    //王鹏伟判断是否是 贸易管理客户申请表 下的文件 如果是
    public static void DeleteTradeCustomerManagerFile(List<Attachment> newList, Map<Id, Attachment> newMap, List<Attachment> oldList, Map<Id, Attachment> oldMap){
        for(Attachment accach : oldList){
            String parentId = accach.parentId;
            String tradeCustomerManagerStart = System.label.TradeCustomerManagerStart;
            if(parentId.startsWith(tradeCustomerManagerStart)){
                TradeCustomerManager__c trade = [select Id,order__c,isHaveLink__c from TradeCustomerManager__c where Id =: parentId];
                if(trade!=null){
                    Order order = [select Id,applicationForm__c,ApproveStatus__c from Order where id=:trade.order__c];
                    if(order!=null){
                        if(order.ApproveStatus__c == 'OrderPass' || order.ApproveStatus__c == 'OrderSubmit'){
                            accach.addError('合同已提交，申请表附件不可删除！');
                            return;
                        }
                        if(order!=null &&(accach.Name.startsWith('军事')||(accach.Name.startsWith('个人信息') && trade.isHaveLink__c == '是'))){
                            order.applicationForm__c = false;
                            update order;
                        }
                    }
                }
            }
        }
    }
    //王鹏伟新加判断  贸易管理客户申请表 一个申请表下只能有一份文件名以军事或个人信息开头的文件！
    public static void UploadTradeCustomerManagerFile(List<Attachment> newList, Map<Id, Attachment> newMap, List<Attachment> oldList, Map<Id, Attachment> oldMap){
         for(Attachment accach : newList){
            String parentId = accach.parentId;
            String tradeCustomerManagerStart = System.label.TradeCustomerManagerStart;
            if(parentId.startsWith(tradeCustomerManagerStart)){
                List<Attachment> fileList = [select Id,Name from Attachment where ParentId =:parentId];
                if(fileList!=null && fileList.size()!=0){
                    for(Attachment acc : fileList){
                        if(acc.Name.substring(0,2).equals('军事') && accach.Name.startsWith('军事')){
                            accach.addError('一个贸易管理客户申请表下，只能有一份文件名以军事开头的文件！');
                            return;
                        }
                        if(acc.Name.startsWith('个人信息') && accach.Name.startsWith('个人信息')){
                            accach.addError('一个贸易管理客户申请表下，只能有一份文件名以个人开头的文件！');
                            return;
                        }
                    }
                }
            }
        }
    }
}