// RowDataを残すしてから execute にします(@future ではない)
global class MDMITMWebService {
    public static boolean isRunning = false;
    // Integer batchsize = 200;  考量する必要がないと思います。
    global class ItemMasters {
        webservice NFMUtil.Monitoring Monitoring;
        webservice MDMITMWebService.ItemMaster[] ItemMaster;
    }
    global class ItemMaster {
        webservice String InterfaceNumber;
        webservice Integer RecordCount;
        webservice MDMITMWebService.Record[] Record;
    }
    global class Record {
        webservice String MaterialNumber;
        webservice MDMITMWebService.MaterialDescription[] MaterialDescription;
        webservice String ModelForSales;
        webservice String RepairCode;
        webservice String Layer1st;
        webservice String Layer2nd;
        webservice String Layer3rd;
        webservice String Layer4th;
        webservice String Layer5th;
        webservice MDMITMWebService.ProductLotSerialNoTraceability[] ProductLotSerialNoTraceability;
        webservice Integer LifeTime;
        webservice String MCompany;
        webservice String BaseUnitOfMeasure;
        webservice MDMITMWebService.BusinessSegmentName BusinessSegmentName;
        webservice String To;

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

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

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

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

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

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

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

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

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

    global class MaterialClassificationCode{
        webservice String Value;
    }

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

    global class ProductDiscontinuationDate{
        webservice String Value;
    }

    global class RepairableUnrepairable{
        webservice String Value;
    }

    global class DangerousGoodsFlag{
        webservice String Value;
    }

    global class UNNumber1{
        webservice Integer Value;
    }

    global class UNNumber2{
        webservice Integer Value;
    }

    global class UNNumber3{
        webservice Integer Value;
    }

    global class UNNumber4{
        webservice Integer Value;
    }

    global class DangerClass1A{
        webservice String Value;
    }

    global class DangerClass1B{
        webservice String Value;
    }

    global class DangerClass2A{
        webservice String Value;
    }

    global class DangerClass2B{
        webservice String Value;
    }

    global class DangerClass3A{
        webservice String Value;
    }

    global class DangerClass3B{
        webservice String Value;
    }

    global class DangerClass4A{
        webservice String Value;
    }

    global class DangerClass4B{
        webservice String Value;
    }

    global class UNPackingGroup1{
        webservice String Value;
    }

    global class UNPackingGroup2{
        webservice String Value;
    }

    global class UNPackingGroup3{
        webservice String Value;
    }

    global class UNPackingGroup4{
        webservice String Value;
    }

    global class ProperShippingName1{
        webservice String Value;
    }

    global class ProperShippingName2{
        webservice String Value;
    }

    global class ProperShippingName3{
        webservice String Value;
    }

    global class ProperShippingName4{
        webservice String Value;
    }

    global class WEEEClassification{
        webservice String Value;
    }

    global class WEEE2Classification{
        webservice String Value;
    }

    global class WEEEWeight{
        webservice Decimal Value;
    }

    global class BatteryType1{
        webservice String Value;
    }

    global class BatterySystemName1{
        webservice String Value;
    }

    global class BatteryQuantity1{
        webservice Integer Value;
    }

    global class BatteryWeight1{
        webservice Decimal Value;
    }

    global class BatteryType2{
        webservice String Value;
    }

    global class BatterySystemName2{
        webservice String Value;
    }

    global class BatteryQuantity2{
        webservice Integer Value;
    }

    global class BatteryWeight2{
        webservice Decimal Value;
    }

    global class GlassWeight{
        webservice Decimal Value;
    }

    global class PaperCardboardWeight{
        webservice Decimal Value;
    }

    global class SteelWeight{
        webservice Decimal Value;
    }

    global class AluminiumWeight{
        webservice Decimal Value;
    }

    global class PlasticWeight{
        webservice Decimal Value;
    }

    global class EPSWeight{
        webservice Decimal Value;
    }

    global class WoodWeight{
        webservice Decimal Value;
    }

    global class SalesPackagingUnit{
        webservice String Value;
    }

    global class HSCodeCustomCodes{
        webservice String Value;
    }

    global class DualUseIndicator{
        webservice String Value;
    }

    global class SupplierProductNumber{
        webservice String Value;
    }

    global class BusinessSegmentCode{
        webservice String Value;
    }

    global class BusinessGroup{
        webservice String Value;
    }

    global class OtherWeight{
        webservice Decimal Value;
    }

    global class CarbonFootprint{
        webservice Decimal Value;
    }

    global class COSHH{
        webservice String Value;
    }

    global class RoHS{
        webservice String Value;
    }

    global class REACH{
        webservice String Value;
    }

    global class SKU_QtyPerPallet{
        webservice String Value;
    }

    global class MultiPackGTIN{
        webservice String Value;
    }

    global class MultiPack {
        webservice String Value;
    }

    global class SinglePackGTIN{
        webservice String Value;
    }

    global class SinglePack{
        webservice String Value;
    }

    global class DeviceGTIN{
        webservice String Value;
    }

    global class DPM{
        webservice String Value;
    }

    global class ProductionDateFlag{
        webservice String Value;
    }

    global class GS1_128Flag{
        webservice String Value;
    }

    global class MultiPackWidth{
        webservice String Value;
    }

    global class MultiPackHeight{
        webservice String Value;
    }

    global class MultiPackLength{
        webservice String Value;
    }

    global class MultiPackWeight{
        webservice String Value;
    }

    global class VirtualItemFlag{
        webservice String Value;
    }

    global class ManufacturerSite{
        webservice String Value;
    }
    //========xinhonglu=======add=====End=============20180827===========
    
    // 非同期を見せかけ、常にreturn void
    webservice static void MDMITM(MDMITMWebService.ItemMasters ItemMasters) {
        if (ItemMasters == null) {
            return;
        }
        NFMUtil.Monitoring Monitoring = ItemMasters.Monitoring;
        if (Monitoring == null) {
            return;
        }
        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'MDMITM', ItemMasters.ItemMaster);
        if (String.isBlank(rowData.Log__c) == false) executefuture(rowData.Id);
    }

    @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];
        MDMITMWebService.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 (MDMITMWebService.ItemMaster ItemMaster : itemMasterList) {
                for (MDMITMWebService.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
                                        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 (MDMITMWebService.ItemMaster ItemMaster : itemMasterList) {
                for (MDMITMWebService.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）
                    Product2 prd = prdsMap.get(Record.MaterialNumber);
                    String prdName = null;
                    if (prd == null) {
                        // 新規の場合 LanguageKey が ZH 商品のみ受信
                        Boolean isZh = false;
                        if (Record.MaterialDescription != null) {
                            for (MDMITMWebService.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;
                        }
                    } else {
                        // 更新の場合 LanguageKey が ZH の名前の更新が受付けする
                        if (Record.MaterialDescription != null) {
                            for (MDMITMWebService.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();
                            prd.Name = (prd.MDM_Model_No__c == '' ? prd.ProductCode : prd.MDM_Model_No__c) + ':' + mc.group(3).trim();
                        } 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();
                                prd.Name = (prd.MDM_Model_No__c == '' ? prd.ProductCode : prd.MDM_Model_No__c) + ':' + mc.group(3).trim();
                            }
                        }
                        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(); 
                                prd.Name = (prd.MDM_Model_No__c == '' ? prd.ProductCode : prd.MDM_Model_No__c) + ':' + mc.group(2).trim();
                            } else {
                                pt = Pattern.compile('(.*)：(.*)');
                                mc = pt.matcher(prdName);
                                if (mc.matches()) {
                                    prd.MDM_Model_No__c = mc.group(1).trim();
                                    prd.Name = (prd.MDM_Model_No__c == '' ? prd.ProductCode : prd.MDM_Model_No__c) + ':' + mc.group(2).trim();
                                }
                            }
                        }
                        
                        // 上記以外のパターン
                        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);
                            }
                            prd.Name = prd.ProductCode + ':' + prd.Name.trim();
                        }
                    }
                    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）

                    //=======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(MDMITMWebService.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;
    }

    
}