package psdi.app.iface.spms;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import jnr.ffi.Struct;
import org.apache.axis2.databinding.types.xsd.Decimal;
import psdi.app.iface.comm.UrlConstants;
import psdi.mbo.Mbo;
import psdi.mbo.MboRemote;
import psdi.mbo.MboSetRemote;
import psdi.server.MXServer;
import psdi.util.MXException;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.nio.charset.StandardCharsets;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 数据方向 SPMS-->EAM
 *
 * @author liuxingqiang
 */
@Path("/inventory")
public class Eam2SpmsService {

    public Eam2SpmsService() throws RemoteException, MXException {
    }

    //库存传输接口,EAM接收SPMS端发出的库存变更数据，然后进行处理---中间表插入----提交
    @POST
    @Path("/metailInfo")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public JSONObject Z_SPMS_STORAGE_INVENTORY_TO_EAM(String received){
        JSONObject returnDate = new JSONObject();
        JSONObject jsonObject = JSONObject.parseObject(received);
//        MboRemote udkclogsMbo=null;
        //JSONObject dataObj = jsonObject.getJSONObject("REQUEST").getJSONObject("REQUEST_DATA").getJSONObject("Head");
        //JSONArray dataArray = (JSONArray) jsonObject.get("IT_REQUEST");
        JSONArray dataArray = JSONArray.parseArray(jsonObject.getString("IT_REQUEST"));
        try {
//            MboSetRemote UDKCLOGS = MXServer.getMXServer().getMboSet("UDKCLOGS",MXServer.getMXServer().getSystemUserInfo());
//            udkclogsMbo=UDKCLOGS.add(2L);
//            udkclogsMbo.setValue("LOGDATE", new Date(), 2L);
//            udkclogsMbo.setValue("LOGTYPE", "metailInfo", 2L);
//            udkclogsMbo.setValue("RECEIVED", received, 2L);

            //库存表
            MboSetRemote mobSet = MXServer.getMXServer().getMboSet("UDKC",MXServer.getMXServer().getSystemUserInfo());
            for (int i = 0; i < dataArray.size(); i++) {
                Map<String, Object> map = new HashMap<String, Object>();
                JSONObject jobj = (JSONObject) dataArray.get(i);//获取每个json对象
                String MATNR = (String) jobj.get("materialNo"); //物料号
                String ISSUEUNIT = (String) jobj.get("unit"); //单位
                String SITEID = (String) jobj.get("werks"); //工厂地点码
                String ORGID = "";
                MboSetRemote siteSet = MXServer.getMXServer().getMboSet("SITE",MXServer.getMXServer().getSystemUserInfo());
                siteSet.setWhere(" siteid='"+SITEID+"' and ACTIVE=1");
                siteSet.reset();
                if(siteSet!=null && !siteSet.isEmpty()){
                    MboRemote siteMbo = siteSet.getMbo(0);
                    if(siteMbo!=null){
                        ORGID = siteMbo.getString("ORGID");
                    }
                }else{
                    continue;
                }
                String STORELOC = (String) jobj.get("whsLocationCode"); //库房
                Double PHYSCNTTOTAL = jobj.getDouble("availableQty") ; //数量
                if(PHYSCNTTOTAL==null){
                    PHYSCNTTOTAL = (double) 0;
                }
                String BINNUM = (String) jobj.get("storageNo"); //储位编号
                String BINNUMFLAG = (String) jobj.get("storageType"); //储位标记
                String unitcostStr = (jobj.get("unitCost")==null || "".equals(jobj.get("unitCost"))) ? "0" : (String) jobj.get("unitCost");
                Double UNITCOST = Double.parseDouble(unitcostStr); //单价
                String CURRENCY = (String) jobj.get("currency"); //币种
                mobSet.setWhere(" ITEMNUM='"+MATNR+"' and BINNUM='"+BINNUM+"' and LOCATION='"+STORELOC+"' and siteid='"+SITEID+"'");//一个物料对应多个库位
                mobSet.reset();
                if(mobSet!=null && !mobSet.isEmpty()){
                    MboRemote mbo  = mobSet.getMbo(0);
                    mbo.setValue("ISSUEUNIT",ISSUEUNIT,2L);
                    mbo.setValue("MODIFTIME",new Date(),2L);
/*                    if(received.toString().getBytes(StandardCharsets.UTF_8).length<=4000){
                        mbo.setValue("RECEIVED", UrlConstants.restEsbUrl+received.toString(), 2L);
                    }else{
                        mbo.setValue("RECEIVED", (UrlConstants.restEsbUrl+received.toString()).substring(0,1333), 2L);
                    }*/
                    mbo.setValue("LOCATION",STORELOC,2L);
                    mbo.setValue("CURBALTOTAL",PHYSCNTTOTAL,2L);
                    mbo.setValue("BINNUM",BINNUM,2L);
                    mbo.setValue("UNITCOST",UNITCOST,2L);
                    mbo.setValue("CURRENCY",CURRENCY,2L);
                    mbo.setValue("BINNUMFLAG",BINNUMFLAG,2L);
                  /*  MboSetRemote udgnSet=mbo.getMboSet("$UDGNCJG", "UDGNCJG", "MATNR='"+MATNR+"' and BWKEY='"+SITEID+"'");
                    if(null!=udgnSet && !udgnSet.isEmpty() && udgnSet.count()>0){
                        MboRemote udgnMbo=udgnSet.getMbo(0);
                        mbo.setValue("CURRENCY",udgnMbo.getString("WAERS"),2L);//币种
                        mbo.setValue("PRICE",udgnMbo.getDouble("VERPR"),2L);//单价
                        mbo.setValue("UNITCOST",(PHYSCNTTOTAL*udgnMbo.getDouble("VERPR")),2L);//标识当前项目的单位成本。
                    }*/
                    mbo.getThisMboSet().save();

                }else{
                    MboRemote mbo = mobSet.add();//创建对象
                    mbo.setValue("MODIFTIME",new Date(),2L);
 /*                   if(received.toString().getBytes(StandardCharsets.UTF_8).length<=4000){
                        mbo.setValue("RECEIVED", UrlConstants.restEsbUrl+received.toString(), 2L);
                    }else{
                        mbo.setValue("RECEIVED", (UrlConstants.restEsbUrl+received.toString()).substring(0,1333), 2L);
                    }*/
                    mbo.setValue("ITEMNUM",MATNR,2L);//给对象赋值
                    mbo.setValue("ISSUEUNIT",ISSUEUNIT,2L);
                    mbo.setValue("SITEID",SITEID,2L);
                    mbo.setValue("ORGID",ORGID,2L);
                    mbo.setValue("LOCATION",STORELOC,2L);
                    mbo.setValue("CURBALTOTAL",PHYSCNTTOTAL,2L);
                    mbo.setValue("BINNUM",BINNUM,2L);
                    mbo.setValue("UNITCOST",UNITCOST,2L);
                    mbo.setValue("CURRENCY",CURRENCY,2L);
                    mbo.setValue("BINNUMFLAG",BINNUMFLAG,2L);
                  /*  MboSetRemote udgnSet=mbo.getMboSet("$UDGNCJG", "UDGNCJG", "MATNR='"+MATNR+"' and BWKEY='"+SITEID+"'");
                    if(null!=udgnSet && !udgnSet.isEmpty() && udgnSet.count()>0){
                        MboRemote udgnMbo=udgnSet.getMbo(0);
                        mbo.setValue("CURRENCY",udgnMbo.getString("WAERS"),2L);//币种
                        mbo.setValue("PRICE",udgnMbo.getDouble("VERPR"),2L);//单价
                        mbo.setValue("UNITCOST",(PHYSCNTTOTAL*udgnMbo.getDouble("VERPR")),2L);//标识当前项目的单位成本。
                    }*/
                    mbo.getThisMboSet().save();
                }
            }
            returnDate.put("code", "success");
            returnDate.put("msg", "成功");
        }catch (Exception e){
            e.getMessage();
            e.getCause();
            returnDate.put("code", "failure");
            returnDate.put("msg", "失败="+e.getMessage());
        }finally {
            return returnDate;
        }
    }

    //出入库信息传输接口，SPMS->ESB->EAM,EAM接收SPMS接口传输的出入库数据，进行处理。
    @POST
    @Path("/inoutMetail")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public JSONObject Z_SPMS_STOCK_LIST_TO_EAM(String received) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
//        MboRemote udkclogsMbo=null;
        JSONObject returnDate = new JSONObject();
        JSONObject jsonObject = JSONObject.parseObject(received);
        JSONArray dataArray = JSONArray.parseArray(jsonObject.getString("IT_REQUEST"));
        try{
//            MboSetRemote UDKCLOGS = MXServer.getMXServer().getMboSet("UDKCLOGS",MXServer.getMXServer().getSystemUserInfo());
//            udkclogsMbo=UDKCLOGS.add(2L);
//            udkclogsMbo.setValue("LOGDATE", new Date(), 2L);
//            udkclogsMbo.setValue("LOGTYPE", "inoutMetail", 2L);
//            udkclogsMbo.setValue("RECEIVED", received, 2L);

            MboSetRemote mobSet = MXServer.getMXServer().getMboSet("UDWLCRK",MXServer.getMXServer().getSystemUserInfo());
            for (int i = 0; i < dataArray.size(); i++) {
                //获取表的对象
                MboSetRemote siteSet = MXServer.getMXServer().getMboSet("SITE",MXServer.getMXServer().getSystemUserInfo());
                Map<String, Object> map = new HashMap<String, Object>();
                JSONObject jobj = (JSONObject) dataArray.get(i);//获取每个json对象
                String userName = (String) jobj.get("userName"); //创建人
                String createTime = (String) jobj.get("createTime"); //创建日期
                String relateDocumentNumber = (String) jobj.get("relateDocumentNumber"); //单据号
                String documentType = (String) jobj.get("documentType"); //日志类型
                String remarks = (String) jobj.get("remarks"); //备注
                String overseaWhsInNo = (String) jobj.get("overseaWhsInNo"); //入库单号 未找到
                String whsOutNo = (String) jobj.get("whsOutNo"); //出库单号
                String overseaOtherTaskNo = (String) jobj.get("overseaOtherTaskNo"); //其他出入库单号 未找到
                String deliveryNoteSap = (String) jobj.get("deliveryNoteSap"); //SAP交货单 未找到
                String overseaWhsMoveNo = (String) jobj.get("overseaWhsMoveNo"); //调拨单号 未找到
                String boxNote = (String) jobj.get("boxNote"); //箱码
                String cabinetNumber = (String) jobj.get("cabinetNumber"); //柜号
                String packageList = (String) jobj.get("packageList"); //装箱单号
                String requisitionNo = (String) jobj.get("requisitionNo"); //领用单号
                String lastName = (String) jobj.get("lastName"); //领用人
                String costCenter = (String) jobj.get("costCenter"); //成本中心
                String operationType = (String) jobj.get("operationType"); //操作类型
                String comments = (String) jobj.get("comments"); //操作内容
                String materialNo = (String) jobj.get("materialNo"); //物料号
                String unitSales = (String) jobj.get("unitSales"); //单位
                Integer quantity = jobj.getInteger("quantity"); //数量
                String werks = (String) jobj.get("werks"); //工厂
                siteSet.setWhere("siteid='"+werks+"'");
                siteSet.reset();
                String orgid = "";
                if(siteSet!=null && !siteSet.isEmpty()){
                    MboRemote siteMbo = siteSet.getMbo(0);
                    if(siteMbo!=null){
                        orgid = siteMbo.getString("ORGID");
                    }
                }else{
                    continue;
                }
                String whsLocationCode = (String) jobj.get("whsLocationCode"); //库存地点
                String storageNo = (String) jobj.get("storageNo"); //储位编号
                String movementType = (String) jobj.get("movementType"); //移动类型
                String waers = (String) jobj.get("waers"); //本币
                String dmbtr = (String) jobj.get("dmbtr"); //行成本
                MboRemote UDWLCRKOBJ = mobSet.add();//当前对象
                UDWLCRKOBJ.setValue("userName".toUpperCase(), userName,2L);
                UDWLCRKOBJ.setValue("createTime".toUpperCase(), sdf.parse(createTime),2L);
                UDWLCRKOBJ.setValue("relateDocumentNumber".toUpperCase(), relateDocumentNumber,2L);
                UDWLCRKOBJ.setValue("documentType".toUpperCase(), documentType,2L);
                UDWLCRKOBJ.setValue("remarks".toUpperCase(), remarks,2L);
                UDWLCRKOBJ.setValue("overseaWhsInNo".toUpperCase(), overseaWhsInNo,2L);
                UDWLCRKOBJ.setValue("whsOutNo".toUpperCase(), whsOutNo,2L);
                UDWLCRKOBJ.setValue("overseaOtherTaskNo".toUpperCase(), overseaOtherTaskNo,2L);
                UDWLCRKOBJ.setValue("deliveryNoteSap".toUpperCase(), deliveryNoteSap,2L);
                UDWLCRKOBJ.setValue("overseaWhsMoveNo".toUpperCase(), overseaWhsMoveNo,2L);
                UDWLCRKOBJ.setValue("boxNote".toUpperCase(), boxNote,2L);
                UDWLCRKOBJ.setValue("cabinetNumber".toUpperCase(), cabinetNumber,2L);
                UDWLCRKOBJ.setValue("packageList".toUpperCase(), packageList,2L);
                UDWLCRKOBJ.setValue("requisitionNo".toUpperCase(), requisitionNo,2L);
                UDWLCRKOBJ.setValue("lastName".toUpperCase(), lastName,2L);
                UDWLCRKOBJ.setValue("costCenter".toUpperCase(), costCenter,2L);
                UDWLCRKOBJ.setValue("operationType".toUpperCase(), operationType,2L);
                UDWLCRKOBJ.setValue("comments".toUpperCase(), comments,2L);
                UDWLCRKOBJ.setValue("materialNo".toUpperCase(), materialNo,2L);
                UDWLCRKOBJ.setValue("unitSales".toUpperCase(), unitSales,2L);
                UDWLCRKOBJ.setValue("quantity".toUpperCase(), String.valueOf(quantity),2L);
                UDWLCRKOBJ.setValue("werks".toUpperCase(), werks,2L);
                UDWLCRKOBJ.setValue("whsLocationCode".toUpperCase(), whsLocationCode,2L);
                UDWLCRKOBJ.setValue("storageNo".toUpperCase(), storageNo,2L);
                UDWLCRKOBJ.setValue("dmbtr".toUpperCase(), dmbtr,2L);
                UDWLCRKOBJ.setValue("waers".toUpperCase(), waers,2L);
                UDWLCRKOBJ.setValue("movementType".toUpperCase(), movementType,2L);
                UDWLCRKOBJ.setValue("SITEID".toUpperCase(), werks,2L);
                UDWLCRKOBJ.setValue("ORGID".toUpperCase(), orgid,2L);
                UDWLCRKOBJ.getThisMboSet().save();
//                }
            }
            returnDate.put("code", "success");
            returnDate.put("msg", "成功");
//            udkclogsMbo.setValue("RESULTS", "success", 2L);
//            udkclogsMbo.getThisMboSet().save();
        }catch (Exception e){
            e.getMessage();
            e.getCause();
            returnDate.put("code", "failure");
            returnDate.put("msg", "失败"+e.getMessage());
//            udkclogsMbo.setValue("RESULTS", "失败"+e.getMessage(), 2L);
//            udkclogsMbo.getThisMboSet().save();
        }finally {
            return returnDate;
        }
    }

    /**
     * 领料申请单 状态更新
     * @param received
     * @return
     */
    @POST
    @Path("/udlldSetStatusValue")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String setStatusValue(String received)  {
        JSONObject msgJSONObject = new JSONObject();
        if("".equalsIgnoreCase(received) || null==received){
            msgJSONObject.put("code", "20001");
            msgJSONObject.put("errmsg", "参数不能为空");
            return msgJSONObject.toString();
        }
        JSONObject jsonObject = JSONObject.parseObject(received);
        JSONObject jsonObject2 = JSONObject.parseObject(jsonObject.getString("OVDATA"));
        String wonum = jsonObject2.getString("WONUM");

        if("".equalsIgnoreCase(wonum) || null==wonum){
            msgJSONObject.put("code", "20001");
            msgJSONObject.put("errmsg", "WONUM参数不能为空");
            return msgJSONObject.toString();
        }
        String status = jsonObject2.getString("STATE");
        if("".equalsIgnoreCase(status) || null==status){
            msgJSONObject.put("code", "20001");
            msgJSONObject.put("errmsg", "STATE参数不能为空");
            return msgJSONObject.toString();
        }
        try{
                MboSetRemote woSet = MXServer.getMXServer().getMboSet("UDLLD",MXServer.getMXServer().getSystemUserInfo());
                woSet.setWhere("WONUM='"+wonum+"' ");
                woSet.reset();
                if(null!=woSet && !woSet.isEmpty()){
                    //更新子表 行成本
                    JSONArray dataArray = JSONArray.parseArray(jsonObject.getString("ITEMDATA"));
                    if(null!=dataArray){
                        MboSetRemote lldlineSet = MXServer.getMXServer().getMboSet("UDLLDLINE",MXServer.getMXServer().getSystemUserInfo());
                        for (int i = 0; i < dataArray.size(); i++) {
                            JSONObject jobj = (JSONObject) dataArray.get(i);//获取每个json对象
                            String linenum = (String) jobj.get("LINENUM"); //行号
                            String materialno = (String) jobj.get("MATERIALNO"); //物料号
                            String waers = (String) jobj.get("WAERS"); //行项目币种
                            String dmbtr = (String) jobj.get("DMBTR"); //SPMS出库单行成本
                            String spmsoutid = (String) jobj.get("SPMSOUTID"); //SPMS出库单
                            String sapvouchernumber = (String) jobj.get("SAPVOUCHERNUMBER"); //SAP凭证
                            double ACTUALQTYBASICUNIT = jobj.getDouble("ACTUALQTYBASICUNIT"); //实际出库数量
                            String BASIC_UNIT = (String) jobj.get("BASIC_UNIT"); //基本单位
                            lldlineSet.setWhere(" PARENTID=(SELECT UDLLDID FROM UDLLD WHERE WONUM='"+wonum+"') AND LINENUM='"+linenum+"' AND ITEMNUM='"+materialno+"'");
                            lldlineSet.reset();
                            if(null!=lldlineSet && !lldlineSet.isEmpty() && lldlineSet.count()>0){
                                MboRemote lineMbo=lldlineSet.getMbo(0);
                                lineMbo.setValue("WAERS", waers, 2L);//行项目币种
                                lineMbo.setValue("DMBTR", dmbtr, 2L);//SPMS出库单行成本
                                lineMbo.setValue("SPMSOUTID", spmsoutid, 2L);//SPMS出库单
                                lineMbo.setValue("SAPVOUCHERNUMBER", sapvouchernumber, 2L);//SAP凭证
                                lineMbo.setValue("ACTUALQTYBASICUNIT", ACTUALQTYBASICUNIT, 2L);
                                lineMbo.setValue("BASIC_UNIT", BASIC_UNIT, 2L);
                                lineMbo.getThisMboSet().save();
                            }
                        }
                        MboRemote woMbo=woSet.getMbo(0);
                        woMbo.setFieldFlag("STATUS", 7L, false);
                        woMbo.setFieldFlag("STATUSDATE", 7L, false);
                        if("0".equalsIgnoreCase(status)){//已完成
                            woMbo.setValue("STATUS", "COMP",2L);
                        }else if("1".equalsIgnoreCase(status)){//已撤回
                            woMbo.setValue("STATUS", "CAN",2L);
                            woMbo.setValue("SPMSSTAUTS", "CAN",2L);
                        }
                        woMbo.setValue("STATUSDATE", new Date(),2L);
                        woMbo.setValue("REASON",jsonObject2.getString("REASON"));//撤回原因
                        woMbo.setValue("OUTBOUND",jsonObject2.getString("OUTBOUND"));//出库单号（领用单转出库单才有）
                        woMbo.setValue("SPMSID",jsonObject2.getString("SPMSID"));//SPMS领用单号
                        woMbo.setValue("COMMENTS",jsonObject2.getString("COMMENTS"));//SPMS领用单标题
                        woMbo.getThisMboSet().save();

                    }

                    msgJSONObject.put("code", "10000");
                    msgJSONObject.put("msg", "success");
                }else{
                    msgJSONObject.put("code", "20001");
                    msgJSONObject.put("errmsg", "当前参数在EAM领料申请单应用中不存在");
                }
        }catch (Exception e){
            e.getMessage();
            e.getCause();
            msgJSONObject.put("code", "20001");
            msgJSONObject.put("sysErrMsg", e.getMessage());
        }
        return msgJSONObject.toString();
    }

    /**
     * 退库申请单 状态更新
     * @param received
     * @return
     */
    @POST
    @Path("/udReturnSetStatusValue")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String setReturnStatusValue(String received)  {
        JSONObject msgJSONObject = new JSONObject();
        if("".equalsIgnoreCase(received) || null==received){
            msgJSONObject.put("code", "20001");
            msgJSONObject.put("errmsg", "参数不能为空");
            return msgJSONObject.toString();
        }
        JSONObject jsonObject = JSONObject.parseObject(received);
        JSONObject jsonObject2 = JSONObject.parseObject(jsonObject.getString("OVDATA"));
        String wonum = jsonObject2.getString("WONUM");
        if("".equalsIgnoreCase(wonum) || null==wonum){
            msgJSONObject.put("code", "20001");
            msgJSONObject.put("errmsg", "WONUM参数不能为空");
            return msgJSONObject.toString();
        }
        String OUTBOUND = jsonObject2.getString("OUTBOUND");//退库单
        String REASON = jsonObject2.getString("REASON");//退库原因
        String STATUS = jsonObject2.getString("STATE");//退库状态

        try{
            MboSetRemote woSet = MXServer.getMXServer().getMboSet("UDLLD",MXServer.getMXServer().getSystemUserInfo());
            woSet.setWhere("WONUM='"+wonum+"' ");
            woSet.reset();
            if(null!=woSet && !woSet.isEmpty()){
                MboRemote woMbo=woSet.getMbo(0);
                woMbo.setFieldFlag("STATUS", 7L, false);
                woMbo.setFieldFlag("STATUSDATE", 7L, false);
                if("0".equalsIgnoreCase(STATUS)){//已完成
                    woMbo.setValue("STATUS", "COMP",2L);
                }else if("1".equalsIgnoreCase(STATUS)){//已撤回
                    woMbo.setValue("STATUS", "CAN",2L);
                    woMbo.setValue("SPMSSTAUTS", "CAN",2L);
                }
                woMbo.setValue("OUTBOUND",OUTBOUND,2L);
                woMbo.setValue("REASON",REASON,2L);
                woMbo.setValue("STATUSDATE", new Date(),2L);
                woMbo.getThisMboSet().save();
                msgJSONObject.put("code", "10000");
                msgJSONObject.put("msg", "success");
            }else{
                msgJSONObject.put("code", "20001");
                msgJSONObject.put("errmsg", "当前参数在EAM中不存在");
            }
        }catch (Exception e){
            e.getMessage();
            e.getCause();
            msgJSONObject.put("code", "20001");
            msgJSONObject.put("sysErrMsg", e.getMessage());
        }
        return msgJSONObject.toString();
    }

    /**
     * 旧件回收申请单
     * spms调用eam，有两种情况：
     * 1、spms入库成功，传state=0，eam变更状态同时进行库存的变化
     * 2、spms直接驳回/撤销，传state=1，eam变更状态
     * @param received
     * @return
     */
    @POST
    @Path("/udRecSetStatus")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String udRecSetStatus(String received)  {
        JSONObject msgJSONObject = new JSONObject();
        if("".equalsIgnoreCase(received) || null==received){
            msgJSONObject.put("code", "20001");
            msgJSONObject.put("errmsg", "参数不能为空");
            return msgJSONObject.toString();
        }
        JSONObject jsonObject = JSONObject.parseObject(received);
        JSONObject jsonObject2 = JSONObject.parseObject(jsonObject.getString("OVDATA"));
        String RCNUM = jsonObject2.getString("WONUM");//EAM申请单号
        String SPMSRKNUM = jsonObject2.getString("OUTBOUND");//SPMS入库单号 --新增字段
        String REASON = jsonObject2.getString("REASON");//SPMS驳回后，需要说明原因--新增字段
        String STATE = jsonObject2.getString("STATE");//spms入库状态--新增字段，新增接收和发送的字段
        if("".equalsIgnoreCase(RCNUM) || null==RCNUM){
            msgJSONObject.put("code", "20001");
            msgJSONObject.put("errmsg", "RCNUM参数不能为空");
            return msgJSONObject.toString();
        }
        if("".equalsIgnoreCase(STATE) || null==STATE){
            msgJSONObject.put("code", "20001");
            msgJSONObject.put("errmsg", "STATE参数不能为空");
            return msgJSONObject.toString();
        }
        try{
            //留用数量需要 退 到 EAM线边仓,对线边仓而言是 入库
            //报废数量不管，入库spms数量EAM不管
            MboSetRemote personSet = MXServer.getMXServer().getMboSet("PERSON",MXServer.getMXServer().getSystemUserInfo());
            MboSetRemote udinvSet = MXServer.getMXServer().getMboSet("UDINVENTORY",MXServer.getMXServer().getSystemUserInfo());//EAM物资清单表 UDINVENTORY
            MboSetRemote udmatuSet = MXServer.getMXServer().getMboSet("UDMATUSETRANS",MXServer.getMXServer().getSystemUserInfo());//库存交易记录表
            MboSetRemote UDRECOVERYSet = MXServer.getMXServer().getMboSet("UDRECOVERY",MXServer.getMXServer().getSystemUserInfo());//旧件回收主表
            MboSetRemote UDRECOVERYLINESet = MXServer.getMXServer().getMboSet("UDRECOVERYLINE",MXServer.getMXServer().getSystemUserInfo());//旧件回收子表
            UDRECOVERYSet.setWhere("RCNUM='"+RCNUM+"'");
            UDRECOVERYSet.reset();
            if(UDRECOVERYSet!=null && !UDRECOVERYSet.isEmpty()){
                MboRemote recMbo = UDRECOVERYSet.getMbo(0);
                int UDRECOVERYID = recMbo.getInt("UDRECOVERYID");//旧件回收主表ID
                recMbo.setValue("SPMSRKNUM",SPMSRKNUM,11L);
                recMbo.setValue("REASON",REASON,11L);
                recMbo.setValue("STATE",STATE,11L);
                recMbo.setValue("STATUS","CLOSE",11L);
                //保存接收到的参数信息------------------------
                if(jsonObject.toString().getBytes(StandardCharsets.UTF_8).length<=4000){
                    recMbo.setValue("ACCEPTJS", UrlConstants.restEsbUrl+jsonObject.toString(), 2L);
                }else{
                    recMbo.setValue("ACCEPTJS", (UrlConstants.restEsbUrl+jsonObject.toString()).substring(0,1333), 2L);
                }
                //保存接收到的参数信息------------------------
                //state=1 表示 spms直接驳回
                if("1".equalsIgnoreCase(STATE)){
                    recMbo.setValue("STATUS","CANCEL",11L);
                    recMbo.getThisMboSet().save();
                    msgJSONObject.put("code", "10000");
                    msgJSONObject.put("errmsg", "success");
                    return msgJSONObject.toString();
                }
                recMbo.getThisMboSet().save();
            /*    String CREATEBY = recMbo.getString("CREATEBY");//创建人
                String ORGID = recMbo.getString("ORGID");//组织
                String SITEID = recMbo.getString("SITEID");//地点
                String app = "UDRECOVERY";//应用名称
                String DEPTNUM = "";//创建人所在部门
                personSet.setWhere("personid='"+CREATEBY+"'");
                personSet.reset();
                if(personSet!=null && !personSet.isEmpty()){
                    MboRemote mboDesc = personSet.getMbo(0);
                    DEPTNUM = mboDesc.getString("DEPARTMENT");
                }
                UDRECOVERYLINESet.setWhere("UDRECOVERYID="+UDRECOVERYID+"");
                UDRECOVERYLINESet.reset();
                if(UDRECOVERYLINESet!=null && !UDRECOVERYLINESet.isEmpty()){
                    for(int i=0;i<UDRECOVERYLINESet.count();i++){
                        MboRemote reclineMbo = UDRECOVERYLINESet.getMbo(i);
                        Integer UDRECOVERYLINEID = reclineMbo.getInt("UDRECOVERYLINEID");
                        String ITEMNUM = reclineMbo.getString("ITEMNUM");//物料编号
                        Double LYNUM = reclineMbo.getDouble("LYNUM");//留用数量
                        udinvSet.setWhere("ITEMNUM='"+ITEMNUM+"' AND DEPTNUM='"+DEPTNUM+"'");
                        udinvSet.reset();
                        if(null!=udinvSet && !udinvSet.isEmpty()){
                            //插入交易记录表
                            setudmatuSetValue(udmatuSet,ITEMNUM,DEPTNUM,LYNUM,CREATEBY,RCNUM,ORGID,SITEID,app,"Storage");
                        }else{
                            MboRemote udinvMbo=udinvSet.add();
                            udinvMbo.setValue("ITEMNUM", ITEMNUM);
                            udinvMbo.setValue("DEPTNUM",DEPTNUM);
                            udinvMbo.setValue("ORGID",ORGID);
                            udinvMbo.setValue("SITEID",SITEID);
                            udinvMbo.getThisMboSet().save();
                            //插入交易记录表
                            setudmatuSetValue(udmatuSet,ITEMNUM,DEPTNUM,LYNUM,CREATEBY,RCNUM,ORGID,SITEID,app,"Storage");
                        }
                    }
                }*/
            }
            msgJSONObject.put("code", "10000");
            msgJSONObject.put("msg", "success");
        }catch (Exception e){
            e.getMessage();
            e.getCause();
            msgJSONObject.put("code", "20001");
            msgJSONObject.put("sysErrMsg", e.getMessage());
        }
        return msgJSONObject.toString();
    }

    //插入库存交易记录表
    public void setudmatuSetValue(MboSetRemote udmatuSet,String itemnum,String workshop,double quantity,String createby,String wonum,String ORGID,String Siteid,String appname,String issuetype) throws RemoteException, MXException {
        MboRemote udmatuMbo=udmatuSet.add();
        //ITEMNUM=:ITEMNUM and DEPTNUM=:DEPTNUM
        udmatuMbo.setValue("ITEMNUM", itemnum);
        udmatuMbo.setValue("DEPTNUM", workshop);
        udmatuMbo.setValue("QUANTITY", quantity);
        udmatuMbo.setValue("ISSUETYPE", issuetype);
        udmatuMbo.setValue("TRANSDATE", new Date());
        udmatuMbo.setValue("ENTERBY", createby);
        udmatuMbo.setValue("WONUM",wonum);
        udmatuMbo.setValue("ORGID", ORGID);
        udmatuMbo.setValue("SITEID", Siteid);
        udmatuMbo.setValue("APPNAME", appname);
        udmatuMbo.getThisMboSet().save();
    }


    /**
     * 新增SPMS更新EAM物料价格（脱敏后）接口
     * @param received
     * @return
     */
    @POST
    @Path("/spmsSetVirtualpriceToEam")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String Z_SPMS_VIRTUALPRICE_TOEAM(String received)  {
        JSONObject msgJSONObject = new JSONObject();
        if("".equalsIgnoreCase(received) || null==received){
            msgJSONObject.put("code", "20001");
            msgJSONObject.put("errmsg", "参数不能为空");
            return msgJSONObject.toString();
        }
        JSONObject jsonObject = JSONObject.parseObject(received);
        JSONArray dataArray = JSONArray.parseArray(jsonObject.getString("IT_REQUEST"));
        if(null!=dataArray) {
            try {
                MboSetRemote woSet = MXServer.getMXServer().getMboSet("UDVIRTUALPRICE", MXServer.getMXServer().getSystemUserInfo());

                for (int i = 0; i < dataArray.size(); i++) {
                    JSONObject jobj = (JSONObject) dataArray.get(i);//获取每个json对象
                    String factory = (String) jobj.get("factory");//工厂
                    String endDate = (String) jobj.get("endDate");//价格有效终止日期
                    String materialNo = (String) jobj.get("materialNo");//物料编码
                    String virtualPrice = (String) jobj.get("virtualPrice");//单价
                    String currency = (String) jobj.get("currency");//货币单位
                    String startDate = (String) jobj.get("startDate");//价格有效起始日期

                    woSet.setWhere(" factory='"+factory+"' AND materialNo='"+materialNo+"' ");
                    woSet.reset();
                    MboRemote lineMbo=null;
                    if(woSet!=null && !woSet.isEmpty()){
                        lineMbo=woSet.getMbo(0);
                        lineMbo.setValue("endDate", endDate, 11L);
                        lineMbo.setValue("virtualPrice", virtualPrice, 11L);
                        lineMbo.setValue("currency", currency, 11L);
                        lineMbo.setValue("startDate", startDate, 11L);
                        lineMbo.getThisMboSet().save();
                        lineMbo.getThisMboSet().close();
                    }else{
                        lineMbo=woSet.add();
                        lineMbo.setValue("factory", factory, 11L);
                        lineMbo.setValue("endDate", endDate, 11L);
                        lineMbo.setValue("materialNo", materialNo, 11L);
                        lineMbo.setValue("virtualPrice", virtualPrice, 11L);
                        lineMbo.setValue("currency", currency, 11L);
                        lineMbo.setValue("startDate", startDate, 11L);
                        lineMbo.getThisMboSet().save();
                        lineMbo.getThisMboSet().close();
                    }


                }
                msgJSONObject.put("code", "10000");
                msgJSONObject.put("msg", "success");
            } catch (Exception e) {
                e.getMessage();
                e.getCause();
                msgJSONObject.put("code", "20001");
                msgJSONObject.put("sysErrMsg", e.getMessage());
            }
        }

            return msgJSONObject.toString();

        }


}