@RestResource(urlMapping = '/MDMITM/*')
global with sharing class  MDMITMRest {
  public static boolean isRunning = false;
  global class ItemMastersRest {
    public ItemMasters ItemMasters;
  }
  global class ItemMasters {
    public NFMUtil.Monitoring Monitoring;
    public MDMITMRest.ItemMaster[] ItemMaster;
  }
  global class ItemMaster {
    public String InterfaceNumber;
    public Integer RecordCount;
    public MDMITMRest.Record[] Record;
  }
  global class Record {
    public String MaterialNumber;
    public MDMITMRest.MaterialDescription[] MaterialDescription;
    public String ModelForSales;
    public String RepairCode;
    public String Layer1st;
    public String Layer2nd;
    public String Layer3rd;
    public String Layer4th;
    public String Layer5th;
    public MDMITMRest.ProductLotSerialNoTraceability[] ProductLotSerialNoTraceability;
    public Integer LifeTime;
    public String MCompany;
    public String BaseUnitOfMeasure;
    public MDMITMRest.BusinessSegmentName BusinessSegmentName;
    public String To;

    //=======xinhonglu=============Start=============20180827===========
    //HHOA-B3L8G6[委托]销售：产品主数据接口（MDMITM）修改
    public MDMITMRest.QuantityPerSalesPackagingUnit[] QuantityPerSalesPackagingUnit;
    public MDMITMRest.EANUPC[] EANUPC;
    public String CN_SalesPackagingUnit;
    public String GrossWeight;
    public String WeightUnit;
    public String CN_LonerType;
    public MDMITMRest.MaterialClassificationCode MaterialClassificationCode;
    public MDMITMRest.WoodWeight[] WoodWeight;
    public MDMITMRest.SalesPackagingUnit[] SalesPackagingUnit;
    public MDMITMRest.AbbreviatedModelName AbbreviatedModelName;
    public MDMITMRest.GMSCCode GMSCCode;
    public MDMITMRest.ProductionExpriyDateHandling[] ProductionExpriyDateHandling;
    public MDMITMRest.MBCGHQDeliveryStartDate MBCGHQDeliveryStartDate;
    public MDMITMRest.MaterialStatus[] MaterialStatus;
    public MDMITMRest.ProductDiscontinuationDate ProductDiscontinuationDate;
    public MDMITMRest.RepairableUnrepairable RepairableUnrepairable;
    public MDMITMRest.DangerousGoodsFlag[] DangerousGoodsFlag;
    public MDMITMRest.UNNumber1[] UNNumber1;
    public MDMITMRest.UNNumber2[] UNNumber2;
    public MDMITMRest.UNNumber3[] UNNumber3;
    public MDMITMRest.UNNumber4[] UNNumber4;
    public MDMITMRest.DangerClass1A[] DangerClass1A;
    public MDMITMRest.DangerClass2A[] DangerClass2A;
    public MDMITMRest.DangerClass3A[] DangerClass3A;
    public MDMITMRest.DangerClass4A[] DangerClass4A;
    public MDMITMRest.DangerClass1B[] DangerClass1B;
    public MDMITMRest.DangerClass2B[] DangerClass2B;
    public MDMITMRest.DangerClass3B[] DangerClass3B;
    public MDMITMRest.DangerClass4B[] DangerClass4B;
    public MDMITMRest.UNPackingGroup1[] UNPackingGroup1;
    public MDMITMRest.UNPackingGroup2[] UNPackingGroup2;
    public MDMITMRest.UNPackingGroup3[] UNPackingGroup3;
    public MDMITMRest.UNPackingGroup4[] UNPackingGroup4;
    public MDMITMRest.ProperShippingName1[] ProperShippingName1;
    public MDMITMRest.ProperShippingName2[] ProperShippingName2;
    public MDMITMRest.ProperShippingName3[] ProperShippingName3;
    public MDMITMRest.ProperShippingName4[] ProperShippingName4;
    public MDMITMRest.WEEEClassification[] WEEEClassification;
    public MDMITMRest.WEEE2Classification[] WEEE2Classification;
    public MDMITMRest.WEEEWeight[] WEEEWeight;
    public MDMITMRest.BatteryType1[] BatteryType1;
    public MDMITMRest.BatterySystemName1[] BatterySystemName1;
    public MDMITMRest.BatteryQuantity1[] BatteryQuantity1;
    public MDMITMRest.BatteryWeight1[] BatteryWeight1;
    public MDMITMRest.BatteryType2[] BatteryType2;
    public MDMITMRest.BatterySystemName2[] BatterySystemName2;
    public MDMITMRest.BatteryQuantity2[] BatteryQuantity2;
    public MDMITMRest.BatteryWeight2[] BatteryWeight2;
    public MDMITMRest.GlassWeight[] GlassWeight;
    public MDMITMRest.PaperCardboardWeight[] PaperCardboardWeight;
    public MDMITMRest.SteelWeight[] SteelWeight;
    public MDMITMRest.AluminiumWeight[] AluminiumWeight;
    public MDMITMRest.PlasticWeight[] PlasticWeight;
    public MDMITMRest.EPSWeight[] EPSWeight;
    public MDMITMRest.HSCodeCustomCodes[] HSCodeCustomCodes;
    public MDMITMRest.DualUseIndicator DualUseIndicator;
    public MDMITMRest.SupplierProductNumber SupplierProductNumber;
    public MDMITMRest.BusinessSegmentCode BusinessSegmentCode;
    public MDMITMRest.BusinessGroup BusinessGroup;
    public MDMITMRest.OtherWeight[] OtherWeight;
    public MDMITMRest.CarbonFootprint[] CarbonFootprint;
    public MDMITMRest.COSHH[] COSHH;
    public MDMITMRest.RoHS[] RoHS;
    public MDMITMRest.REACH[] REACH;

    public MDMITMRest.SKU_QtyPerPallet[] SKU_QtyPerPallet ;
    public MDMITMRest.MultiPackGTIN[] MultiPackGTIN ;
    public MDMITMRest.MultiPack[] MultiPack ;
    public MDMITMRest.SinglePackGTIN[] SinglePackGTIN;
    public MDMITMRest.SinglePack[] SinglePack;
    public MDMITMRest.DeviceGTIN[] DeviceGTIN;
    public MDMITMRest.DPM[] DPM ;
    public MDMITMRest.ProductionDateFlag[] ProductionDateFlag;
    public MDMITMRest.GS1_128Flag[] GS1_128Flag;
    public MDMITMRest.MultiPackWidth[] MultiPackWidth;
    public MDMITMRest.MultiPackHeight[] MultiPackHeight;
    public MDMITMRest.MultiPackLength[] MultiPackLength;
    public MDMITMRest.MultiPackWeight[] MultiPackWeight;
    public MDMITMRest.VirtualItemFlag[] VirtualItemFlag;
    public MDMITMRest.ManufacturerSite[] ManufacturerSite;

    public String[] CN_String1;
    public String[] CN_String2;
    public String[] CN_String3;
    public String[] CN_String4;
    public String[] CN_String5;

    public String[] CN_Dec1;
    public String[] CN_Dec2;
    public String[] CN_Dec3;
    public String[] CN_Dec4;
    public String[] CN_Dec5;

    public String[] CN_Date1;
    public String[] CN_Date2;
    public String[] CN_Date3;
    public String[] CN_Date4;
    public String[] CN_Date5;

    public String SizeDimensions;
    public String[] MaterialGroup;
    public String[] IndustrialSector;
    public String[] TransportationGroup;
    public String[] ExtMatlgroup;
    public String[] RA_GMDNNumber;
    public String[] RA_FDAReqNumber;
    public String[] RA_510k;
    public String[] RA_ListingNumber;
    public String[] RA_ProductCode;
    public String[] RA_EstablishmentCode;
    public String[] SalesStartDate;
    public String[] SalesDiscontinuationDate;
    public String[] NFM_Category;
    public String[] OCN_Material_Group;
    public String[] Vendor;
    public String[] Sales_Product_Description;
    public String[] EANCategory;
    public String FromBC;
    public String UpdateFlag;
    public String[] ValuationClass;
    public String[] CountryOfOrigin;
    //====================End=============20180827===========
  }

  global class MaterialDescription {
    public String LanguageKey;
    public String Description;
  }
  global class ProductLotSerialNoTraceability {
    public String Value;
  }
  global class BusinessSegmentName {
    public String Value;
  }

  //========xinhonglu=======add=====Start=============20180827===========
  global class EANUPC {
    public String Category;
    public String Value;
  }

  global class QuantityPerSalesPackagingUnit {
    //HHOA-BC5A4H LHJ 20190513 Start
    //public Integer value;
    public String value;
    //HHOA-BC5A4H LHJ 20190513 End
  }
  global class AbbreviatedModelName {
    public String Value;
  }

  global class MaterialClassificationCode {
    public String Value;
  }

  global class GMSCCode {
    public String Value;
  }
  global class ProductionExpriyDateHandling {
    public String Value;
  }
  global class MBCGHQDeliveryStartDate {
    public String Value;
  }
  global class MaterialStatus {
    public String Value;
  }

  global class ProductDiscontinuationDate {
    public String Value;
  }

  global class RepairableUnrepairable {
    public String Value;
  }

  global class DangerousGoodsFlag {
    public String Value;
  }

  global class UNNumber1 {
    public Integer Value;
  }

  global class UNNumber2 {
    public Integer Value;
  }

  global class UNNumber3 {
    public Integer Value;
  }

  global class UNNumber4 {
    public Integer Value;
  }

  global class DangerClass1A {
    public String Value;
  }

  global class DangerClass1B {
    public String Value;
  }

  global class DangerClass2A {
    public String Value;
  }

  global class DangerClass2B {
    public String Value;
  }

  global class DangerClass3A {
    public String Value;
  }

  global class DangerClass3B {
    public String Value;
  }

  global class DangerClass4A {
    public String Value;
  }

  global class DangerClass4B {
    public String Value;
  }

  global class UNPackingGroup1 {
    public String Value;
  }

  global class UNPackingGroup2 {
    public String Value;
  }

  global class UNPackingGroup3 {
    public String Value;
  }

  global class UNPackingGroup4 {
    public String Value;
  }

  global class ProperShippingName1 {
    public String Value;
  }

  global class ProperShippingName2 {
    public String Value;
  }

  global class ProperShippingName3 {
    public String Value;
  }

  global class ProperShippingName4 {
    public String Value;
  }

  global class WEEEClassification {
    public String Value;
  }

  global class WEEE2Classification {
    public String Value;
  }

  global class WEEEWeight {
    public Decimal Value;
  }

  global class BatteryType1 {
    public String Value;
  }

  global class BatterySystemName1 {
    public String Value;
  }

  global class BatteryQuantity1 {
    public Integer Value;
  }

  global class BatteryWeight1 {
    public Decimal Value;
  }

  global class BatteryType2 {
    public String Value;
  }

  global class BatterySystemName2 {
    public String Value;
  }

  global class BatteryQuantity2 {
    public Integer Value;
  }

  global class BatteryWeight2 {
    public Decimal Value;
  }

  global class GlassWeight {
    public Decimal Value;
  }

  global class PaperCardboardWeight {
    public Decimal Value;
  }

  global class SteelWeight {
    public Decimal Value;
  }

  global class AluminiumWeight {
    public Decimal Value;
  }

  global class PlasticWeight {
    public Decimal Value;
  }

  global class EPSWeight {
    public Decimal Value;
  }

  global class WoodWeight {
    public Decimal Value;
  }

  global class SalesPackagingUnit {
    public String Value;
  }

  global class HSCodeCustomCodes {
    public String Value;
  }

  global class DualUseIndicator {
    public String Value;
  }

  global class SupplierProductNumber {
    public String Value;
  }

  global class BusinessSegmentCode {
    public String Value;
  }

  global class BusinessGroup {
    public String Value;
  }

  global class OtherWeight {
    public Decimal Value;
  }

  global class CarbonFootprint {
    public Decimal Value;
  }

  global class COSHH {
    public String Value;
  }

  global class RoHS {
    public String Value;
  }

  global class REACH {
    public String Value;
  }

  global class SKU_QtyPerPallet {
    public String Value;
  }

  global class MultiPackGTIN {
    public String Value;
  }

  global class MultiPack {
    public String Value;
  }

  global class SinglePackGTIN {
    public String Value;
  }

  global class SinglePack {
    public String Value;
  }

  global class DeviceGTIN {
    public String Value;
  }

  global class DPM {
    public String Value;
  }

  global class ProductionDateFlag {
    public String Value;
  }

  global class GS1_128Flag {
    public String Value;
  }

  global class MultiPackWidth {
    public String Value;
  }

  global class MultiPackHeight {
    public String Value;
  }

  global class MultiPackLength {
    public String Value;
  }

  global class MultiPackWeight {
    public String Value;
  }

  global class VirtualItemFlag {
    public String Value;
  }

  global class ManufacturerSite {
    public String Value;
  }
  @HttpPost
  global static void execute() {
    // 取得接口传输内容
    String strData = RestContext.request.requestBody.toString();
    ItemMastersRest ItemMastersRest = (ItemMastersRest) JSON.deserializeStrict(strData, ItemMastersRest.class);
    if (ItemMastersRest == null ) {
      return;
    }


    if (ItemMastersRest.ItemMasters == null) {
      return;
    }
    NFMUtil.Monitoring Monitoring = ItemMastersRest.ItemMasters.Monitoring;
    if (Monitoring == null) {
      return;
    }
    BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'MDMITM', ItemMastersRest.ItemMasters.ItemMaster);
    if (String.isBlank(rowData.Log__c) == false) {
      executefuture(rowData.Id);
    }
    // JSONを戻す
    RestResponse res = RestContext.response;
    res.addHeader('Content-Type', 'application/json');
    res.statusCode = 200;
    //String jsonResponse = '{"status": "Success", "Message":'  + gedata + '}';
    String jsonResponse = '{"status": "Success", "Message":""}';
    res.responseBody = blob.valueOf(jsonResponse);
    return;
  }
  @future
  global static void executefuture(String rowData_Id) {
    execute(rowData_Id);
  }
  global static void execute(String rowData_Id) {
    Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
    BatchIF_Log__c rowData = [Select Id, Name, Log__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c, Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c, retry_cnt__c from BatchIF_Log__c where RowDataFlg__c = true and Id = :rowData_Id];
    MDMITMRest.isRunning = true;
    String logstr = rowData.MessageGroupNumber__c + ' start\n';
    BatchIF_Log__c iflog = new BatchIF_Log__c();
    iflog.Type__c = 'MDMITM';
    iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
    iflog.Log__c = logstr;
    iflog.ErrorLog__c = '';
    insert iflog;
    String rowDataStr = NFMUtil.getRowDataStr(rowData);
    List<ItemMaster> itemMasterList = (List<ItemMaster>) JSON.deserialize(rowDataStr, List<ItemMaster>.class);
    if (itemMasterList == null || itemMasterList.size() == 0) {
      return;
    }

    // BatchIF転送表 から、コード変換のMapを作成
    Map<String, String> transferMap = new Map<String, String>();
    List<BatchIF_Transfer__c> transferList = [select Table__c,
                              Column__c,
                              External_value__c,
                              Internal_value__c
                              from BatchIF_Transfer__c
                              where Dropped_Flag__c = false
                                      and Table__c = 'Product2'];
    for (BatchIF_Transfer__c t : transferList) {
      transferMap.put(t.Column__c + t.External_value__c, t.Internal_value__c);
    }

    Savepoint sp = Database.setSavepoint();
    try {

      Map<String, String> pickListValuesMap = new Map<String, String>();
      Schema.DescribeFieldResult fieldResult = Product2.ENG__c.getDescribe();
      List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
      for ( Schema.PicklistEntry pickListVal : ple) {
        pickListValuesMap.put(pickListVal.getValue(), pickListVal.getLabel());
      }
      // 更新対応配列とMapなどをセット
      List<String> productCodeList = new List<String>();
      List<String> assetModelNoList = new List<String>();
      for (MDMITMRest.ItemMaster ItemMaster : itemMasterList) {
        for (MDMITMRest.Record Record : ItemMaster.Record) {
          if (Record.To != 'OCN') {
            // TOは必ず OCN
            continue;
          }
          if (Record.MaterialNumber == null || Record.MaterialNumber == '') {
            // 必須項目がない場合、処理と飛ばす
            continue;
          }
          // vivek start by vivek 2019-7-18 使用MDM的备用字段【CN_String1】同步产品主数据的【ENG区分】（ENG__c）
          if (Record.CN_String1 != null && !pickListValuesMap.containsKey(Record.CN_String1[0]) && Record.CN_String1[0] != '') {
            // 判断传过来的值是否在选项列表Eng区分中存在
            continue;
          }
          // vivek end by vivek 2019-7-18 使用MDM的备用字段【CN_String1】同步产品主数据的【ENG区分】（ENG__c）
          productCodeList.add(Record.MaterialNumber);
          if (Record.ModelForSales != null && Record.ModelForSales != '') {
            assetModelNoList.add(Record.ModelForSales);
          }
        }

      }

      List<Product2> prdList = [select Id, ENG__c, ProductCode, ProductCode_Ext__c,
                                MDM_Name__c, MDM_Model_No__c, Alternative_Products__c,
                                Name, Asset_Model_No__c, IsActive,
                                Repair_Product_Code__c,
                                BSSCategory__c, Family,
                                Category2__c, Category3__c,
                                Category4__c, Category5__c,
                                Serial_Lot_No__c,
                                Durable_Years__c,
                                Brand_Name__c,
                                Qty_Unit__c,
                                      Image_Height__c, Image_Width__c, Image_DocumentID__c,
                                      IsFromSAP__c 
                                from Product2
                                where ProductCode_Ext__c in :productCodeList
                                order by CreatedDate desc];
      Map<String, Product2> prdsMap = new Map<String, Product2>();
      for (Product2 prd : prdList) {
        prdsMap.put(prd.ProductCode_Ext__c, prd);
      }

      // SWAG-AVHDLM MDM数据来的时候相同型号的拷贝照片
      List<Product2> prdList2 = [select Id, Asset_Model_No__c, Image_Height__c, Image_Width__c, Image_DocumentID__c
                                 from Product2
                                 where Asset_Model_No__c in :assetModelNoList
                                 and Image_DocumentID__c != null
                                 order by CreatedDate desc];
      Map<String, Product2> imgMap = new Map<String, Product2>();
      for (Product2 prd : prdList2) {
        if (prd.Image_DocumentID__c != null && imgMap.containsKey(prd.Asset_Model_No__c) == false) {
          imgMap.put(prd.Asset_Model_No__c, prd);
        }
      }

      // 更新対応配列をセット
      prdList = new List<Product2>();
      Map<String, Product2> prdUpdateMap = new Map<String, Product2>();

      for (MDMITMRest.ItemMaster ItemMaster : itemMasterList) {
        for (MDMITMRest.Record Record : ItemMaster.Record) {
          if (Record.To != 'OCN') {
            // TOは必ず OCN
            logstr += 'Record.To==' + Record.To + ' ';
            continue;
          }
          if (Record.MaterialNumber == null || Record.MaterialNumber == '') {
            // 必須項目がない場合、処理と飛ばす
            iflog.ErrorLog__c += 'MaterialNumber is required\n';
            continue;
          }
          // vivek start by vivek 2019-7-18 使用MDM的备用字段【CN_String1】同步产品主数据的【ENG区分】（ENG__c）
          if (Record.CN_String1 != null && !pickListValuesMap.containsKey(Record.CN_String1[0]) && Record.CN_String1[0] != '') {
            iflog.ErrorLog__c += Record.MaterialNumber + ':Eng区分' + Record.CN_String1 + '不存在\n';
            continue;
          }
          // vivek end by vivek 2019-7-18 使用MDM的备用字段【CN_String1】同步产品主数据的【ENG区分】（ENG__c）
                    //HHOA-BLZCYF MDM：新增字段传输 精琢技术 2020/03/11 start
                    //保修期（年）
                    if(Record.CN_Dec1 != null ){
                        if (Record.CN_Dec1[0] != '' && Record.CN_Dec1[0] != '2'
                           && Record.CN_Dec1[0] != '3' && Record.CN_Dec1[0] != '4' 
                           && Record.CN_Dec1[0] != '5') {
                            iflog.ErrorLog__c += Record.MaterialNumber+':数据错误，数据不进行更新/保存。原因：传入其他数字'+Record.CN_Dec1[0]+'\n';
                            continue;
                        }
                       
                    }
                    //HHOA-BLZCYF MDM：新增字段传输 精琢技术 2020/03/11 end
                    Product2 prd = prdsMap.get(Record.MaterialNumber);
                    String prdName = null;
                    if (prd == null) {
                        // 新規の場合 LanguageKey が ZH 商品のみ受信
                        Boolean isZh = false;
                        if (Record.MaterialDescription != null) {
                            for (MDMITMRest.MaterialDescription MaterialDescription : Record.MaterialDescription) {
                                if (MaterialDescription.LanguageKey == 'ZH') {
                                    isZh = true;
                                    prdName = MaterialDescription.Description;
                                    break;
                                }
                            }
                        }
                        if (isZh == false) {
                            logstr += 'ZH==false ';
                            continue;
                        }

            prd = new Product2();
            // prd.ENG__c = 'ENG';
            // SWAG-AVHDLM MDM数据来的时候相同型号的拷贝照片
            if (Record.ModelForSales != null && imgMap.containsKey(Record.ModelForSales) == true) {
              prd.Image_Height__c = imgMap.get(Record.ModelForSales).Image_Height__c;
              prd.Image_Width__c = imgMap.get(Record.ModelForSales).Image_Width__c;
              prd.Image_DocumentID__c = imgMap.get(Record.ModelForSales).Image_DocumentID__c;
            }
                        //HHOA-BLZCYF MDM：新增字段传输 精琢技术 2020/03/11 start
                        if(Record.CN_String2 != null && Record.CN_Dec1 !=null){
                             prd  = upsertProduct(false,prd,Record.CN_String2[0],Record.CN_Dec1[0],iflog,transferMap);
                        }
                        //HHOA-BLZCYF MDM：新增字段传输 精琢技术 2020/03/11 end
                    } else {
                        // 更新の場合 LanguageKey が ZH の名前の更新が受付けする
                        if (Record.MaterialDescription != null) {
                            for (MDMITMRest.MaterialDescription MaterialDescription : Record.MaterialDescription) {
                                if (MaterialDescription.LanguageKey == 'ZH') {
                                    prdName = MaterialDescription.Description;
                                    break;
                                }
                            }
                        }
                    }

          // 項目転送のセット
          prd.ProductCode        = Record.MaterialNumber;
          prd.IsActive = true;
          if (prdUpdateMap.get(prd.ProductCode) == null) {
            prdList.add(prd);
            prdUpdateMap.put(prd.ProductCode, prd);
            //logstr += Record.MaterialNumber + ' ';               // 価格表のところまとめてlogを出す
          } else {
            prd = prdUpdateMap.get(prd.ProductCode);
          }
          prd.Manual_Entry__c = false;
          // 中文名称が転送してきた場合
          if (prdName != null) {
            // デフォルト値
            prd.MDM_Name__c = prdName;
            prd.Alternative_Products__c = '';
            prd.MDM_Model_No__c = '';
            prd.Name = prdName.trim();

            // 型番:代替品::中文名称 のパターン
            Pattern pt = Pattern.compile('(.*):(.*)::(.*)');
            Matcher mc = pt.matcher(prdName);
            if (mc.matches()) {
              prd.MDM_Model_No__c = mc.group(1).trim();
              prd.Alternative_Products__c = mc.group(2).trim();
                            // HWAG-BPXBEW  报价和配置单中，无型号产品的显示  精琢技术  wql 2020/05/29 start 
                            //注释源代码
                            // prd.Name = (prd.MDM_Model_No__c == '' ? prd.ProductCode : prd.MDM_Model_No__c) + ':' + mc.group(3).trim();
                            if(prd.MDM_Model_No__c == ''){
                                prd.Name = mc.group(3).trim();
                            }else{
                                prd.Name =prd.MDM_Model_No__c+ ':' + mc.group(3).trim();
                            }
                            // HWAG-BPXBEW  报价和配置单中，无型号产品的显示  精琢技术  wql 2020/05/29 end
                            
                        } else {
                            pt = Pattern.compile('(.*)：(.*)：：(.*)');
                            mc = pt.matcher(prdName);
                            if (mc.matches()) {
                                prd.MDM_Model_No__c = mc.group(1).trim();
                                prd.Alternative_Products__c = mc.group(2).trim();
                                // HWAG-BPXBEW  报价和配置单中，无型号产品的显示  精琢技术  wql 2020/05/29 start 
                                //注释源代码
                                // prd.Name = (prd.MDM_Model_No__c == '' ? prd.ProductCode : prd.MDM_Model_No__c) + ':' + mc.group(3).trim();
                                if(prd.MDM_Model_No__c == ''){
                                    prd.Name = mc.group(3).trim();
                                }else{
                                    prd.Name =prd.MDM_Model_No__c+ ':' + mc.group(3).trim();
                                }
                                // HWAG-BPXBEW  报价和配置单中，无型号产品的显示  精琢技术  wql 2020/05/29 end
                               
                            }
                        }
                        if (mc.matches() == false
                                && ((prd.Name.indexOf(':') >= 0 && prd.Name.indexOf(':') != prd.Name.indexOf('::'))
                                    || (prd.Name.indexOf('：') >= 0 && prd.Name.indexOf('：') != prd.Name.indexOf('：：'))
                                   )
                           ) {
                            // 型番::中文名称 のパターン
                            pt = Pattern.compile('(.*):(.*)');
                            mc = pt.matcher(prdName);
                            if (mc.matches()) {
                                prd.MDM_Model_No__c = mc.group(1).trim();
                                // HWAG-BPXBEW  报价和配置单中，无型号产品的显示  精琢技术  wql 2020/05/29 start 
                                //注释源代码
                                // prd.Name = (prd.MDM_Model_No__c == '' ? prd.ProductCode : prd.MDM_Model_No__c) + ':' + mc.group(2).trim();
                                if(prd.MDM_Model_No__c == ''){
                                    prd.Name = mc.group(2).trim();
                                }else{
                                    prd.Name =prd.MDM_Model_No__c+ ':' + mc.group(2).trim();
                                }
                                // HWAG-BPXBEW  报价和配置单中，无型号产品的显示  精琢技术  wql 2020/05/29 end
                                
                            } else {
                                pt = Pattern.compile('(.*)：(.*)');
                                mc = pt.matcher(prdName);
                                if (mc.matches()) {
                                    prd.MDM_Model_No__c = mc.group(1).trim();
                                // HWAG-BPXBEW  报价和配置单中，无型号产品的显示  精琢技术  wql 2020/05/29 start 
                                //注释源代码
                                // prd.Name = (prd.MDM_Model_No__c == '' ? prd.ProductCode : prd.MDM_Model_No__c) + ':' + mc.group(2).trim();
                                if(prd.MDM_Model_No__c == ''){
                                    prd.Name = mc.group(2).trim();
                                }else{
                                    prd.Name =prd.MDM_Model_No__c+ ':' + mc.group(2).trim();
                                }
                                // HWAG-BPXBEW  报价和配置单中，无型号产品的显示  精琢技术  wql 2020/05/29 end
                                   
                                }
                            }
                        }
                        // 上記以外のパターン
                        if (mc.matches() == false) {
                            if (prd.Name.indexOf('::') == 0) {
                                prd.Name = prd.Name.substring(2);
                            }
                            if (prd.Name.indexOf('：：') == 0) {
                                prd.Name = prd.Name.substring(2);
                            }
                            // HWAG-BPXBEW  报价和配置单中，无型号产品的显示  精琢技术  wql 2020/05/29 start 
                            //注释源代码
                            // prd.Name = prd.ProductCode + ':' + prd.Name.trim();
                            prd.Name = prd.Name.trim();
                            // HWAG-BPXBEW  报价和配置单中，无型号产品的显示  精琢技术  wql 2020/05/29 end
                            
                        }
                    }      
                    if (Record.ModelForSales != null) {
                        prd.Asset_Model_No__c = Record.ModelForSales;
                    }
                    if (Record.RepairCode != null) {
                        prd.Repair_Product_Code__c = Record.RepairCode;
                    }
                    if (Record.Layer1st != null) {
                        prd.Family = Record.Layer1st;
                    }
                    if (Record.Layer2nd != null) {
                        prd.Category2__c = Record.Layer2nd;
                    }
                    if (Record.Layer3rd != null) {
                        prd.Category3__c = Record.Layer3rd;
                    }
                    if (Record.Layer4th != null) {
                        prd.Category4__c = Record.Layer4th;
                    }
                    if (Record.Layer5th != null) {
                        prd.Category5__c = Record.Layer5th;
                    }
                    if (Record.ProductLotSerialNoTraceability != null &&
                            Record.ProductLotSerialNoTraceability.size() > 0 &&
                            Record.ProductLotSerialNoTraceability.get(0).Value != null
                       ) {
                        prd.Serial_Lot_No__c = Record.ProductLotSerialNoTraceability.get(0).Value;
                    }
                    if (Record.LifeTime != null) {
                        prd.Durable_Years__c = Record.LifeTime;
                    }
                    if (Record.MCompany != null) {
                        prd.Brand_Name__c = Record.MCompany;
                    }
                    if (Record.BaseUnitOfMeasure != null) {
                        prd.Qty_Unit__c = Record.BaseUnitOfMeasure;
                    }
                    if (Record.BusinessSegmentName != null && Record.BusinessSegmentName.Value != null) {
                        prd.BSSCategory__c = Record.BusinessSegmentName.Value;
                    }
                    // vivek start by vivek 2019-7-18 使用MDM的备用字段【CN_String1】同步产品主数据的【ENG区分】（ENG__c）
                    if (Record.CN_String1 != null) {
                        prd.ENG__c = Record.CN_String1[0];
                    }

                    // update end by vivek 2019-7-18 使用MDM的备用字段【CN_String1】同步产品主数据的【ENG区分】（ENG__c）
                    //HHOA-BLZCYF MDM：新增字段传输 精琢技术 2020/03/24 start
                    system.debug('IsFromSAP__c:'+prd.IsFromSAP__c );
                    if(Record.CN_String2 != null && Record.CN_Dec1 !=null){
                         prd  = upsertProduct(prd.IsFromSAP__c,prd,Record.CN_String2[0],Record.CN_Dec1[0],iflog,transferMap);
                    }
                    //HHOA-BLZCYF MDM：新增字段传输 精琢技术 2020/03/24 end
                    //=======xinhonglu=============Start=============20180816===========
                    //HHOA-B3L8G6[委托]销售：产品主数据接口（MDMITM）修改
                    if (Record.MaterialClassificationCode != null && Record.MaterialClassificationCode.Value != null
                       ) {
                        prd.BSS_Code__c = Record.MaterialClassificationCode.Value;
                    }
                    if (Record.QuantityPerSalesPackagingUnit != null ) {
                        if (Record.QuantityPerSalesPackagingUnit.size() > 0
                                && Record.QuantityPerSalesPackagingUnit.get(0).Value != null
                                //HHOA-BC5A4H LHJ 20190513 Start
                                && Record.QuantityPerSalesPackagingUnit.get(0).Value != '') {
                            prd.Packing_list_manual__c = Integer.valueOf(Record.QuantityPerSalesPackagingUnit.get(0).Value);
                        } else {
                            prd.Packing_list_manual__c = 0;
                        }
                    }
                    //HHOA-BC5A4H LHJ 20190513 End


          if (Record.EANUPC != null) {
            for (MDMITMRest.EANUPC eANUPC : Record.EANUPC) {
              if (eANUPC.Category == 'G1') {
                prd.JANCODE__c = eANUPC.Value;
              }
            }

          }
          // LHJ 20180927 10.8上线时暂时注释掉
          if (Record.CN_SalesPackagingUnit != null) {
            prd.SalesPackagingUnit_Chinese__c = NFMUtil.getMapValue(transferMap, 'SalesPackagingUnit_Chinese__c', Record.CN_SalesPackagingUnit, iflog);
          }
          if (Record.GrossWeight != null) {
            prd.GrossWeight__c = Decimal.valueOf(Record.GrossWeight);
          }
          if (Record.WeightUnit != null) {
            prd.WeightUnit__c = Record.WeightUnit;
          }
          // LHJ 20180927 10.8上线时暂时注释掉
          //if (Record.CN_LonerType != null) {
          //    prd.LonerType__c = Record.CN_LonerType;
          //}
          //====================End=============20180816===========
        }
      }
      if (prdList.size() > 0) {
        upsert prdList;
        // PricebookEntryにデータがない場合insertする、CNYとUSDのみ
        List<Pricebook2> pricebookList = new List<Pricebook2>();
        if (system.Test.isRunningTest()) {
          pricebookList.add(new Pricebook2(Id = system.Test.getStandardPricebookId(), Name = 'Standard Pricebook'));
        } else {
          pricebookList = [Select Id From Pricebook2 where IsStandard = true];
        }
        if (pricebookList.size() == 0) {
          iflog.ErrorLog__c += 'Can not find SFDC Standard Pricebook\n';
        } else {
          String pricebookId = pricebookList.get(0).Id;
          List<PricebookEntry> pbeList = [Select Product2Id, CurrencyIsoCode, UnitPrice, Pricebook2Id From PricebookEntry where Product2Id in: prdList and Pricebook2Id = :pricebookId order by Product2Id, CurrencyIsoCode];
          List<PricebookEntry> pbeInsertList = new List<PricebookEntry>();
          Map<String, PricebookEntry> rmbMap = new Map<String, PricebookEntry>();
          Map<String, PricebookEntry> usdMap = new Map<String, PricebookEntry>();
          for (PricebookEntry pbe : pbeList) {
            if (pbe.CurrencyIsoCode == 'CNY') {
              rmbMap.put(pbe.Product2Id, pbe);
            } else if (pbe.CurrencyIsoCode == 'USD') {
              usdMap.put(pbe.Product2Id, pbe);
            }
          }
          for (Product2 prd : prdList) {
            logstr += prd.ProductCode;
            if (rmbMap.get(prd.Id) == null) {
              PricebookEntry pbe = new PricebookEntry();
              pbe.Pricebook2Id    = pricebookId;
              pbe.Product2Id      = prd.Id;
              pbe.CurrencyIsoCode = 'CNY';
              pbe.UnitPrice       = 0;
              pbe.IsActive        = prd.IsActive;
              pbeInsertList.add(pbe);
              logstr += ' add(CNY_0)';
            }
            if (usdMap.get(prd.Id) == null) {
              PricebookEntry pbe = new PricebookEntry();
              pbe.Pricebook2Id    = pricebookId;
              pbe.Product2Id      = prd.Id;
              pbe.CurrencyIsoCode = 'USD';
              pbe.UnitPrice       = 0;
              pbe.IsActive        = prd.IsActive;
              pbeInsertList.add(pbe);
              logstr += ' add(USD_0)';
            }
            logstr += ' ';
          }
          if (pbeInsertList.size() > 0) {
            insert pbeInsertList;
          }
        }
      }
      logstr += '\nend';
      rowData.retry_cnt__c = 0;
    } catch (Exception ex) {
      // エラーが発生した場合
      Database.rollback(sp);
      System.debug(Logginglevel.ERROR, 'MDMITM_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
      System.debug(Logginglevel.ERROR, 'MDMITM_' + rowData.MessageGroupNumber__c + ':' + ex.getStackTraceString());
      logstr += '\n' + ex.getMessage();
      iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
      if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
      if (rowData.retry_cnt__c < batch_retry_max_cnt) {
        rowData.retry_cnt__c++;
        LogAutoSendSchedule.assignOneMinute();
      }
      if (rowData.retry_cnt__c >= batch_retry_max_cnt) {
        rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c + '错误次数已经超过自动收信设定的最大次数，请手动收信';
      }
    }
    update rowData;
    iflog.Log__c = logstr;
    if (iflog.Log__c.length() > 131072) {
      iflog.Log__c = iflog.Log__c.subString(0, 131065) + ' ...';
    }
    if (iflog.ErrorLog__c.length() > 32768) {
      iflog.ErrorLog__c = iflog.ErrorLog__c.subString(0, 32760) + ' ...';
    }
    update iflog;
  }
    //HHOA-BLZCYF MDM：新增字段传输 精琢技术 2020/03/24 start
    global static Product2 upsertProduct(Boolean flag ,Product2 prd,String CN_String2,String  CN_Dec1,BatchIF_Log__c iflog,Map<String, String> transferMap ) {
        if(flag ==false){

            if(CN_String2 != null && CN_Dec1 !=null){
                if(CN_String2 =='服务保修对象'){
                    prd.Extend_new_product_gurantee__c = true;
                    prd.Entend_gurantee_period__c = NFMUtil.getMapValue(transferMap, 'Entend_gurantee_period__c', CN_Dec1, iflog);
                }else if(CN_String2 =='市场保修对象'){
                     prd.Extend_new_product_gurantee_MD__c =true;
                    prd.Entend_gurantee_period_MD__c = NFMUtil.getMapValue(transferMap, 'Entend_gurantee_period__c', CN_Dec1, iflog);
                }
            }
                    
        }
        return prd;
    }
//HHOA-BLZCYF MDM：新增字段传输 精琢技术 2020/03/24 end

}