package com.cim.idm.service.Impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cim.idm.dao.FgStockInDao;
import com.cim.idm.dao.MesToWmsDao;
import com.cim.idm.data.ErpMessageLog;
import com.cim.idm.exception.GlobalException;
import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.framework.data.EventInfo;
import com.cim.idm.framework.orm.SqlTemplate;
import com.cim.idm.framework.util.sys.SystemPropHelper;
import com.cim.idm.framework.util.time.TimeStampUtil;
import com.cim.idm.model.MaterialPackingSubDto;
import com.cim.idm.mwmsextend.materialpacking.service.MaterialPackingServiceImpl;
import com.cim.idm.service.MESToWMSService;
import com.cim.idm.service.QMSService;
import com.cim.idm.service.impl.ToSAPServiceImpl;
import com.cim.idm.util.MessageLogUtil;
import com.cim.idm.utils.AjaxResult;
import com.cim.idm.utils.CommonUtils;
import com.cim.idm.utils.EventInfoUtil;
import com.cim.idm.wmspackage.materialpacking.MaterialPackingServiceProxy;
import com.cim.idm.wmspackage.materialpacking.management.data.MaterialPackingKey;
import com.cim.idm.wmspackage.materialpacking.management.info.RemoveInfo;
import com.cim.idm.wmspackage.materialpacking.management.info.SetEventInfo;
import com.cim.idm.wmspackage.name.NameServiceProxy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.*;

@Service("MESToWMS")
@Slf4j
public class MESToWMSServiceImpl implements MESToWMSService {


    @Autowired
    private ToSAPServiceImpl toSAPService;

    @Autowired
    private SqlTemplate sqlTemplate;

    @Autowired
    private ProductIntoServiceImpl productIntoServiceImpl;
    @Autowired
    private ReturnStockIntoServiceImpl returnStockIntoServiceImpl;
    @Autowired
    private QMSService qmsService;

    @Autowired
    private MesToWmsDao mesToWmsDao;

    @Override
    @Transactional
    public AjaxResult materialConsume_Request(JSONArray in) throws Exception {
        AjaxResult result = new AjaxResult();
        ErpMessageLog loginfo = new ErpMessageLog();
        loginfo.setServerName("MESToWms");
        loginfo.setMessageId("");
        loginfo.setEventUser("MES");
        loginfo.setId(TimeStampUtil.getCurrentEventTimeKey());
        loginfo.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
        loginfo.setSendMsg(in.toJSONString());
        loginfo.setEventName("materialConsume_Request");
        String siteName = System.getProperty("company", "SDK");


        List<String> boxIdList = new ArrayList<>();
        List<String> qtyList = new ArrayList<>();
        List<MaterialPackingKey> mpList = new ArrayList<>();
        int success = 0;
        String errorCode = "";
        //根据wo，qty，materialSpecName生成物料消耗
        /**
         * 1. 从MATERIALPACKINGMDC该要求先进先出取出满足消耗的charge
         * 2. 写入接口临时表
         * 3. 过账
         * 4. 更新MATERIALPACKINGMDC表库存
         */

        for (int i = 0; i < in.size(); i++) {
            JSONObject jb = in.getJSONObject(i);
            String materialSpecName = jb.get("materialSpecName").toString();
            String qty = jb.get("qty").toString(); // 消耗数量
            String  wo = jb.get("requestName") == null ? "" : jb.get("requestName").toString(); // 工单
            String flag = jb.get("flag") == null ? "" : jb.get("flag").toString();
            //判空
            if (StringUtils.isBlank(materialSpecName) || StringUtils.isBlank(qty)) {
                result = AjaxResult.me().setSuccess(false).setErrorCode(500).setMessage("料号或数量不能为空");
                loginfo.setResultCode("1");
                loginfo.setReturnMsg(JSONObject.toJSONString(result));
                // 消息保存日志，erp推送wms的数据写入表BS_ERPMESSAGELOG中
                MessageLogUtil.writeMessageLog(loginfo);
                return result;
            }
            if (StringUtils.isBlank(wo)) {
                result = AjaxResult.me().setSuccess(false).setErrorCode(500).setMessage("工单不能为空");
                loginfo.setResultCode("1");
                loginfo.setReturnMsg(JSONObject.toJSONString(result));
                // 消息保存日志，erp推送wms的数据写入表BS_ERPMESSAGELOG中
                MessageLogUtil.writeMessageLog(loginfo);
                return result;
            }
            //调用存储MES_CONSUME
            String procedureName = "MES_CONSUME";
            // 调用存储过程返回参数
//            IDMFrameServiceProxy.getSqlTemplate().getJdbcTemplate().execute(procedureName);
            Map<String, Object> bindMap = new HashMap<String, Object>() {
                {
                    put("V_WO", wo);
                    put("V_MATERIALSPECNAME", materialSpecName);
                    put("V_QTY", qty);
                        put("V_FLAG", flag);
                    put("V_RETURN_CODE", "");
                    put("V_RETURN_MESSAGE", "");
                }
            };
            Map<String, Object> stringObjectMap = IDMFrameServiceProxy.getSqlTemplate().executeProcedure(procedureName, bindMap);
            if (stringObjectMap != null) {
                if (stringObjectMap.get("V_RETURN_CODE") != null && !stringObjectMap.get("V_RETURN_CODE").toString().equals("0")) {
                    errorCode = stringObjectMap.get("V_RETURN_CODE").toString();
                    String vReturnMessage = stringObjectMap.get("V_RETURN_MESSAGE").toString();
                    log.error("MES_CONSUME返回错误码：" + errorCode + "，错误信息：" + vReturnMessage);
                    result = AjaxResult.me().setSuccess(false).setErrorCode(Integer.parseInt(errorCode)).setMessage(vReturnMessage);
                    return result;
                }
            }


        }
        // 将工单的物料消耗数据传给SAP
        String undoId = toSAPService.mesMaterialConsume("MES");
        result = AjaxResult.me().setSuccess(true).setErrorCode(200).setMessage("执行成功");
        loginfo.setResultCode("0");
        loginfo.setReturnMsg(JSONObject.toJSONString(result));
        // 消息保存日志，erp推送wms的数据写入表BS_ERPMESSAGELOG中
        MessageLogUtil.writeMessageLog(loginfo);
        return result;
    }

    @Override
    @Transactional
    public AjaxResult materialOutByMES(JSONArray in) throws Exception {
        AjaxResult result = new AjaxResult();
        ErpMessageLog loginfo = new ErpMessageLog();
        loginfo.setServerName("MESToWms");
        loginfo.setMessageId("");
        loginfo.setEventUser("MES");
        loginfo.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
        loginfo.setSendMsg(in.toJSONString());
        loginfo.setEventName("MaterialOut_Request");

        List<String> boxIdList = new ArrayList<>();
        String shipRequestName = "";
        for (int i = 0; i < in.size(); i++) {
            JSONObject jb = in.getJSONObject(i);
            String charge = jb.get("charge").toString(); // 批号
            shipRequestName = jb.get("shipRequestName").toString(); // 领料单号
            boxIdList.add(charge);

        }

        String billCode = new ToSAPServiceImpl().ProductionStockOut_NEW(shipRequestName, "SDK", "MES", boxIdList);

        EventInfo makeEventInfo = new EventInfoUtil().makeEventInfo("CompleteShipRequest", "MES", "CompleteShipRequest:MES Receive");
        new CommonUtils().SaveUnDoInfo_ForSap(boxIdList, billCode, makeEventInfo);

        result = AjaxResult.me().setSuccess(true).setErrorCode(200).setMessage("执行成功");
        loginfo.setResultCode("S");
        loginfo.setReturnMsg(JSONObject.toJSONString(result));
        // 消息保存日志，erp推送wms的数据写入表BS_ERPMESSAGELOG中
        MessageLogUtil.writeMessageLog(loginfo);
        return result;
    }

    @Override
    @Transactional
    public AjaxResult cancelShipByMES(JSONArray in) {
        AjaxResult result = new AjaxResult();
        ErpMessageLog loginfo = new ErpMessageLog();
        loginfo.setServerName("MESToWms");
        loginfo.setMessageId("");
        loginfo.setEventUser("MES");
        loginfo.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
        loginfo.setSendMsg(in.toJSONString());
        loginfo.setEventName("CancelShip_Request");

        List<String> boxIdList = new ArrayList<>();
        for (int i = 0; i < in.size(); i++) {
            JSONObject jb = in.getJSONObject(i);
            String charge = jb.get("charge").toString(); // 批号
            boxIdList.add(charge);

        }

        String sqld = "DELETE FROM BS_MES_SHIPPED  b WHERE b.CHARGE in(:BOXIDLIST) AND NVL(b.receive_flag,'N')<>'Y' ";
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("BOXIDLIST", boxIdList);
        IDMFrameServiceProxy.getSqlTemplate().update(sqld, hashMap);

        result = AjaxResult.me().setSuccess(true).setErrorCode(200).setMessage("执行成功");
        loginfo.setResultCode("S");
        loginfo.setReturnMsg(JSONObject.toJSONString(result));
        // 消息保存日志，erp推送wms的数据写入表BS_ERPMESSAGELOG中
        MessageLogUtil.writeMessageLog(loginfo);
        return result;
    }

    /**
     * 成品入库SAP冲销
     * @param undoId
     * @param user
     */
    @Override
    @Transactional
    public AjaxResult sapcprkUndo(String undoId, String user) throws Exception {

        String billCode = toSAPService.cancelShipInter(undoId, user);
        if (billCode == null) {
            throw new GlobalException("报送ERP失败,请联系IT处理！");
        }


        AjaxResult result = new AjaxResult();

        EventInfo makeEventInfo = new EventInfoUtil ().makeEventInfo("MakeUndo", user, "MakeUndo");
        String  condition="SELECT MATERIALPACKINGNAME FROM MATERIALPACKING WHERE UNDOID = :UNDOID ";
//		String[] bindSet={undoId};
        Map<String, Object> hashMap = new HashMap<String, Object> ();
        hashMap.put("UNDOID", undoId);
        //根据物料凭证找到所有的待冲销数据，更新库存状态为创建
        List<Map<String, Object>> MPlIST = IDMFrameServiceProxy.getSqlTemplate().queryForList(condition, hashMap);
        SetEventInfo setEventInfo = new SetEventInfo();
        setEventInfo.setUserColumns(hashMap);
        RemoveInfo removeInfo = new RemoveInfo();
        for (Map<String, Object> MP : MPlIST) {
            //根据当前的数据跟新完工报告且删除入库表的数据
            String sql = "SELECT M.RECEIVEREQUESTNAME,M.RECEIVEREQUESTDETAILNAME,M.QTY FROM MATERIALPACKINGSUB M WHERE M.MATERIALPACKINGNAME = :MATERIALPACKINGNAME\r\n" +
                    "UNION \r\n" +
                    "SELECT M.RECEIVEREQUESTNAME,M.RECEIVEREQUESTDETAILNAME,M.QTY FROM MATERIALPACKINGSUBHISTORY M WHERE M.MATERIALPACKINGNAME = :MATERIALPACKINGNAME";
            String MATERIALPACKINGNAME = MP.get("MATERIALPACKINGNAME").toString();
            hashMap.put("MATERIALPACKINGNAME", MATERIALPACKINGNAME);
            List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap);
            for (int i = 0; i < queryForList.size(); i++) {
                String dh = queryForList.get(i).get("RECEIVEREQUESTNAME").toString();
                hashMap.put("RECEIVEREQUESTNAME", dh);
                String hh = queryForList.get(i).get("RECEIVEREQUESTDETAILNAME").toString();
                hashMap.put("RECEIVEREQUESTDETAILNAME", hh);
//				String sl = queryForList.get(i).get("QTY").toString();
                String updateSql = "UPDATE MATERIALRECEIVEREQUESTDETAIL T  \r\n" +
                        "SET T.RECEIVEDQUANTITY = T.RECEIVEDQUANTITY - (  \r\n" +
                        "    SELECT NVL(SUM(M.QTY),0)  \r\n" +
                        "    FROM MATERIALPACKINGSUB M  \r\n" +
                        "    WHERE M.MATERIALPACKINGNAME = :MATERIALPACKINGNAME  \r\n" +
                        "      AND M.RECEIVEREQUESTNAME = T.RECEIVEREQUESTNAME  \r\n" +
                        "      AND M.RECEIVEREQUESTDETAILNAME = T.RECEIVEREQUESTDETAILNAME  \r\n" +
                        ")  \r\n" +
                        "WHERE T.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME  \r\n" +
                        "  AND T.RECEIVEREQUESTDETAILNAME = :RECEIVEREQUESTDETAILNAME";
                IDMFrameServiceProxy.getSqlTemplate().update(updateSql, hashMap);


                String updateSql2 = "UPDATE MATERIALRECEIVEREQUESTDETAIL T  \r\n" +
                        "SET T.RECEIVEDQUANTITY = T.RECEIVEDQUANTITY - (  \r\n" +
                        "    SELECT NVL(SUM(M.QTY),0)  \r\n" +
                        "    FROM MATERIALPACKINGSUBHISTORY M  \r\n" +
                        "    WHERE M.MATERIALPACKINGNAME = :MATERIALPACKINGNAME  \r\n" +
                        "      AND M.RECEIVEREQUESTNAME = T.RECEIVEREQUESTNAME  \r\n" +
                        "      AND M.RECEIVEREQUESTDETAILNAME = T.RECEIVEREQUESTDETAILNAME  \r\n" +
                        ")  \r\n" +
                        "WHERE T.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME  \r\n" +
                        "  AND T.RECEIVEREQUESTDETAILNAME = :RECEIVEREQUESTDETAILNAME";
                IDMFrameServiceProxy.getSqlTemplate().update(updateSql2, hashMap);

                String deleteSql = " DELETE FROM MATERIALPACKINGSUB T WHERE T.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME AND "
                        + "T.RECEIVEREQUESTDETAILNAME = :RECEIVEREQUESTDETAILNAME AND T.MATERIALPACKINGNAME = :MATERIALPACKINGNAME";
                IDMFrameServiceProxy.getSqlTemplate().update(deleteSql, hashMap);

                String MESsQL = " UPDATE BS_MES_SHIPPED T SET T.RECEIVE_FLAG = 'N' WHERE T.LOTNAME = :MATERIALPACKINGNAME ";
                IDMFrameServiceProxy.getSqlTemplate().update(MESsQL, hashMap);
            }
            MaterialPackingServiceProxy.getMaterialPackingService().remove(new MaterialPackingKey("SDK", MATERIALPACKINGNAME), makeEventInfo, removeInfo);
        }

        String sql = "UPDATE IF_ERPUNDO T SET T.FLAG = 'Y' WHERE  T.UNDOID = :UNDOID ";
        Map<String, Object> hashMap2 = new HashMap<String, Object> ();
        hashMap2.put("UNDOID", undoId);
        IDMFrameServiceProxy.getSqlTemplate().update(sql, hashMap2);

        result = AjaxResult.me().setSuccess(true).setErrorCode(200).setMessage("执行成功");
        return result;
    }
    // 改造成mybase实现
//    @Override
//    @Transactional
//    public AjaxResult sapcprkUndo(String undoId, String user) throws Exception {
//
//        String billCode = toSAPService.cancelShipInter(undoId, user);
//        if (billCode == null) {
//            throw new GlobalException("报送ERP失败,请联系IT处理！");
//        }
//
//
//        AjaxResult result = new AjaxResult();
//
//        EventInfo makeEventInfo = new EventInfoUtil ().makeEventInfo("MakeUndo", user, "MakeUndo");
//        String  condition="SELECT MATERIALPACKINGNAME FROM MATERIALPACKING WHERE UNDOID = :UNDOID ";
////		String[] bindSet={undoId};
//        Map<String, Object> hashMap = new HashMap<String, Object> ();
//        hashMap.put("UNDOID", undoId);
//        //根据物料凭证找到所有的待冲销数据，更新库存状态为创建
//        List<Map<String, Object>> MPlIST = IDMFrameServiceProxy.getSqlTemplate().queryForList(condition, hashMap);
//        SetEventInfo setEventInfo = new SetEventInfo();
//        setEventInfo.setUserColumns(hashMap);
//        RemoveInfo removeInfo = new RemoveInfo();
//        for (Map<String, Object> MP : MPlIST) {
//            //根据当前的数据跟新完工报告且删除入库表的数据
//            String MATERIALPACKINGNAME = MP.get("MATERIALPACKINGNAME").toString();
//            hashMap.put("MATERIALPACKINGNAME", MATERIALPACKINGNAME);
//            List<MaterialPackingSubDto> queryForList = mesToWmsDao.getEndReportList(MATERIALPACKINGNAME);
//
//            for (int i = 0; i < queryForList.size(); i++) {
//                String dh = queryForList.get(i).getReceiveRequestName().toString();
//                hashMap.put("RECEIVEREQUESTNAME", dh);
//                String hh = queryForList.get(i).getReceiveRequestDetailName().toString();
//                hashMap.put("RECEIVEREQUESTDETAILNAME", hh);
//
//                mesToWmsDao.updateEndReport(dh, hh, MATERIALPACKINGNAME);
//
//                mesToWmsDao.updateEndReport2(dh, hh, MATERIALPACKINGNAME);
//
//                mesToWmsDao.deleteSub(dh, hh, MATERIALPACKINGNAME);
//
//                mesToWmsDao.updateBsMesShipped(MATERIALPACKINGNAME);
//
//            }
//            MaterialPackingServiceProxy.getMaterialPackingService().remove(new MaterialPackingKey("SDK", MATERIALPACKINGNAME), makeEventInfo, removeInfo);
//        }
//
//        Map<String, Object> hashMap2 = new HashMap<String, Object> ();
//        hashMap2.put("UNDOID", undoId);
//        mesToWmsDao.updateUnDoId(undoId);
//
//        result = AjaxResult.me().setSuccess(true).setErrorCode(200).setMessage("执行成功");
//        return result;
//    }

    @Override
    @Transactional
    public AjaxResult shipByMES(JSONArray in) throws Exception {
        AjaxResult result = new AjaxResult();
        ErpMessageLog loginfo = new ErpMessageLog();
        loginfo.setServerName("MESToWms");
        loginfo.setMessageId("");
        loginfo.setEventUser("MES");
        loginfo.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
        loginfo.setSendMsg(in.toJSONString());
        loginfo.setEventName("Ship_Request");

        List<String> boxIdList = new ArrayList<>();
        List<String> barCodeList = new ArrayList<>();
        String stockInType = ""; // 用于记录是产成品入库，还是生产退料入库  入库类型，成品FG，退料MAT
        String operationType = ""; // 用于记录是否是自动入库  手动入库0，自动入库1
        String fgStockIn = "";
        if (in != null && in.size() > 0) {
            for (int i = 0; i < in.size(); i++) {
                JSONObject jb = in.getJSONObject(i);
                String charge = jb.get("charge").toString(); // 批号
                boxIdList.add(charge);
                barCodeList.add(jb.get("lotName").toString());
            }
            String sqld = "SELECT b.charge FROM BS_MES_SHIPPED  b WHERE b.CHARGE in(:BOXIDLIST) ";
            Map<String, Object> hashMap = new HashMap<>();
            hashMap.put("BOXIDLIST", boxIdList);
            List<Map<String, Object>> existShips = sqlTemplate.queryForList(sqld, hashMap);
            if (existShips != null && existShips.size() > 0) {
                List<String> lots = new ArrayList<>();
                for (Map<String, Object> existShip : existShips) {
                    String lot = (String) existShip.get("charge");
                    lots.add(lot);
                }

                result = AjaxResult.me().setSuccess(false).setErrorCode(500).setMessage("执行失败:" + lots + " 已经SHIP,请不要重复SHIP");
                return result;
            }
            String needIqcSql = SystemPropHelper.CR + "SELECT IQCFLAG "
                    + "  FROM BS_MATERIALFACTORY bm "
                    + " WHERE bm.MATERIALSPECNAME = :MATERIALSPECNAME "
                    + "   AND bm.ERPFACTORY = :ERPFACTORY";
            String insertSql = SystemPropHelper.CR + "INSERT INTO BS_MES_SHIPPED(LOTNAME,QTY, UNIT, REQUESTNAME, AREA, "
                    + "PRODUCTSPECNAME, PRODUCTNAME, SDK_ID, PHASE, RECEIVE_FLAG,  REMARK, SHIPTIME, "
                    + "SHIPUSER, SITENAME, MATERIALSPECTYPE,"
                    + "INVENTORYTYPE, SALENO, SALEDETAILNO, ERPLOCATION, CHARGE, LOCATIONNAME, "
                    + "OPERATIONTYPE, ERPFACTORY,GXID)" + SystemPropHelper.CR
                    + "                     VALUES(:LOTNAME,:QTY,:UNIT,:REQUESTNAME, :AREA, "
                    + ":PRODUCTSPECNAME, :PRODUCTNAME, :SDK_ID, :PHASE, 'N',  :REMARK, :SHIPTIME, "
                    + "'MES', 'SDK', :MATERIALSPECTYPE, "
                    + ":INVENTORYTYPE, :SALENO, :SALEDETAILNO, :ERPLOCATION, :CHARGE, :LOCATIONNAME, "
                    + ":OPERATIONTYPE, :ERPFACTORY,:GXID)";
            String receiveActNo = "";
            String productSpecName = "";
            String erpFactory = "";
            for (int i = 0; i < in.size(); i++) {
                JSONObject jo = in.getJSONObject(i);
                String charge = jo.get("charge").toString(); // 批号
                String lotname = jo.getString("lotName");
                double qty = StringUtils.isEmpty(jo.getString("qty")) ? 0 : Double.parseDouble(jo.getString("qty"));
                String unit = jo.getString("unit");
                String requestName = jo.getString("requestName");
                String area = jo.getString("area");
                //recycledParticlesSpec表示回收粒子
                productSpecName = jo.getString("productSpecName");
                String productName = jo.getString("productName");
                String sdkId = jo.getString("sdkId");
                String phase = jo.getString("phase");
                String remark = jo.getString("remark");
                String shipTimeStr = jo.getString("shipTime");
                Timestamp shipTime = StringUtils.isEmpty(shipTimeStr) ? TimeStampUtil.getCurrentTimestamp() : TimeStampUtil.getTimestamp(shipTimeStr);
                String shipUser = jo.getString("shipUser");
                String inventoryType = jo.getString("inventoryType");
                String saleNo = jo.getString("saleNo");
                String saleDetailNo = jo.getString("saleDetailNo");
                String erpLocation = jo.getString("erpLocation");
                String locationName = jo.getString("locationName");
                String gxId = jo.getString("gxId"); // 增加管芯字段
//                String makeDate = jo.getString("makeDate");
                erpFactory = jo.getString("erpFactory");
                if (i == 0) {
                    stockInType = jo.getString("stockInType");
                    operationType = jo.getString("operationType");
                    List<String> args = Arrays.asList(new String[]{"SH", "F", TimeStampUtil.getCurrentTime("yyyyMMdd")});
                    receiveActNo = NameServiceProxy.getNameRuleDefService().generateName("ReceiveActNo", args, 1).get(0);
                }
                String recycledParticlesSpec = jo.get("recycledParticlesSpec") == null ? "" : jo.get("recycledParticlesSpec").toString();
                //如果是回收例子，料号修改为recycledParticlesSpec
                if ("BFG".equals(stockInType)) {
                    productSpecName = recycledParticlesSpec;
                    //回收粒子需要生成新的Box ID
                    List<String> boxIDs =  MaterialPackingServiceImpl.generateBoxID("LabelId", "SDK",
                            1 + ""
                            , shipTimeStr, "SH", erpFactory);
                    lotname = boxIDs.get(0);
                }
                Map<String, Object> bindMap = new HashMap<>();
                bindMap.put("LOTNAME", lotname);
                bindMap.put("QTY", qty);
                bindMap.put("UNIT", unit);
                bindMap.put("REQUESTNAME", requestName);
                bindMap.put("AREA", area);
                bindMap.put("PRODUCTSPECNAME", productSpecName);
                bindMap.put("PRODUCTNAME", productName);
                bindMap.put("SDK_ID", sdkId);
                bindMap.put("PHASE", phase);
                bindMap.put("REMARK", remark);
                bindMap.put("SHIPTIME", shipTime);
                bindMap.put("SHIPUSER", shipUser);
                bindMap.put("INVENTORYTYPE", inventoryType);
                bindMap.put("SALENO", saleNo);
                bindMap.put("SALEDETAILNO", saleDetailNo);
                bindMap.put("ERPLOCATION", erpLocation);
                bindMap.put("LOCATIONNAME", locationName);
                bindMap.put("OPERATIONTYPE", operationType);
                bindMap.put("ERPFACTORY", erpFactory);
                bindMap.put("MATERIALSPECTYPE", stockInType);
                bindMap.put("CHARGE", charge);
                bindMap.put("GXID", gxId);
//                bindMap.put("makeDate", makeDate);

                if ("1".equals(operationType)) { // 自动入库
                    if ("FG".equals(stockInType) || "BFG".equals(stockInType)) { // 产成品入库  增加回收例子入库
                        sqlTemplate.update(insertSql, bindMap);
                        MaterialPackingServiceImpl.checkMaterialPackingExist(lotname);

                        EventInfo makeEventInfo = EventInfoUtil.makeEventInfo("createfgBoxInfo", "MES", "createfgBoxInfo", "", "");
                        productIntoServiceImpl.receiveMesShippInfo(makeEventInfo, "SDK", lotname, "", "MES",
                                lotname, receiveActNo, erpLocation, erpFactory, locationName, requestName, "", "");
                    } else if ("MAT".equals(stockInType)) { // 生产退料入库
                        Map<String, Object> iqcBind = new HashMap<>();
                        iqcBind.put("MATERIALSPECNAME", productSpecName);
                        iqcBind.put("ERPFACTORY", erpFactory);
                        List<Map<String, Object>> iqcFlags = sqlTemplate.queryForList(needIqcSql, iqcBind);
                        if (iqcFlags != null && iqcFlags.size() > 0) {
                            if ("Y".equals(iqcFlags.get(0).get("IQCFLAG"))) {
                                throw new GlobalException("物料[" + productSpecName + "]需要质检，不允许自动入库，请手动入库");
                            }
                        }
                        sqlTemplate.update(insertSql, bindMap);
                        MaterialPackingServiceImpl.checkMaterialPackingExist(lotname);

                        EventInfo makeEventInfo = EventInfoUtil.makeEventInfo("createBoxInfoReturn", "MES", "createBoxInfoReturn", "", "");
//                        returnStockIntoServiceImpl.CreateMaterialReceiveRequestAct
//                                (makeEventInfo, "SDK", requestName, productSpecName, shipTimeStr,
//                                        receiveActNo, "ProduceReturn", Double.toString(qty), productSpecName);
                        returnStockIntoServiceImpl.SHIPMesShippInfo(makeEventInfo, "SDK", lotname, "", "MES",
                                lotname, receiveActNo, erpLocation, erpFactory, locationName, requestName,
                                productSpecName);
                    }
                } else {
                    sqlTemplate.update(insertSql, bindMap);
                }

            }
            if ("1".equals(operationType)) { // 自动入库
                if ("FG".equals(stockInType) || "BFG".equals(stockInType)) { // 产成品入库 增加回收粒子入库
                    fgStockIn = productIntoServiceImpl.outoFgStockIn(receiveActNo, "MES");
                    if (fgStockIn.isEmpty()) {
                        throw new GlobalException("报送ERP失败,请联系IT处理！");
                    }
                    String checkIqcSql = "SELECT DISTINCT MATERIALSPECNAME, ERPFACTORY FROM MATERIALPACKING m WHERE M.RECEIVEACTNO = :RECEIVEACTNO";
                    Map<String, Object> bindMap = new HashMap<>();
                    bindMap.put("RECEIVEACTNO", receiveActNo);
                    bindMap.put("MATERIALSPECNAME", productSpecName);
                    bindMap.put("ERPFACTORY", erpFactory);
                    List<Map<String, Object>> materialSpecs = sqlTemplate.queryForList(needIqcSql, bindMap);
                    if (materialSpecs != null && materialSpecs.size() > 0) {
                        for (Map<String, Object> materialSpec : materialSpecs) {
                            Map<String, Object> iqcBind = new HashMap<>();
                            iqcBind.put("MATERIALSPECNAME", materialSpec.get("MATERIALSPECNAME"));
                            iqcBind.put("ERPFACTORY", materialSpec.get("ERPFACTORY"));
                            List<Map<String, Object>> iqcFlags = sqlTemplate.queryForList(needIqcSql, iqcBind);
                            if (iqcFlags != null && iqcFlags.size() > 0) {
                                if ("Y".equals(iqcFlags.get(0).get("IQCFLAG"))) {
                                    qmsService.PreIQCInfoSend(receiveActNo, "SDK", "", "");
                                }
                            }
                        }
                    }

                } else if ("MAT".equals(stockInType)) { // 生产退料入库
                    fgStockIn = returnStockIntoServiceImpl.ReturnStockIn(receiveActNo, "MES", "", "");
                    if (fgStockIn.isEmpty()) {
                        throw new GlobalException("报送ERP失败,请联系IT处理！");
                    }
                    return AjaxResult.me().setResultObj(null);
                }
            }
        }
        result = AjaxResult.me().setResultObj(fgStockIn).setSuccess(true).setErrorCode(200).setMessage("执行成功");
        loginfo.setResultCode("S");
        loginfo.setReturnMsg(JSONObject.toJSONString(result));
        // 消息保存日志，erp推送wms的数据写入表BS_ERPMESSAGELOG中
        MessageLogUtil.writeMessageLog(loginfo);
        return result;
    }
}