package com.foreverwin.mesnac.dataimport.client;

import com.alibaba.fastjson.JSONObject;
import com.foreverwin.mesnac.common.enums.HandleEnum;
import com.foreverwin.mesnac.common.util.ExceptionUtil;
import com.foreverwin.mesnac.common.util.StringUtil;
import com.foreverwin.modular.core.meext.MEServices;
import com.sap.me.common.ObjectAliasEnum;
import com.sap.me.common.ObjectReference;
import com.sap.me.productdefinition.ItemConfigurationServiceInterface;
import com.sap.me.productdefinition.ItemFullConfiguration;
import com.sap.me.productdefinition.QuantityRestriction;

import java.math.BigDecimal;

/**
 * 物料主数据操作类
 *
 * @author Leon
 * @date 2021/7/6
 */
public class ItemWSClient {

    /**
     * 查询物料
     *
     * @param data
     * @return
     */
    public static ItemFullConfiguration find(JSONObject data) {
        try {
            String site = (String) data.get("site");
            String item = data.getString("item");
            //物料只有一个版本，默认A
            String objRef = HandleEnum.ITEM.getHandle(site, item, "A");

            //----------------------------------------------------------------------------------------------------------
            ItemConfigurationServiceInterface itemConfigurationService = MEServices.create("com.sap.me.productdefinition", "ItemConfigurationService", site);
            ObjectReference objectReference = new ObjectReference(objRef);
            ItemFullConfiguration op = itemConfigurationService.readItem(objectReference);

            return op;
        } catch (Exception e) {
        }

        return null;
    }

    /**
     * 更新物料
     *
     * @param jsonObject
     * @param itemFull
     * @return
     */
    public static String update(JSONObject jsonObject, ItemFullConfiguration itemFull) {
        try {
            String site = jsonObject.getString("site");
            //批次大小
            String lotSize = jsonObject.getString("lotSize");
            lotSize = StringUtil.notBlank(lotSize) ? lotSize : "999999";

            //---------------------------------------------------------------------------------------
            ItemConfigurationServiceInterface itemConfigurationService = MEServices.create("com.sap.me.productdefinition", "ItemConfigurationService", site);
            itemFull.setLotSize(new BigDecimal(lotSize));
            if ("1".equals(lotSize)) {
                itemFull.setQuantityRestriction(QuantityRestriction.ONLY_1);
            } else {
                itemFull.setQuantityRestriction(QuantityRestriction.ANY_NUMBER);
            }
            itemConfigurationService.updateItem(itemFull);

            //自定义字段保存
            CustomDataWSClient.update(jsonObject, itemFull.getRef(), ObjectAliasEnum.ITEM.value());
        } catch (Exception e) {
            return ExceptionUtil.getExceptionMsg(e);
        }

        return null;
    }
}
