/**
 * 20220606 lt 带量采购记录
 * 根据“产品编号”检索产品主数据，给字段“产品”（查找产品）赋值
 */
public without sharing class BringQuantityHandler extends Oly_TriggerHandler{
    private Map<Id, BringQuantityPurchaseRecord__c> newMap;
    private Map<Id, BringQuantityPurchaseRecord__c> oldMap;
    private List<BringQuantityPurchaseRecord__c> newList;
    private List<BringQuantityPurchaseRecord__c> oldList;

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

    protected override void beforeInsert(){
        specialCharacterClear();
        FindProducts();
    }

    protected override void beforeUpdate(){
        specialCharacterClear();
        FindProducts();
    }

    // 把型号、型号确认、规格里的”改成"
    private void specialCharacterClear() {
        for(BringQuantityPurchaseRecord__c bqp : newList){
            // 型号
            bqp.Model__c = String.isNotBlank(bqp.Model__c) && bqp.Model__c.contains('”') ? bqp.Model__c.replaceAll('”','"') : bqp.Model__c;
            // 型号确认
            bqp.ModelConfirm__c = String.isNotBlank(bqp.ModelConfirm__c) && bqp.ModelConfirm__c.contains('”') ? bqp.ModelConfirm__c.replaceAll('”','"') : bqp.ModelConfirm__c;
            // 规格
            bqp.Specifications__c = String.isNotBlank(bqp.Specifications__c) && bqp.Specifications__c.contains('”') ? bqp.Specifications__c.replaceAll('”','"') : bqp.Specifications__c;
        }
    }

    private void FindProducts(){
        if(trigger.isInsert || trigger.isUpdate){
            //存带量采购的产品编号
            List<String> bqList = new List<String>();
            List<String> MDMList = new List<String>();
            for(BringQuantityPurchaseRecord__c bqp : newList){
                // if(bqp.ProductNumber__c != null){
                if(String.isNotBlank(bqp.ProductNumber__c)){
                    bqList.add(bqp.ProductNumber__c);
                }
                if (String.isNotBlank(bqp.ModelConfirm__c)) {
                    MDMList.add(bqp.ModelConfirm__c);
                }
            }

            //根据产品编号查产品
            List<Product2> proList = [select id, Name, ProductCode, MDM_Model_No__c from Product2 where ProductCode in :bqList or MDM_Model_No__c in :MDMList];
            
            for(BringQuantityPurchaseRecord__c bqr : newList){
                for(Product2 pro : proList){
                    if((bqr.ProductNumber__c == pro.ProductCode) || (bqr.ModelConfirm__c == pro.MDM_Model_No__c)){
                        bqr.Product2__c = pro.id;
                    }
                }
            }

        }
    }
}