/**********************************************************************
 
*************************************************************************/
@RestResource(urlMapping = '/SBG019/*')
global with sharing class SBG019Rest {
	global class GeDatasRest {
        public GeDatas GeDatas;
    }
	global class GeDatas {
        public NFMUtil.Monitoring Monitoring;
        public GeData[] GeData;
    }

    global class GeData {
    	public String TransforDate; //传输日期
        public GeDataDetails[] GeDataDetails;

        
    }

    global class GeDataDetails {

        public String ProductCode;//物料
        public String ProductDate;//监管产品最早生产日期

    }




    @HttpPost
    global static void execute() {
        // 取得接口传输内容
        String strData = RestContext.request.requestBody.toString();

        GeDatasRest ges = (GeDatasRest) JSON.deserializeStrict(strData, GeDatasRest.class);

        if (ges == null ) {
            return;
        }

        NFMUtil.Monitoring Monitoring = ges.GeDatas.Monitoring;
        if (Monitoring == null) {
            return;
        }

        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'SBG019', ges.GeDatas.GeData);
        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":""}';
        res.responseBody = blob.valueOf(jsonResponse);
        return;
    }

    @future
    global static void executefuture(String rowData_Id) {
        main(rowData_Id);
    }

    global static void main(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];
        String logstr = rowData.MessageGroupNumber__c + ' start\n';
        BatchIF_Log__c iflog = new BatchIF_Log__c();
        iflog.Type__c = 'SBG019';
        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
        iflog.ErrorLog__c = '';
        insert iflog;

        String rowDataStr = NFMUtil.getRowDataStr(rowData);
        List<GeData> geDataList = (List<GeData>) JSON.deserialize(rowDataStr, List<GeData>.class);
        if (geDataList == null || geDataList.size() == 0) {
            return;
        }


        Savepoint sp = Database.setSavepoint();
        String result = '';
        try {
        	// 符合的明细
            Map<String, GeDataDetails> satisfyGeDataDetailMap = RequiredFieldValidator(geDataList, iflog);
            if (satisfyGeDataDetailMap.size() > 0) {
               result = updateProduct(satisfyGeDataDetailMap,iflog);
            }
            logstr += result;
            logstr += '\n End';
            rowData.retry_cnt__c = 0;
            if(Test.isRunningTest()){
                Integer num = Integer.valueOf('TestError');
            }
        }catch (Exception ex) {
            Database.rollback(sp);
            System.debug(Logginglevel.ERROR, 'SBG019_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'SBG019_' + 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 + '错误次数已经超过自动收信设定的最大次数，请手动收信';
            }
        }
        iflog.Log__c = logstr;
        upsert iflog;
        upsert rowData;
    }
    /**
     * 必填字段的验证
     * @Author   XHL
     * @DateTime 2021-07-22
     * @param    geDataList [接口传输数据]
     * @param    iflog      [BatchLog日志]
     * @return              [符合的数据]
     */
    public static Map<String, GeDataDetails> RequiredFieldValidator(List<GeData> geDataList, BatchIF_Log__c iflog) {
        Map<String, GeDataDetails> result = new Map<String, GeDataDetails>();
        for (GeData gda : geDataList) {
            // 传输日期
            if (String.isNotBlank(gda.TransforDate)) {
                
            }

            for (GeDataDetails  geDataDetail : gda.GeDataDetails) {
            	//产品编码
            	if (String.isBlank(geDataDetail.ProductCode)) {
                    iflog.ErrorLog__c += 'ProductCode is required,This data is skipped.\n';
                    continue;
                }
                //监管产品最早生产日期
                if (String.isBlank(geDataDetail.ProductDate)) {
                    iflog.ErrorLog__c += 'ProductCode[ ' + geDataDetail.ProductDate + ' ] of ProductDate is required,This data is skipped.\n';
                    continue;
                }
                String productCode = ZeroPadding(geDataDetail.ProductCode);
                result.put(productCode,geDataDetail);
            }
        }

        return result;
    }

    // 保存产品
    public static String updateProduct(Map<String, GeDataDetails> satisfyGeDataDetailMap, BatchIF_Log__c iflog) {
        String result = '';
    	//根据产品Code查询产品信息
    	List<Product2> getProductList = 
    				[SELECT Id, Name, ProductCode,demoteer_Sap__c 
    				FROM Product2 
    				WHERE ProductCode 
    				IN:satisfyGeDataDetailMap.keyset() 
    				];
    	Map<String, Product2> productMap = new Map<String, Product2>();
    	for(Product2 product:getProductList){
    		productMap.put(product.ProductCode, product);
    	}

        Integer nonexisQuantity = 0;
    	for (String ProductCode : satisfyGeDataDetailMap.keySet()) {
			if (productMap.containsKey(productCode)) {
				GeDataDetails geDataDetails = satisfyGeDataDetailMap.get(productCode);
				Date demoteer_Sap = NFMUtil.parseStr2Date(geDataDetails.ProductDate, false);
            	Product2  product = productMap.get(productCode);
            	product.demoteer_Sap__c = demoteer_Sap;

            	productMap.put(productCode,product);
                result += 'productCode [ ' + productCode + ' ]\n';  
            } else {
                nonexisQuantity +=1;
                iflog.ErrorLog__c += 'productCode [ ' + productCode + ' ] is Nonexistent,This data is skipped.\n';
                continue;
            }	
    	}
        Integer repeatTheNumber = satisfyGeDataDetailMap.size() - productMap.size() -nonexisQuantity;
        result += '共传输 ' + satisfyGeDataDetailMap.size() +'条数据\n';
    	if (productMap.size() > 0) {
    	    update productMap.values();
            result += '更新成功 ' + productMap.size() +'条数据\n';
    	}
        if (repeatTheNumber > 0) {
            result += '重复 ' + repeatTheNumber +'条数据\n';
        }
        if (nonexisQuantity >0) {
            result += '产品不存在 ' + nonexisQuantity +'条数据\n';
        }


        

        return result;
    }

    // 纯数字产品编码进行补零
    public static String ZeroPadding(String productCode) {
        Pattern pattern = Pattern.compile('^[0-9]*$');
        Matcher isNum = pattern.matcher(productCode);
        if (isNum.matches()) {
            productCode = productCode.leftPad(18, '0');
        }

        return productCode;
    }
}