package com.foreverwin.mesnac.dataimport.util;

import com.alibaba.fastjson.JSONObject;
import com.sap.me.common.AttributeValue;
import com.sap.me.common.CustomValue;
import com.sap.me.common.ObjectReference;
import com.sap.me.customdata.*;
import com.sap.me.demand.SFCBOHandle;
import com.sap.me.extension.Services;
import com.sap.me.frame.BasicBOBeanException;
import com.sap.me.frame.Data;
import com.sap.me.frame.Utils;
import com.sap.me.frame.domain.BusinessException;
import com.sap.me.frame.service.CommonMethods;
import com.sap.me.frame.transitionutils.Exceptions;
import com.sap.me.messaging.*;
import com.sap.me.numbering.*;
import com.sap.me.productdefinition.BOMBOHandle;
import com.sap.me.productdefinition.BOMConfigurationServiceInterface;
import com.sap.me.productdefinition.BOMFullConfiguration;
import com.sap.me.productdefinition.ReadBOMRequest;
import com.sap.me.production.SfcConfiguration;
import com.sap.me.production.SfcStateServiceInterface;
import com.sap.me.user.UserBasicConfiguration;
import com.sap.me.user.UserConfigurationServiceInterface;
import com.sap.tc.logging.Category;
import com.sap.tc.logging.Location;
import com.sap.tc.logging.Severity;
import com.sap.tc.logging.SimpleLogger;
import com.visiprise.globalization.DateGlobalizationServiceInterface;
import com.visiprise.globalization.GlobalizationService;
import com.visiprise.globalization.KnownGlobalizationServices;
import com.visiprise.globalization.ResourceBundleGlobalizationServiceInterface;
import com.visiprise.globalization.util.DateTimeInterface;
import com.visiprise.globalization.util.LocaleContextType;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

public class AppUtil {
    private static final String CUSTOM_DATA_SERVICE = "CustomDataService";
    private static final String COM_SAP_ME_CUSTOMDATA = "com.sap.me.customdata";
    private static final String COM_SAP_ME_ACTIVITY = "com.sap.me.activity";
    private static final String ACTIVITYCONFIGURATIONSERVICE = "ActivityConfigurationService";
    private static final String BOM_PACKAGE = "com.sap.me.productdefinition";
    private static final String BOMSERVICE = "BOMConfigurationService";
    private static final String USERCONF_SERVICE = "UserConfigurationService";
    private static final String USERCONF_PACK = "com.sap.me.user";
    private static final String CUSTOM_DATA_CONFIGURATION_SERVICE = "CustomDataConfigurationService";


    /**
     * 通用 查找 项目别名+自定义数据属性 配置项
     *
     * @param site
     * @param objalia 项目别名 如 USR、BOM等
     * @param attrib  自定义数据属性
     * @return N(找不到), Y(找到), NG(异常)
     */
    public static String findCustomFieldConfig(String site, String objalia, String attrib) {
        String ret = "N";
        CustomDataConfigurationServiceInterface customDataConfigurationService = Services.getService(COM_SAP_ME_CUSTOMDATA, CUSTOM_DATA_CONFIGURATION_SERVICE, site);
        try {

            FindCustomFieldDefinitionRequest request = new FindCustomFieldDefinitionRequest();
            request.setObjectAlias(objalia);
            Collection<CustomFieldBasicConfiguration> customFields = customDataConfigurationService.findCustomFieldConfigurationsByCategory(request);
            if (customFields.isEmpty()) {
                ret = "N";
            } else {
                for (CustomFieldBasicConfiguration con : customFields) {
                    if (attrib.equals(con.getFieldName())) {
                        ret = "Y";
                        break;
                    }

                }

            }

        } catch (BusinessException e) {
            SimpleLogger.log(Severity.ERROR, Category.SYS_SERVER, Location.getLocation("SystemOper"), "findCustomFieldConfig", e.toString());
            ret = "NG" + e.getMessage();
        }

        return ret;

    }

    /**
     * 通用 创建 项目别名+自定义数据属性 配置项
     * @param site
     * @param objalia 项目别名 如 USR、BOM等
     * @param attrib 自定义数据属性
     * @return Y(成功), NG(失败)
     */
	/*
	public static String createCustomFieldConfig(String site,String objalia,String attrib)
	{
		String ret="Y";
		CustomDataConfigurationServiceInterface customDataConfigurationService=Services.getService(COM_SAP_ME_CUSTOMDATA, CUSTOM_DATA_CONFIGURATION_SERVICE,site);
		try
		{
			List<CustomFieldTranslation> customFieldTranslationList=new ArrayList<CustomFieldTranslation>();
			CustomFieldTranslation fieldTranslation=new CustomFieldTranslation();
			fieldTranslation.setFieldLabel(attrib);
			fieldTranslation.setLocale("zh");
			
			customFieldTranslationList.add(fieldTranslation);
			CustomFieldConfiguration fieldConfig=new CustomFieldConfiguration();
			fieldConfig.setFieldName(attrib);
			fieldConfig.setFieldLabel(attrib);
			fieldConfig.setObjectAlias(objalia);
			fieldConfig.setSequence(new BigDecimal(1));
			fieldConfig.setCustomFieldTranslationList(customFieldTranslationList);
			customDataConfigurationService.createCustomFieldConfiguration(fieldConfig);
			
		}catch(BusinessException e)
		{
			SimpleLogger.log( Severity.ERROR, Category.SYS_SERVER, Location.getLocation( "SystemOper" ), "createCustomFieldConfig", e.toString() );
			ret = "NG"+e.getMessage();
		}
		
		return ret;
		
	}
	*/


    /**
     * 通用保存各项自定义数据
     *
     * @param objalia 项目别名 如 USR、BOM等
     * @param site
     * @param objbo   指定的项目handle
     * @param attrib  自定义数据属性
     * @param value   自定义数据值
     * @return
     */
    public static boolean saveCustomData(String site, String objalia, String objbo, String attrib, String value) {
        boolean ret = true;
        CustomDataServiceInterface customDataService = Services.getService(COM_SAP_ME_CUSTOMDATA, CUSTOM_DATA_SERVICE, site);
        ReadCustomDataRequest custDataRequest = new ReadCustomDataRequest();
        custDataRequest.setObjectAlias(objalia);
        custDataRequest.setRef(objbo);
        Collection<CustomValue> customValueList;
        try {
            customValueList = customDataService.readCustomDataForObject(custDataRequest);

            SaveCustomDataRequest request = new SaveCustomDataRequest();
            List<CustomValue> customData = new ArrayList<CustomValue>();
            CustomValue attribute = null;
            for (Iterator<CustomValue> iterator = customValueList.iterator(); iterator.hasNext(); ) {
                CustomValue customValue = (CustomValue) iterator.next();
                if (!customValue.getName().equals(attrib)) {
                    attribute = new CustomValue();
                    attribute.setName(customValue.getName());
                    attribute.setValue(customValue.getValue());
                    customData.add(attribute);
                }
            }
            if (value != null && !"".equals(value.trim())) {
                attribute = new CustomValue();
                attribute.setName(attrib);
                attribute.setValue(value);
                customData.add(attribute);
            }
            request.setCustomData(customData);
            request.setObjectAlias(objalia);
            request.setRef(objbo);
            customDataService.saveCustomData(request);
        } catch (BusinessException e) {
            SimpleLogger.log(Severity.ERROR, Category.SYS_SERVER, Location.getLocation("SystemOper"), "SaveCustomData", e.toString());
            ret = false;
        }
        return ret;
    }

    /**
     * 通过BO和类型获取自定义字段维护值
     *
     * @param site
     * @param objalia
     * @param objbo
     * @return
     */
    public static Collection<CustomValue> getCustomData(String site, String objalia, String objbo) {
        CustomDataServiceInterface customDataService = Services.getService(COM_SAP_ME_CUSTOMDATA, CUSTOM_DATA_SERVICE, site);
        ReadCustomDataRequest custDataRequest = new ReadCustomDataRequest();
        custDataRequest.setObjectAlias(objalia);
        custDataRequest.setRef(objbo);
        Collection<CustomValue> customValueList = null;
        try {
            customValueList = customDataService.readCustomDataForObject(custDataRequest);
            return customValueList;
        } catch (BusinessException e) {
            SimpleLogger.log(Severity.ERROR, Category.SYS_SERVER, Location.getLocation("SystemOper"), "SaveCustomData", e.toString());
        }
        return customValueList;
    }

    /**
     * 获取指定属性的值
     * 如果指定属性的值为空,则返回默认的值
     *
     * @param customValueList
     * @param attrib
     * @param defaultVal
     * @return
     */
    public static String getCustomDataByAttr(Collection<CustomValue> customValueList, String attrib, String defaultVal) {
        for (Iterator<CustomValue> iterator = customValueList.iterator(); iterator.hasNext(); ) {
            CustomValue customValue = (CustomValue) iterator.next();
            if (customValue.getName().equals(attrib)) {
                return customValue.getValue() == null ? defaultVal : customValue.getValue().toString();
            }
        }
        return defaultVal;
    }


    public static BOMFullConfiguration readBOM(String site, String BOM, String rev) {
        BOMConfigurationServiceInterface service = Services.getService(BOM_PACKAGE, BOMSERVICE, site);
        ReadBOMRequest request = new ReadBOMRequest();
        BOMBOHandle handle = new BOMBOHandle(site, BOM, "U", rev);
        request.setBomRef(handle.getValue());
        try {
            return service.readBOM(request);
        } catch (BusinessException e) {
            SimpleLogger.log(Severity.ERROR, Category.SYS_SERVER, Location.getLocation("SystemOper"), "readBOM", e.toString());
        }
        return null;
    }

    /**
     * 根据用户HANDLE获取用户相关信息
     *
     * @param site
     * @param handle
     */
    public static UserBasicConfiguration getUserInfo(String site, String handle) throws BasicBOBeanException {
        //		ApplicationVO result = new ApplicationVO();
        //FindUserBySiteAndUserIdRequest request = new FindUserBySiteAndUserIdRequest(site, userid);
        UserConfigurationServiceInterface userConfigurationService = Services.getService(USERCONF_PACK, USERCONF_SERVICE, site);
        UserBasicConfiguration user = null;
        try {
            user = userConfigurationService.findUserByRef(new ObjectReference(handle));
            //UserBasicConfiguration user = userConfigurationService.findUserBySiteAndUserId(request);
            //			result.setValue("USERID", user.getUserId());
            //			result.setValue("LASTNAME", user.getLastName()); //姓
            //			result.setValue("FIRSTNAME", user.getFirstName()); //名
            //			result.setValue("EMAIL", user.getEmail());
            //			result.setValue("STATUS", user.getStatus().toString());
            //			result.setValue("EMPNUMBER", user.getEmployeeNumber());  //用户编号
        } catch (BusinessException e) {
            SimpleLogger.log(Severity.ERROR, Category.SYS_SERVER, Location.getLocation("SystemOper"), "getUserInfo", "查找人员信息出现异常！" + e.toString());
        }
        return user;
    }

    /**
     * 获得当前时间
     *
     * @return
     */
    public static DateTimeInterface getCurdate() {
        DateGlobalizationServiceInterface dateservice = GlobalizationService.getInvariantService(KnownGlobalizationServices.DATE);
        DateTimeInterface datetime = dateservice.createDateTime();
        return datetime;
    }

    /**
     * 将格式为 yyyy-MM-dd HH:mm:ss的字符串转换成DateTimeInterface类型
     *
     * @param dateStr
     * @return
     */
    public static DateTimeInterface coverDateTimeFromString(String dateStr) {
        DateGlobalizationServiceInterface dateService = GlobalizationService.getUserService(KnownGlobalizationServices.DATE);
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = sdf.parse(dateStr);
            Calendar ca = Calendar.getInstance();
            ca.setTime(date);
            return dateService.createDateTime(ca.get(Calendar.YEAR), ca.get(Calendar.MONTH), ca.get(Calendar.DATE), ca.get(Calendar.HOUR_OF_DAY), ca.get(Calendar.MINUTE), ca.get(Calendar.SECOND));
        } catch (ParseException e) {
            SimpleLogger.log(Severity.ERROR, Category.SYS_SERVER, Location.getLocation("SystemOper"), "coverDateTimeFromString", e.toString());
            return null;
        }
    }

    /**
     * @return Date
     */
    public static Date convertDateTimeToDate(DateTimeInterface dateTimeInterface, String format) {
        if (format == null || "".equals(format)) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        long timeMillis = dateTimeInterface.getTimeInMillis();
        Date date = new Date(timeMillis);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        String dateStr = simpleDateFormat.format(date);
        try {
            return simpleDateFormat.parse(dateStr);
        } catch (ParseException e) {
            SimpleLogger.log(Severity.ERROR, Category.SYS_SERVER, Location.getLocation("SystemOper"), "convertDateTimeToDate", e.toString());
            return null;
        }
    }

    public static String formateDate(Date date) {
        Format df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String newDate = df.format(date);
        return newDate;
    }

    public static Date getDate(String dateStr, String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        try {
            Date date = df.parse(dateStr);
            return date;
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 验证是否是yyyy/MM/dd日期格式的字符串
     */
    public static boolean isValidateString(String dateStr) {
        Pattern p = Pattern.compile("^((\\d{2}(([02468][048])|([13579][26]))[\\/\\/\\s]?((((0?" + "[13578])|(1[02]))[\\/\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))" + "|(((0?[469])|(11))[\\/\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|" + "(0?2[\\/\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][12" + "35679])|([13579][01345789]))[\\/\\/\\s]?((((0?[13578])|(1[02]))" + "[\\/\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))" + "[\\/\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\/\\/\\s]?((0?[" + "1-9])|(1[0-9])|(2[0-8]))))))");
        return p.matcher(dateStr).matches();
    }

    /**
     * 从数据库获取0时区的字符串时间转换成当地时间
     *
     * @return Date
     */
    public static Date getLocalChangeTimeZone(String dateStr) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        TimeZone timeZone = cal.getTimeZone();
        Date date = format.parse(dateStr);
        Date dateTmp = null;
        if (date != null) {
            int timeOffset = timeZone.getRawOffset() + TimeZone.getTimeZone("GMT").getRawOffset();
            dateTmp = new Date(date.getTime() + timeOffset);
        }
        return dateTmp;
    }

    /**
     * 从数据库获取0时区的时间转换成当地时间
     *
     * @param Date date
     * @return Date
     */
    public static Date getGMT0CastLocalTime(Date date) {
        Calendar cal = Calendar.getInstance();
        TimeZone timeZone = cal.getTimeZone();
        if (date != null) {
            int timeOffset = timeZone.getRawOffset() + TimeZone.getTimeZone("GMT").getRawOffset();
            date = new Date(date.getTime() + timeOffset);
        }
        return date;
    }

    /**
     * 从数据库获取0时区的时Timestamp间转换成当地时间
     *
     * @param Date date
     * @return String
     */
    public static String getGMT0TimestampCastLocalTime(Timestamp timestamp) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        TimeZone timeZone = cal.getTimeZone();
        Date date = timestamp;
        String dateStr = "";
        if (date != null) {
            int timeOffset = timeZone.getRawOffset() + TimeZone.getTimeZone("GMT").getRawOffset();
            date = new Date(date.getTime() + timeOffset);
            dateStr = dateFormat.format(date);
        }
        return dateStr;
    }

    /**
     * 系统时间减去0时区的时间存入数据库中
     */
    public static Date getLocalChangeTimeZone(Date sysDate) throws ParseException {
        Calendar cal = Calendar.getInstance();
        TimeZone timeZone = cal.getTimeZone();
        Date date = sysDate;
        Date dateTmp = null;
        if (date != null) {
            int timeOffset = timeZone.getRawOffset() - TimeZone.getTimeZone("GMT").getRawOffset();
            dateTmp = new Date(date.getTime() - timeOffset);
        }
        return dateTmp;
    }

    /**
     * 传入yyyy-MM-dd HH:mm:ss字符串时间格式，转换成0时区日期格式
     *
     * @return Date
     * @throws ParseException
     */
    public static Date getGMTZeroDate(String dateStr) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        TimeZone timeZone = cal.getTimeZone();
        Date date = format.parse(dateStr);
        Date dateTmp = null;
        if (date != null) {
            int timeOffset = timeZone.getRawOffset() - TimeZone.getTimeZone("GMT").getRawOffset();
            dateTmp = new Date(date.getTime() - timeOffset);
        }
        return dateTmp;
    }

    /**
     * 0时区的字符串时间yyyy-MM-dd HH:mm:ss转换成当地时间
     *
     * @return String
     */
    public static String getLocalChangeTimeZoneStr(String dateStr) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        TimeZone timeZone = cal.getTimeZone();
        Date date = format.parse(dateStr);
        Date dateTmp = null;
        if (date != null) {
            int timeOffset = timeZone.getRawOffset() + TimeZone.getTimeZone("GMT").getRawOffset();
            dateTmp = new Date(date.getTime() + timeOffset);
        }
        return format.format(dateTmp);
    }

    /**
     * 从页面获取到的字符串时间yyyy-MM-dd HH:mm:ss减8小时，从而获得国际时间
     *
     * @return String
     */
    public static String getReduceTime(String dateStr) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        TimeZone timeZone = cal.getTimeZone();
        Date date = format.parse(dateStr);
        Date dateTmp = null;
        if (date != null) {
            int timeOffset = timeZone.getRawOffset() - TimeZone.getTimeZone("GMT").getRawOffset();
            dateTmp = new Date(date.getTime() - timeOffset);
        }
        return format.format(dateTmp);
    }

    public static String getReduceTimeByAndy(String dateStr) throws BusinessException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        TimeZone timeZone = cal.getTimeZone();
        Date date;
        try {
            date = format.parse(dateStr);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            throw new BusinessException(0, e.getMessage());
        }
        Date dateTmp = null;
        if (date != null) {
            int timeOffset = timeZone.getRawOffset() - TimeZone.getTimeZone("GMT").getRawOffset();
            dateTmp = new Date(date.getTime() - timeOffset);
        }
        return format.format(dateTmp);
    }

    /**
     * 获取国际化语言
     *
     * @param key
     * @return
     */
    public static String getBundleString(String key) {
        String retVal = null;
        ResourceBundleGlobalizationServiceInterface service = (ResourceBundleGlobalizationServiceInterface) GlobalizationService.getService(LocaleContextType.USER, "com.sap.me.globalization.LocaleSpecificTextResourcesGlobalizationService");
        if (key != null) {
            key = key.trim();
            retVal = service.getString(key, key);
        }
        return retVal;
    }

    /**
     * 获取LocaleSpecificText国际化语言
     *
     * @param key
     * @param data
     */
    public static String getLocaleSpecificText(String key, Data data) {
        String retVal = "";
        ResourceBundleGlobalizationServiceInterface service = (ResourceBundleGlobalizationServiceInterface) GlobalizationService.getService(LocaleContextType.USER, "com.sap.me.globalization.LocaleSpecificTextResourcesGlobalizationService");
        if (key != null && key.trim().length() > 0) {
            key = key.trim();
            retVal = service.getString(key, key);
            if (data != null && data.size() > 0) {
                retVal = Utils.replaceParameters(data, retVal);
            }
        }
        return retVal;
    }

    /**
     * 更新状态描述国际化语言
     *
     * @param statusData
     * @return
     * @throws BasicBOBeanException
     */
    private static Data modifyStatusDataList(Data statusData) throws BasicBOBeanException {
        for (int i = 0, size = statusData.size(); i < size; i++) {
            String statusCode = (String) statusData.get("STATUS", i);
            String bundleKey = (new StringBuilder()).append("STATUS.STATUS_DESCRIPTION.").append(statusCode).toString();
            String localizedDescription = getBundleString(bundleKey);
            if (localizedDescription != null) {
                String description = localizedDescription;
                statusData.put("STATUS_DESCRIPTION", description, i);
            }
        }
        return statusData;
    }


    @SuppressWarnings({"unchecked", "rawtypes"})
    public static List<Map<String, Object>> getAllSitesForUser(String userId) throws BusinessException {
        List res = new ArrayList();

        return res;
    }

    public static void getWorkStationApplications(String workStationId) {

    }

    public static void sendMEMessage(String messageType, String content, Map<String, Object> messageParam) throws BusinessException {

        String messageTypeRef = "";
        String messageSubject = "";
        String messageBody = "";

        MessageServiceInterface messageService = Services.getService("com.sap.me.messaging", "MessageService");
        MessageTypeConfigurationServiceInterface messageTypeConfigService = Services.getService("com.sap.me.messaging", "MessageTypeConfigurationService");

        FindMessageTypeRequest messageTypeRequest = new FindMessageTypeRequest();
        messageTypeRequest.setMessageType(messageType);
        MessageTypeBasicConfiguration messageTypeConfig = null;
        messageTypeConfig = messageTypeConfigService.findMessageTypeConfigurationByName(messageTypeRequest);

        if (messageTypeConfig == null) {
            Data data = new Data();
            data.put("MESSAGE_TYPE", messageType);
            throw Exceptions.convert(new BasicBOBeanException(20123, data));
        }
        messageTypeRef = messageTypeConfig.getRef();
        messageSubject = messageTypeConfig.getSubject();
        messageBody = messageTypeConfig.getBody();

        List<AttributeValue> payloadAttributeList = new ArrayList<AttributeValue>();
        if (messageParam == null) {
            messageBody = messageBody.replaceAll("%MESSAGE%", content);
        } else {
            for (String key : messageParam.keySet()) {
                messageBody = messageBody.replaceAll("%" + key + "%", messageParam.get(key) == null ? "" : messageParam.get(key).toString());
            }

            if (messageParam.get("RESOURCE_BO") != null && !"null".equals(messageParam.get("RESOURCE_BO").toString()) && !"".equals(messageParam.get("RESOURCE_BO").toString())) {
                AttributeValue aValue = new AttributeValue();
                aValue.setAttribute("RESOURCE_BO");
                aValue.setValue(messageParam.get("RESOURCE_BO").toString());
                payloadAttributeList.add(aValue);
            }
            if (messageParam.get("WORK_CENTER_BO") != null && !"null".equals(messageParam.get("WORK_CENTER_BO").toString()) && !"".equals(messageParam.get("WORK_CENTER_BO").toString())) {
                AttributeValue aValue = new AttributeValue();
                aValue.setAttribute("WORK_CENTER_BO");
                aValue.setValue(messageParam.get("WORK_CENTER_BO").toString());
                payloadAttributeList.add(aValue);
            }
        }

        CreateFreeFormMessageRequest request = new CreateFreeFormMessageRequest();
        request.setMessageTypeRef(messageTypeRef);
        request.setSubject(messageSubject);
        if (payloadAttributeList.size() > 0) {
            request.setPayloadAttributeList(payloadAttributeList);
        }
        if (messageBody.length() >= 1024) {
            request.setBody(messageBody == null ? "" : messageBody.substring(0, 1023));
        } else {
            request.setBody(messageBody);
        }

        //request.setBody( content );
        messageService.createFreeFormMessage(request);
    }

    public static void sendMEMessage(String messageType, String content) throws BusinessException {
        sendMEMessage(messageType, content, null);
    }

    /**
     * @param messageType
     * @param messageParam, 参考:https://help.sap.com/saphelp_me151/helpdata/EN/68/8139E18A8E4EE08CADDA1FC8F62C8B/frameset.htm
     */
    public static void sendMEMessage(String messageType, Map<String, Object> messageParam) throws BusinessException {

        MessageServiceInterface messageService = Services.getService("com.sap.me.messaging", "MessageService");

        String site = CommonMethods.getSite();
        String messageTypeRef = new MessageTypeBOHandle(site, messageType).getValue();

        List<AttributeValue> payloadAttributeList = new ArrayList<AttributeValue>();

        if (messageParam == null)
            messageParam = new HashMap<String, Object>();

        for (String key : messageParam.keySet()) {

            AttributeValue req = new AttributeValue();
            req.setAttribute(key);
            req.setValue(messageParam.get(key) == null ? "" : messageParam.get(key).toString());
            payloadAttributeList.add(req);
        }

        CreateMessageRequest request = new CreateMessageRequest();
        request.setMessageTypeRef(messageTypeRef);
        request.setPayloadAttributeList(payloadAttributeList);

        messageService.createMessage(request);
    }

    /**
     * 通过物料HANDLE,工单HANDLE,数量生成sfc编号,数量代表生成几个sfc编号
     *
     * @param itemBo
     * @param shopOrderBo
     * @param sfcNumber
     * @return
     * @throws NextNumberNotLoadedException
     * @throws NextNumberSequenceExceededException
     * @throws NextNumberConcurrencyException
     * @throws NextNumberInvalidFormatException
     * @throws NextNumberLengthException
     * @throws BusinessException
     */
    public static List<String> getNextSFCNo(String itemBo, String shopOrderBo, int sfcNumber) throws NextNumberNotLoadedException, NextNumberSequenceExceededException, NextNumberConcurrencyException, NextNumberInvalidFormatException, NextNumberLengthException, BusinessException {

        NumberingServiceInterface numberingService = Services.getService("com.sap.me.numbering", "NumberingService");
        //生成的sfc序列
        GenerateNextNumberRequest generateNextNumberRequest = new GenerateNextNumberRequest();
        generateNextNumberRequest.setItemRef(itemBo);
        generateNextNumberRequest.setShopOrderRef(shopOrderBo);
        generateNextNumberRequest.setNumberOfValues(new BigDecimal(sfcNumber));
        generateNextNumberRequest.setNextNumberType(NextNumberTypeEnum.SFCRELEASE);
        GenerateNextNumberResponse generateNextNumberResponse = numberingService.generateNextNumber(generateNextNumberRequest);
        List<String> idList = generateNextNumberResponse.getId();
        return idList;
    }

    /**
     * 通过sfc编号和sfc个数获取下一sfc编号,
     */
    public static List<String> getNextSFCNo(String sfc, int sfcNumber) throws NextNumberNotLoadedException, NextNumberSequenceExceededException, NextNumberConcurrencyException, NextNumberInvalidFormatException, NextNumberLengthException, BusinessException {

        NumberingServiceInterface numberingService = Services.getService("com.sap.me.numbering", "NumberingService");
        SfcStateServiceInterface stateServiceInterface = Services.getService("com.sap.me.production", "SfcStateService");
        String site = CommonMethods.getSite();
        SFCBOHandle sfcHandelBO = new SFCBOHandle(site, sfc);
        SfcConfiguration sfcConfiguration = stateServiceInterface.readSfc(sfcHandelBO.getValue());
        //生成的sfc序列
        GenerateNextNumberRequest generateNextNumberRequest = new GenerateNextNumberRequest();
        generateNextNumberRequest.setItemRef(sfcConfiguration.getItemRef());
        generateNextNumberRequest.setShopOrderRef(sfcConfiguration.getShopOrderRef());
        generateNextNumberRequest.setNumberOfValues(new BigDecimal(sfcNumber));
        generateNextNumberRequest.setNextNumberType(NextNumberTypeEnum.SFCRELEASE);
        GenerateNextNumberResponse generateNextNumberResponse = numberingService.generateNextNumber(generateNextNumberRequest);
        List<String> idList = generateNextNumberResponse.getId();
        return idList;
    }

    public static String mapKeyFinder(Map<String, String> map, String value) {

        Iterator<String> iter = map.keySet().iterator();
        while (iter.hasNext()) {
            String _key = iter.next();
            String _value = map.get(_key);
            if (value != null && value.trim().equalsIgnoreCase(_value)) {
                return _key;
            }

        }

        return null;
    }

    public static boolean isNull(String[] values) {
        boolean isNull = true;

        if (values != null && values.length > 0) {
            for (String _tmp : values) {
                if (_tmp != null && _tmp.trim().length() > 0) {
                    isNull = false;
                    break;
                }
            }
        }

        return isNull;

    }

    public static boolean isNotNull(String value) {
        boolean isNotNull = false;

        if (value != null && value.trim().length() > 0) {

            isNotNull = true;


        }

        return isNotNull;

    }


    public static boolean isNotNull(String key, JSONObject data) {
        boolean isNotNull = false;

        if (data != null && data.containsKey(key)) {
            if (data.getString(key).trim().length() > 0) {
                isNotNull = true;
            }

        }


        return isNotNull;

    }


    public static boolean canUpdate(String mode) {


        if (mode.equalsIgnoreCase("Both") || mode.equalsIgnoreCase("Update")) {
            return true;
        }
        return false;
    }

    public static boolean canInsert(String mode) {


        if (mode.equalsIgnoreCase("Both") || mode.equalsIgnoreCase("Insert")) {
            return true;
        }
        return false;
    }

    public static String getUTFStringByEncoding(String str) {
        String encode = "UTF-8";
        String returnStr = "";
        try {
            if (str != null) {
                if (str.equals(new String(str.getBytes("GB2312"), "GB2312"))) {
                    encode = "GB2312";
                } else if (str.equals(new String(str.getBytes("ISO-8859-1"), "ISO-8859-1"))) {
                    encode = "ISO-8859-1";
                } else if (str.equals(new String(str.getBytes("UTF-8"), "UTF-8"))) {
                    encode = "UTF-8";
                } else if (str.equals(new String(str.getBytes("GBK"), "GBK"))) {
                    encode = "GBK";
                }
                System.out.println("getUTFStringByEncoding->" + encode + "->" + str);
                if (encode.equals("UTF-8")) {
                    returnStr = str;
                } else {
                    returnStr = new String(str.getBytes(encode), "UTF-8");
                }
            }
        } catch (Exception ex) {
            //	log.error( ex.getMessage());
            ex.printStackTrace();
        }
        return returnStr;

    }

}
