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.exception.BusinessException;
import com.foreverwin.modular.core.meext.MEServices;
import com.sap.me.common.MaterialType;
import com.sap.me.common.ObjectAliasEnum;
import com.sap.me.common.ObjectReference;
import com.sap.me.common.ProcurementType;
import com.sap.me.productdefinition.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 物料主数据操作类
 *
 * @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
     * @return
     */
    public static String insert(JSONObject jsonObject) {
        try {
            String site = (String) jsonObject.get("site");
            String item = jsonObject.getString("item");
            //物料描述
            String itemDescription = jsonObject.getString("itemDesc");
            //计量单位
            String unitOfMeasure = jsonObject.getString("unit");
            //状态
            String statusBo = HandleEnum.STATUS.getHandle(site, "201");

            //物料类型(FERT(已完成)/ROH(原始)/HALB(半成品)/KMAT(可配置)/INST(安装)/VERP(包装)/FHMI(生产资源/工具)/CSTM(自定义))
            String itemTypeDesc = jsonObject.getString("materialType");
            if (!"已完成".equals(itemTypeDesc) && !"原始".equals(itemTypeDesc) && !"半成品".equals(itemTypeDesc)) {
                throw BusinessException.build("物料类型可维护的值为：已完成、原始、半成品");
            }
            String itemType = "ROH";
            switch (itemTypeDesc) {
                case "原始":
                    itemType = "ROH";
                    break;
                case "半成品":
                    itemType = "HALB";
                    break;
                case "已完成":
                    itemType = "FERT";
                    break;
                default:
                    break;
            }

            //采购类型(M(制造)/P(采购)/B(制造/采购))
            String procurementTypeDesc = jsonObject.getString("itemType");
            if (!"制造".equals(procurementTypeDesc) && !"采购".equals(procurementTypeDesc) && !"制造/采购".equals(procurementTypeDesc)) {
                throw BusinessException.build("采购类型可维护的值为：制造、采购、制造/采购");
            }
            String procurementType = "P";
            switch (procurementTypeDesc) {
                case "采购":
                    procurementType = "P";
                    break;
                case "制造/采购":
                    procurementType = "B";
                    break;
                case "制造":
                    procurementType = "M";
                    break;
                default:
                    break;
            }

            //批次大小
            String lotSize = jsonObject.getString("lotSize");
            lotSize = StringUtil.notBlank(lotSize) ? lotSize : "999999";

            //数量限制
            String qtyRestrictionDesc = jsonObject.getString("qtyRestriction");

            //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            //物料标准API
            ItemConfigurationServiceInterface itemServiceInterFace = MEServices.create("com.sap.me.productdefinition", "ItemConfigurationService", site);

            //创建物料
            ItemConfiguration itemConfiguration = new ItemConfiguration();
            itemConfiguration.setItem(item);
            itemConfiguration.setRevision("A");
            itemConfiguration.setProcurementType(ProcurementType.fromValue(procurementType));
            itemConfiguration.setLotSize(new BigDecimal(lotSize));
            itemConfiguration.setRef(HandleEnum.ITEM.getHandle(site, item, "A"));
            itemConfiguration.setCurrentRevision(true);
            itemConfiguration.setUnitOfMeasurement(unitOfMeasure);
            itemConfiguration.setMaterialType(MaterialType.fromValue(itemType));

            String dataTypeBo = "DataTypeBO:" +site+ ",ASSEMBLY,INV_NAC";
            itemConfiguration.setInventoryAssemblyDataTypeRef(dataTypeBo);
            //物料描述赋值
            List<ItemTranslation> itemTranslationList = new ArrayList<>();
            ItemTranslation itemTranslation = new ItemTranslation();
            itemTranslation.setLocale("zh");
            itemTranslation.setDescription(itemDescription);
            itemTranslationList.add(itemTranslation);
            itemConfiguration.setItemTranslationList(itemTranslationList);
            itemConfiguration.setStatusRef(statusBo);
            //数量限制
            switch (qtyRestrictionDesc) {
                case "仅1.0":
                    itemConfiguration.setQuantityRestriction(QuantityRestriction.ONLY_1);
                    break;
                case "任意数字":
                    itemConfiguration.setQuantityRestriction(QuantityRestriction.ANY_NUMBER);
                    break;
                case "整数":
                    itemConfiguration.setQuantityRestriction(QuantityRestriction.WHOLE_NUMBER);
                    break;
                default:
                    itemConfiguration.setQuantityRestriction(QuantityRestriction.ANY_NUMBER);
                    break;
            }

            //创建物料
            itemServiceInterFace.createItem(itemConfiguration);

            //自定义字段保存
            CustomDataWSClient.update(jsonObject, itemConfiguration.getRef(), ObjectAliasEnum.ITEM.value());
        } catch (Exception e) {
            return ExceptionUtil.getExceptionMsg(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);
            }
            // 更新物料描述
            String itemDescription =  jsonObject.getString("itemDesc");
            List<ItemTranslation> itemTranslationList = new ArrayList<>();
            ItemTranslation itemTranslation = new ItemTranslation();
            itemTranslation.setLocale("zh");
            itemTranslation.setDescription(itemDescription);
            itemTranslationList.add(itemTranslation);
            itemFull.setItemTranslationList(itemTranslationList);
            itemConfigurationService.updateItem(itemFull);

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

        return null;
    }
}
