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

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

    protected override void beforeInsert() {
    }

    protected override void beforeUpdate() {
    }

    protected override void afterUpdate() {
        sendEmail();
    }
    @Future
    // 由于handler更新自己表中字段，只好加@future保证workflow正常执行
    // 正常发mail的时，需要有mail内容和更新时间两个字段，根据时间的变化触发workflow发送mail内容
    private static void sendRejectEmail(Set<Id> needSendEmailSet){
        List<ReceivingNoteDetail__c> rndList = [
               SELECT Id
                    , ReceivingNote__c
                    , Fixture_Model_No_F__c
                    , Reject_Reason__c
                    , Reject_Time__c
                    , DataConfirmationAgain__c
                 FROM ReceivingNoteDetail__c
                WHERE ReceivingNote__c = :needSendEmailSet
                  AND Delete_Flag__c = false
                  AND Change_Point__c != '删除'
                ORDER BY ReceivingNoteDetailNo__c];
        if (rndList.size() > 0) {
            List<ReceivingNote__c> rnmList = new List<ReceivingNote__c>();
            List<ReceivingNote__c> rnmList1 = new List<ReceivingNote__c>();
            String oRnId = '';
            String message = '';
            for (ReceivingNoteDetail__c rnd : rndList) {
                if (String.isBlank(oRnId)) {
                    oRnId = rnd.ReceivingNote__c;
                }
                if (oRnId != rnd.ReceivingNote__c) {
                    ReceivingNote__c rn1 = new ReceivingNote__c(Id = oRnId, Reject_ReceivingNoteDetail_Email_Text__c = null);
                    ReceivingNote__c rn2 = new ReceivingNote__c(Id = oRnId, Reject_ReceivingNoteDetail_Email_Text__c = message);
                    rnmList.add(rn1);
                    rnmList1.add(rn2);
                    message = '';
                }
                oRnId = rnd.ReceivingNote__c;
                if(rnd.Reject_Time__c != null && rnd.DataConfirmationAgain__c == false){
                    message += rnd.Fixture_Model_No_F__c + '\t' + rnd.Reject_Reason__c + '\n';
                }
            }
            if (String.isNotBlank(oRnId)) {
                ReceivingNote__c rn1 = new ReceivingNote__c(Id = oRnId, Reject_ReceivingNoteDetail_Email_Text__c = null);
                ReceivingNote__c rn2 = new ReceivingNote__c(Id = oRnId, Reject_ReceivingNoteDetail_Email_Text__c = message);
                rnmList.add(rn1);
                rnmList1.add(rn2);
            }
            update rnmList;
            update rnmList1;
        }
    }

    @Future
    // 由于handler更新自己表中字段，只好加@future保证workflow正常执行
    // 正常发mail的时，需要有mail内容和更新时间两个字段，根据时间的变化触发workflow发送mail内容
    private static void sendAcceptNGEmail(Set<Id> needSendEmailSet){
        List<ReceivingNoteDetail__c> rndList = [
               SELECT Id
                    , ReceivingNoteSummary__c
                    , Change_Point__c
                    , ReceivingNote__c
                    , Fixture_Model_No_F__c
                    , AcceptanceResult__c
                    , AcceptanceComments__c
                    , ReceivingNoteSummary__r.Fixture_Model_No_F__c
                    , AcceptanceTime__c
                    , DataConfirmation__c 
                 FROM ReceivingNoteDetail__c
                WHERE ReceivingNote__c IN :needSendEmailSet
                  AND Delete_Flag__c = false
                  AND Change_Point__c != '删除'
                ORDER BY ReceivingNoteDetailNo__c];
        if (rndList.size() > 0) {
            List<ReceivingNote__c> rnmList = new List<ReceivingNote__c>();
            List<ReceivingNote__c> rnmList1 = new List<ReceivingNote__c>();
            String oRnId = ''; // 上一条明细的清单Id
            String acceptNGMessage = '';  // 验收NG邮件内容
            String acceptAddMessage = ''; // 新建明细的邮件内容
            Integer acceptedCount = 0;           // 一个清单下的清点完成的明细数
            Integer newAddCount = 0;         // 一个清单下新建的明细数
            Integer totalCount = 0;         // 一个清单下明细总数
            String message = '';
            Map<String,Set<String>> acceptNewRNSMap = new Map<String,Set<String>>() ;
            for (ReceivingNoteDetail__c rnd : rndList) {
                if (String.isBlank(oRnId)) {
                    oRnId = rnd.ReceivingNote__c;
                }
                if (oRnId != rnd.ReceivingNote__c) {
                    // 清单下的除新建之外都清点完成
                    if(newAddCount + acceptedCount == totalCount){
                        // 有新建明细
                        if(newAddCount > 0){
                            acceptAddMessage += '【附属品增加】\n';
                            for(String rnsModel:acceptNewRNSMap.keySet()){
                                acceptAddMessage += '备品配套：' + rnsModel + '\n';
                                acceptAddMessage += '备品配套明细型号：'+ String.join(new List<String>(acceptNewRNSMap.get(rnsModel)),',')+'\n';
                            }
                        }
                        message = acceptNGMessage + acceptAddMessage;
                    }
                    ReceivingNote__c rn1 = new ReceivingNote__c(Id = oRnId, Acceptance_NG_Email__c = null);
                    ReceivingNote__c rn2 = new ReceivingNote__c(Id = oRnId, Acceptance_NG_Email__c = message);
                    rnmList.add(rn1);
                    rnmList1.add(rn2);

                    acceptNGMessage = '';
                    acceptAddMessage = '';
                    acceptedCount = 0;
                    newAddCount = 0;
                    totalCount = 0;
                    message = '';
                }
                oRnId = rnd.ReceivingNote__c;
                totalCount += 1;
                if (rnd.AcceptanceTime__c != null){
                    acceptedCount += 1;
                    if(rnd.AcceptanceResult__c == 'NG'){
                        if(String.isBlank(acceptNGMessage)){
                            acceptNGMessage += '【备品清点NG的情况】\n';
                            acceptNGMessage += '备品配套明细型号\t清点结果\t清点备注\n';
                        }
                        acceptNGMessage+= rnd.Fixture_Model_No_F__c +'\t'+rnd.AcceptanceResult__c+'\t' + rnd.AcceptanceComments__c+'\n';
                    }
                }
                else if(rnd.Change_Point__c == '新建' && rnd.DataConfirmation__c == false){
                    newAddCount += 1;
                    Set<String> rndModelSet = new Set<String> ();
                    String rnsModel = rnd.ReceivingNoteSummary__r.Fixture_Model_No_F__c;
                    if(acceptNewRNSMap.containsKey(rnsModel)){
                        rndModelSet = acceptNewRNSMap.get(rnsModel);
                    }
                    rndModelSet.add(rnd.Fixture_Model_No_F__c);
                    acceptNewRNSMap.put(rnsModel,rndModelSet);
                }
            }

            if (String.isNotBlank(oRnId)) {
                // 清单下的除新建之外都清点完成
                if(newAddCount + acceptedCount == totalCount){
                    // 有新建明细
                    if(newAddCount > 0){
                        acceptAddMessage += '【附属品增加】\n';
                        for(String rnsModel:acceptNewRNSMap.keySet()){
                            acceptAddMessage += '备品配套：' + rnsModel + '\n';
                            acceptAddMessage += '备品配套明细型号：'+ String.join(new List<String>(acceptNewRNSMap.get(rnsModel)),',')+'\n';
                        }
                    }
                    message = acceptNGMessage + acceptAddMessage;
                }
                ReceivingNote__c rn1 = new ReceivingNote__c(Id = oRnId, Acceptance_NG_Email__c = null);
                ReceivingNote__c rn2 = new ReceivingNote__c(Id = oRnId, Acceptance_NG_Email__c = message);
                rnmList.add(rn1);
                rnmList1.add(rn2);
            }
            update rnmList;
            update rnmList1;
        }
    }
    @Future
    // 由于handler更新自己表中字段，只好加@future保证workflow正常执行
    // 正常发mail的时，需要有mail内容和更新时间两个字段，根据时间的变化触发workflow发送mail内容
    private static void sendInspectionFinishEmail(Set<Id> needSendEmailSet){
        List<ReceivingNoteDetail__c> rndList = [
               SELECT Id
                    , ReceivingNote__c
                    , Fixture_Model_No_F__c
                 FROM ReceivingNoteDetail__c
                WHERE ReceivingNote__c = :needSendEmailSet
                  AND Delete_Flag__c = false
                  AND Inspection_result_after__c = 'OK'
                ORDER BY ReceivingNoteDetailNo__c];
        if (rndList.size() > 0) {
            List<ReceivingNote__c> rnmList = new List<ReceivingNote__c>();
            List<ReceivingNote__c> rnmList1 = new List<ReceivingNote__c>();
            String oRnId = '';
            String message = '';
            for (ReceivingNoteDetail__c rnd : rndList) {
                if (String.isBlank(oRnId)) {
                    oRnId = rnd.ReceivingNote__c;
                }
                if (oRnId != rnd.ReceivingNote__c) {
                    ReceivingNote__c rn1 = new ReceivingNote__c(Id = oRnId, Inspection_Finish_Email__c = null);
                    ReceivingNote__c rn2 = new ReceivingNote__c(Id = oRnId, Inspection_Finish_Email__c = message);
                    rnmList.add(rn1);
                    rnmList1.add(rn2);
                    message = '';
                }
                oRnId = rnd.ReceivingNote__c;
                message += rnd.Fixture_Model_No_F__c + '\n';
            }
            if (String.isNotBlank(oRnId)) {
                ReceivingNote__c rn1 = new ReceivingNote__c(Id = oRnId, Inspection_Finish_Email__c = null);
                ReceivingNote__c rn2 = new ReceivingNote__c(Id = oRnId, Inspection_Finish_Email__c = message);
                rnmList.add(rn1);
                rnmList1.add(rn2);
            }
            update rnmList;
            update rnmList1;
        }

    }
    private void sendEmail() {
        Set<Id> needSendRjectEmailSet = new Set<Id>();
        Set<Id> needSendAcceptNGEmailSet = new Set<Id>();
        Set<Id> needSendInspectionFinishEmailSet = new Set<Id>();
        for (ReceivingNote__c nObj : newList) {
            ReceivingNote__c oObj;
            if (Trigger.isUpdate) {
                oObj = oldMap.get(nObj.Id);
            }
            if (Trigger.isUpdate) {
                // 驳回或再数据确认完成
                if (oObj.Wei_DataConfirmationAgain_Reject_Cnt__c != nObj.Wei_DataConfirmationAgain_Reject_Cnt__c
                        && nObj.Wei_DataConfirmationAgain_Reject_Cnt__c == 0) {
                    needSendRjectEmailSet.add(nObj.Id);
                }
                // 未清点数量减少 或 总明细数量增加 时
                if (oObj.Wei_Acceptance_Cnt__c > nObj.Wei_Acceptance_Cnt__c
                    || oObj.ReceivingNoteDetail_Cnt__c < nObj.ReceivingNoteDetail_Cnt__c) {
                    needSendAcceptNGEmailSet.add(nObj.Id);
                }
                // 验收完成
                if (oObj.Wei_Inspection_Cnt__c != nObj.Wei_Inspection_Cnt__c
                        && nObj.Wei_Inspection_Cnt__c == 0){
                    needSendInspectionFinishEmailSet.add(nObj.Id);
                }
            }
        }
        if(!needSendRjectEmailSet.isEmpty()){
            sendRejectEmail(needSendRjectEmailSet);
        }
        if(!needSendAcceptNGEmailSet.isEmpty()){
            sendAcceptNGEmail(needSendAcceptNGEmailSet);
        }
        if(!needSendInspectionFinishEmailSet.isEmpty()){
            sendInspectionFinishEmail(needSendInspectionFinishEmailSet);
        }
    }
}