package com.sw.mes.webservice.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.sw.mes.base.factory.init.entity.MachineCapacityInfo;
import com.sw.mes.base.factory.init.service.MachineCapacityInfoService;
import com.sw.mes.base.factory.material.entity.MaterialModel;
import com.sw.mes.base.factory.material.entity.MaterialType;
import com.sw.mes.base.factory.material.entity.Unit;
import com.sw.mes.base.factory.material.service.MaterialModelService;
import com.sw.mes.base.factory.material.service.MaterialTypeService;
import com.sw.mes.base.factory.material.service.UnitService;
import com.sw.mes.base.factory.product.entity.FbProductModel;
import com.sw.mes.base.factory.product.entity.ProductModel;
import com.sw.mes.base.factory.product.service.FbProductModelService;
import com.sw.mes.base.factory.product.service.ProductModelService;
import com.sw.mes.base.system.entity.DictionaryItem;
import com.sw.mes.base.system.entity.SysLog;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.base.system.service.SysLogService;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.utils.IpUtils;
import com.sw.mes.core.utils.RegexUtils;
import com.sw.mes.core.utils.StringUtils;
import com.sw.mes.enumvalue.EnumValuesServer;
import com.sw.mes.mmcs.service.MMcsInterfaceService;
import com.sw.mes.third.entity.*;
import com.sw.mes.webservice.entity.MaterialNumberOutPut;
import com.sw.mes.webservice.entity.ProductionOrderOutPut;
import com.sw.mes.webservice.service.MyWebService;
import com.sw.mes.yb.plan.entity.FbProductionOrder;
import com.sw.mes.yb.plan.entity.ProductionOrder;
import com.sw.mes.yb.plan.service.FbProductionOrderService;
import com.sw.mes.yb.plan.service.ProductionOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.jws.WebService;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@WebService(
        serviceName = "MyWebService", // 与接口中指定的name一致
        targetNamespace = "http://service.webservice.mes.sw.com", // 与接口中的命名空间一致,一般是接口的包名倒序
        endpointInterface = "com.sw.mes.webservice.service.MyWebService"// 接口地址
)
@Service
@Transactional
@Slf4j
public class MyWebServiceImpl implements MyWebService {

	@Autowired
	private MaterialTypeService materialTypeService;
	@Autowired
	private MaterialModelService materialModelService;
	@Autowired
	private ProductModelService ybProductModelService;
	@Autowired
	private FbProductModelService fbProductModelService;
	@Autowired
	private ProductionOrderService ybProductionOrderService;
	@Autowired
	private FbProductionOrderService fbProductionOrderService;
	@Autowired
	private MachineCapacityInfoService machineCapacityInfoService;
	@Autowired
	private UnitService unitService;
	@Autowired
	private SysLogService sysLogService;
	@Autowired
	private DictionaryItemService dictionaryItemService;
	@Autowired
	private MMcsInterfaceService mMcsInterfaceService;

    @Override
    public SoapOutDto SAP_TO_1031MES_Request(SoapInDto soapInDto) {
        SoapOutDto soapOutDto=new SoapOutDto();
        try {
        	log.debug("***********接收sap发过来的消息*********" + soapInDto.toString());
            if (soapInDto != null) {
                soapOutDto.setBSKEY(soapInDto.getBSKEY());
                soapOutDto.setSAPKEY(soapInDto.getSAPKEY());
                soapOutDto.setZTYPE(soapInDto.getIFYWID());
                soapOutDto.setZMESSAGE("success");
                List<SoapData> soapDataList=new ArrayList<>();
                //List<SoapDataStore> soapDataStoreList = new ArrayList<>();
                soapOutDto.setBSKEY(UUID.randomUUID().toString());
                if ("1031MES".equals(soapInDto.getSYSID())){
                    soapOutDto.setZTYPE("S");
                    soapOutDto.setZMESSAGE("success");
                    if (soapInDto.getIFYWID().equalsIgnoreCase(WebServiceApiName.MaterialNumber)) {//处理物料主数据
                        soapDataList=setMaterialNumber(soapInDto.getZDATA());
                        soapOutDto.setZDATA(JSONObject.toJSON(soapDataList).toString());
                    } else if (soapInDto.getIFYWID().equalsIgnoreCase(WebServiceApiName.ProductionOrder)) {//处理订单数据
                        soapDataList= setProductionOrder(soapInDto.getZDATA());
                        soapOutDto.setZDATA(JSONObject.toJSON(soapDataList).toString());
                    }
//                    else if(soapInDto.getIFYWID().equalsIgnoreCase("PP060")){
//                        soapDataStoreList= setStore(soapInDto.getZDATA(),soapInDto.getSAPKEY());
//                        soapOutDto.setZDATA(JSONObject.toJSON(soapDataStoreList).toString());
//                    }
                }else{
                    soapOutDto.setZTYPE("E");
                    soapOutDto.setZMESSAGE("不是中环六期接收的数据！！！");
                }
            }
        } catch (Exception e) {
            soapOutDto.setZTYPE("E");
            soapOutDto.setZMESSAGE("调用异常");
			log.error("调用异常：错误信息", e);
        }

        try {
	        SysLog syslog = new SysLog();
	        syslog.setCreateTime(new Date());
	        syslog.setType("info");
	        syslog.setCreateUserId(BaseContextHandler.getUserID());
	        syslog.setCreateUserName("SAP");
	        syslog.setContent(JSON.toJSONString(soapInDto));
	        syslog.setResult(JSON.toJSONString(soapOutDto));
	        syslog.setCreateUserId(-1);
	        syslog.setMethodName("SAP_TO_1031MES_Request()");
	        syslog.setStatus(1);
	        syslog.setName("SAP数据传入MES");
	        String serverAddr = "http://"+IpUtils.getLocalIP()+":9007/MES-PC-SERVER/service/ZHXX_MES_SAP_WebService";
	        syslog.setServerAddr(serverAddr);
	        syslog.setReqType("WebService");
	        syslog.setReqIp(IpUtils.getWebServiceReqIP());
	        sysLogService.save(syslog);
        }catch (Exception e) {
			log.error("日志记录错误：", e);
		}

        log.info("******8返回给sap的数据******"+soapOutDto.toString());


        //System.out.println(JSON.toJSONString(soapInDto));

        return soapOutDto;
    }



//    public static void main(String[] args) {
//
//	    String str = "12.50";
//
//	    String regex="[0-9]+(\\.[0-9]+)?";
//
//	    Pattern p = Pattern.compile(regex);
//
//	    Matcher m = p.matcher(str);
//
//	    while (m.find()) {
//
//	    if (!"".equals(m.group()))
//
//	    System.out.println("价格:" + m.group());
//
//	    }
//
//    }





    /**设置物料数据**/
    private List<SoapData> setMaterialNumber(String parameter)   {
        log.info("***收到物料主数据的数据***"+parameter);
        List<SoapData> soapDataList=new ArrayList<>();
        List<MaterialNumberOutPut> list = null;
        try {
            list = JSONObject.parseArray(parameter, MaterialNumberOutPut.class);
        } catch (JSONException e) {
        	e.printStackTrace();
            log.info(e.getMessage());
            throw  new RuntimeException("Json字符串数据格式错误");
        }
        if (list!=null && !list.isEmpty()) {

        	//查询数据字典长度范围对照表 product_length
        	List<DictionaryItem> _lenItems = dictionaryItemService.findByThemeValueAndEnable(EnumValuesServer.DictionaryTheme.产品长度.getKey(), true);
        	Map<String, DictionaryItem> _lenItemsMap = _lenItems.stream().collect(Collectors.toMap(DictionaryItem::getExtendValue, DictionaryItem -> DictionaryItem));

        	List<DictionaryItem> items = dictionaryItemService.findByThemeValueAndEnable(EnumValuesServer.DictionaryTheme.物料类别.getKey(), true);
            Map<String, DictionaryItem> collect = items.stream().collect(Collectors.toMap(DictionaryItem::getValue, DictionaryItem -> DictionaryItem));


            for (MaterialNumberOutPut materialNumber : list) {
                SoapData soapData =new SoapData();
                //log.info("****materialNumber*****"+materialNumber);
                if (WebServiceApiName.MESID.equals(materialNumber.getWERKS())){

                	String maktx = materialNumber.getMAKTX();
                    if(!StringUtils.isBlank(maktx)) {
                    	String[] maktxs = maktx.split("/");
                    	String type = maktx.substring(0,1);
	                	if((type.equals("方") && (maktxs.length==10 || maktxs.length==9)) || (type.equals("圆") && (maktxs.length==8 || maktxs.length==7)) || type.equals("籽")) {
	                		soapData.setResult(0);
	                        soapData.setTID(materialNumber.getMATNR());
	                        soapDataList.add(soapData);
	                	}else {
	                		soapData.setResult(1);
	                        soapData.setTID(materialNumber.getMATNR());
	                        soapData.setErrorDesc("物料信息格式错误,");
	                        soapDataList.add(soapData);
	                	}
                    }else {
                    	soapData.setResult(1);
                        soapData.setTID(materialNumber.getMATNR());
                        soapData.setErrorDesc("没有物料描述信息");
                        soapDataList.add(soapData);
                    }


                    //物料表更新、新增

                    //materialType 数据字典
                    //过滤未配置的物料类别不接收

                    if(collect.get(materialNumber.getEXTWG())==null) {
                    	continue;
                    }


                    Date currentDate = new Date();

                    //物料类型
                    MaterialType materialType = materialTypeService.getByCode(materialNumber.getMATKL());//MATKL 物料组
                    if(materialType==null) {
                    	materialType = new MaterialType();
                    	materialType.setCreateDate(currentDate);
                    	materialType.setCreateUser("SAP");
                    	materialType.setCode(materialNumber.getMATKL());//编码 - 物料组
                    }
                    materialType.setDel((materialNumber.getLVORM()!=null && materialNumber.getLVORM().equals("X"))?true:false);//LVORM 删除标识
                    materialType.setType(materialNumber.getEWBEZ()+"("+materialNumber.getEXTWG()+")");//MTBEZ 类型描述  MTART类型
                    materialType.setName(materialNumber.getWGBEZ());//WGBEZ 物料组描述
                    //添加或更新物料类型
                    materialTypeService.saveOrUpdate(materialType);


                    //物料主数据
                    MaterialModel materialModel = materialModelService.findByCode(materialNumber.getMATNR());
                    if(materialModel==null) {
                    	materialModel = new MaterialModel();
                    	materialModel.setCode(materialNumber.getMATNR());//物料编码 物料编码
                    	materialModel.setMaterialType(materialType);
                    	materialModel.setCreateDate(currentDate);
                    	materialModel.setCreateUser("SAP");
                    }
                    materialModel.setDel((materialNumber.getLVORM()!=null && materialNumber.getLVORM().equals("X"))?true:false);//LVORM 删除标识
                    materialModel.setName(materialNumber.getMAKTX());//MAKTX 物料描述

                    //补录内容2022/6/1
                    materialModel.setMstae(materialNumber.getMSTAE());
                    materialModel.setLoggr(materialNumber.getLOGGR());
                    materialModel.setLtext(materialNumber.getLTEXT());
                    materialModel.setEkgrp(materialNumber.getEKGRP());
                    materialModel.setXchpf(materialNumber.getXCHPF());
                    materialModel.setMeinh(materialNumber.getMEINH());
                    materialModel.setUmren(materialNumber.getUMREN());
                    materialModel.setUmrez(materialNumber.getUMREZ());
                    materialModel.setBstrf(materialNumber.getBSTRF());
                    materialModel.setZbty(materialNumber.getZBTY());
                    materialModel.setBismt(materialNumber.getBISMT());
                    materialModel.setWerks(materialNumber.getWERKS());
                    materialModel.setWorkRemark(materialNumber.getNAME1());
                    materialModel.setMtart(materialNumber.getMTART());
                    materialModel.setMtbez(materialNumber.getMTBEZ());
                    materialModel.setMatnr(materialNumber.getMATNR());
                    materialModel.setMaktx(materialNumber.getMAKTX());
                    materialModel.setMatkl(materialNumber.getMATKL());
                    materialModel.setWgbez(materialNumber.getWGBEZ());
                    materialModel.setExtwg(materialNumber.getEXTWG());
                    materialModel.setEwbez(materialNumber.getEWBEZ());
                    materialModel.setMeins(materialNumber.getMEINS());

                    //单位   //MEINS
                    if(!StringUtils.isBlank(materialNumber.getMEINS())) {
                    	Unit unit = unitService.getCode(materialNumber.getMEINS());
                    	if(unit==null) {
                    		unit = new Unit();
                    		unit.setCode(materialNumber.getMEINS());
                    		unit.setName(materialNumber.getMEINS());
                    		unit.setCreateDate(currentDate);
                    		unit.setCreateUser("SAP");
                    		unit.setDel(false);
                        	unitService.saveOrUpdate(unit);
                    	}
                    	//设置物料主数据单位
                    	materialModel.setUnit(unit);
                    }

                    //添加更新物料主数据
                    materialModelService.saveOrUpdate(materialModel);




                    //补录单晶产品模型  - MAKTX(物料描述)
                    //圆(扭细)/P/B/223/PA-1/80-698/1/NA
                    //方-工/P/B/158.75/223/PA-1/0.3-1.5/＞60/1
                    maktx = materialNumber.getMAKTX();
                    if(!StringUtils.isBlank(maktx)) {
                    	String[] maktxs = maktx.split("/");
                    	String type = maktx.substring(0,1);

                    	if((type.equals("方") && (maktxs.length==10 || maktxs.length==9)) || (type.equals("圆") && (maktxs.length==8 || maktxs.length==7))) {
                    		String matnr = materialNumber.getMATNR();//物料编号
                    		String productName = materialNumber.getMAKTX();//物料编号
                    		if(type.equals("方")) {//方棒
                    			FbProductModel model = fbProductModelService.findByProductNo(matnr);
                    			if(model==null) {
                    				model = new FbProductModel();
                    				model.setProductNo(matnr);
                    			}
                    			model.setProductLevel(maktxs[5]);
                				model.setConductiveType(maktxs[1]);
                				model.setDopant(maktxs[2]);
                				model.setCrystalDiameter(RegexUtils.getBigDecimal(maktxs[4]));
                				model.setSideLength(RegexUtils.getBigDecimal(maktxs[3]));
                				model.setSpecs(maktxs[4]);
                				model.setResistivity(maktxs[6]);
                				String[] resistivity = model.getResistivity().split("-");
                				if(resistivity.length==2) {
                					model.setResistivityMin(RegexUtils.getBigDecimal(resistivity[0]));
                    				model.setResistivityMax(RegexUtils.getBigDecimal(resistivity[1]));
                				}
                				model.setLength(getLengScope(_lenItemsMap , maktxs[7]));
                				model.setSpellNo(maktxs[8]);
                				if(maktxs.length==10) {
                					model.setCustomer(maktxs[9]);
                				}
                				model.setRemark(maktx);
                				model.setCreateUser("SAP");
                				model.setCreateTime(currentDate);
                				model.setMaterialType(materialType);
                				model.setDel(false);

                    			fbProductModelService.saveOrUpdate(model);
                    		}else {//圆棒
                    			ProductModel model = ybProductModelService.findByCode(matnr);
                    			if(model==null) {
                    				model = new ProductModel();
                    				model.setName(productName);
                    				model.setCode(matnr);
                    			}
                    			model.setProductGrade(maktxs[4]);
                    			model.setDopant(maktxs[2]);
                    			model.setMaterialType(materialType);
                    			model.setCreateUser("SAP");
                    			model.setCreateDate(currentDate);
                    			model.setDrawMethod("C");
                    			model.setOrientation("C");
                    			model.setSpecs(maktxs[3]);
                    			model.setConductionType(maktxs[1]);
                    			model.setLenRange(getLengScope(_lenItemsMap , maktxs[5]));
                    			model.setSticksCount(RegexUtils.getBigDecimal(maktxs[6]).intValue());
                    			model.setRemark(maktx);
                    			model.setDel(false);

                    			ybProductModelService.saveOrUpdate(model);
                    		}
                    	}
                    }
                }else{
                    soapData.setResult(1);
                    soapData.setTID(materialNumber.getMATNR());
                    soapData.setErrorDesc("不是六期需要的数据");
                    soapDataList.add(soapData);
                }
            }


            try {
            	//MMCS 同步物料信息接口
            	//mMcsInterfaceService.mcsMaterialToMmcs(list);
            }catch (Exception e) {
			}

        }
        return  soapDataList;
    }

    /**过滤长度范围**/
    private String getLengScope(Map<String, DictionaryItem> _lenItemsMap,String value) {
    	if(StringUtils.isBlank(value)) {
    		return value;
    	}

    	DictionaryItem dic =_lenItemsMap.get(value);
    	if(dic!=null) {
    		return dic.getValue();
    	}
    	return value;
    }

    /**设置订单数据**/
    private List<SoapData> setProductionOrder(String parameter) {
        log.info("***收到订单主数据的数据***"+parameter);
        List<SoapData> soapDataList=new ArrayList<>();
        List<ProductionOrderOutPut> list=null;
        try {
            list = JSONObject.parseArray(parameter, ProductionOrderOutPut.class);
        } catch (JSONException e) {
            log.info(e.getMessage());
            throw  new RuntimeException("Json字符串数据格式错误");
        }
        if (list!=null && !list.isEmpty()){
            for (ProductionOrderOutPut productionOrder : list) {
                log.debug("****productionOrder*****"+productionOrder);
                SoapData soapData =new SoapData();
                try {
	                if (WebServiceApiName.MESID.equals(productionOrder.getWERKS())){
	                    soapData.setResult(0);
	                    soapData.setTID(productionOrder.getTID());
	                    soapDataList.add(soapData);
	                    //判断是方棒订单还是圆棒订单
	                    //确认物料主数据是否存在 - 物料编号
	                    MaterialModel materialModel = materialModelService.findByCode(productionOrder.getMATNR());
	                    if(materialModel==null){
	                        soapData.setResult(1);
	                        soapData.setTID(productionOrder.getTID());
	                        soapData.setErrorDesc("找不到订单对应的物料号");
	                        soapDataList.add(soapData);
	                        continue;
	                    }

	                    boolean isExist = false;
	                    ProductModel ybModel = ybProductModelService.findByCode(materialModel.getCode());
	                    if(ybModel==null) {
	                    	FbProductModel fbModel = fbProductModelService.findByProductNo(materialModel.getCode());
	                    	if(fbModel!=null) {
	                    		//方棒 plan_fb_production_order
	                    		FbProductionOrder fbProductionOrder = fbProductionOrderService.findByAufnr(productionOrder.getAUFNR());//生产订单编码
	                    		if(fbProductionOrder==null) {
	                    			fbProductionOrder = new FbProductionOrder();
	                    			fbProductionOrder.setTid(productionOrder.getTID());
	                    			fbProductionOrder.setAufnr(productionOrder.getAUFNR());
	                    			fbProductionOrder.setWerks(productionOrder.getWERKS());
	                    			fbProductionOrder.setAuart(productionOrder.getAUART());
	                    			fbProductionOrder.setMeins(productionOrder.getMEINS());
	                    			fbProductionOrder.setMatnr(productionOrder.getMATNR());
	                    			fbProductionOrder.setFbProductModel(fbModel);
	                    			fbProductionOrder.setProductionStatus(false);
	                    		}

	                    		Calendar calendar = Calendar.getInstance();

	                    		Date gltrp = productionOrder.getGLTRP();
	                    		calendar.setTime(gltrp);//08:59:59
	                    		calendar.set(Calendar.HOUR_OF_DAY, 8);
	                    		calendar.set(Calendar.MINUTE, 59);
	                    		calendar.set(Calendar.SECOND, 59);
	                    		calendar.set(Calendar.MILLISECOND, 0);
	                    		gltrp = calendar.getTime();

	                    		Date gstrp = productionOrder.getGSTRP();
	                    		calendar.setTime(gstrp);//09:00:00
	                    		calendar.set(Calendar.HOUR_OF_DAY, 9);
	                    		calendar.set(Calendar.MINUTE, 0);
	                    		calendar.set(Calendar.SECOND, 0);
	                    		calendar.set(Calendar.MILLISECOND, 0);
	                    		gstrp = calendar.getTime();

	                    		fbProductionOrder.setAprio(productionOrder.getAPRIO());
	                			fbProductionOrder.setCustomerid(productionOrder.getCUSTOMERID());
	                			fbProductionOrder.setSalesorder(productionOrder.getSALESORDER());
	                			fbProductionOrder.setOwnerengineer(productionOrder.getOWNERENGINEER());
	                			fbProductionOrder.setComment(productionOrder.getCOMMENT());
	                			fbProductionOrder.setBonded(productionOrder.getBONDED());
	                			fbProductionOrder.setRdInd(productionOrder.getRD_IND());
	                    		fbProductionOrder.setMenge(BigDecimal.valueOf(productionOrder.getMENGE()));
	                    		fbProductionOrder.setGltrp(gltrp);
	                			fbProductionOrder.setGstrp(gstrp);
	                			fbProductionOrder.setStatus(productionOrder.getSTATUS());
	                			fbProductionOrder.setRdNum(productionOrder.getRD_NUM());
	                			fbProductionOrder.setField1(productionOrder.getFIELD1());
	                			fbProductionOrder.setField2(productionOrder.getFIELD2());
	                			fbProductionOrder.setField3(productionOrder.getFIELD3());
	                			fbProductionOrder.setField4(productionOrder.getFIELD4());
	                			fbProductionOrder.setField5(productionOrder.getFIELD5());
	                			fbProductionOrder.setCreateDate(new Date());
	                			fbProductionOrderService.saveOrUpdate(fbProductionOrder);

	                    		isExist = true;
	                    	}
	                    }else {
	                    	//圆棒 plan_production_order
	                    	ProductionOrder ybProductionOrder = ybProductionOrderService.findByAufnr(productionOrder.getAUFNR());//生产订单编码

	                		if(ybProductionOrder==null) {
	                			ybProductionOrder = new ProductionOrder();
	                			ybProductionOrder.setTid(productionOrder.getTID());
	                			ybProductionOrder.setAufnr(productionOrder.getAUFNR());
	                			ybProductionOrder.setWerks(productionOrder.getWERKS());
	                			ybProductionOrder.setAuart(productionOrder.getAUART());
	                			ybProductionOrder.setMeins(productionOrder.getMEINS());
	                			ybProductionOrder.setMatnr(productionOrder.getMATNR());
	                			ybProductionOrder.setProductModel(ybModel);
	                			ybProductionOrder.setProductionStatus(false);
	                		}


	                		Calendar calendar = Calendar.getInstance();

                    		Date gltrp = productionOrder.getGLTRP();
                    		calendar.setTime(gltrp);//08:59:59
                    		calendar.set(Calendar.HOUR_OF_DAY, 8);
                    		calendar.set(Calendar.MINUTE, 59);
                    		calendar.set(Calendar.SECOND, 59);
                    		calendar.set(Calendar.MILLISECOND, 0);
                    		gltrp = calendar.getTime();

                    		Date gstrp = productionOrder.getGSTRP();
                    		calendar.setTime(gstrp);//09:00:00
                    		calendar.set(Calendar.HOUR_OF_DAY, 9);
                    		calendar.set(Calendar.MINUTE, 0);
                    		calendar.set(Calendar.SECOND, 0);
                    		calendar.set(Calendar.MILLISECOND, 0);
                    		gstrp = calendar.getTime();

	                		ybProductionOrder.setAprio(productionOrder.getAPRIO());
	                		ybProductionOrder.setCustomerid(productionOrder.getCUSTOMERID());
	                		ybProductionOrder.setSalesorder(productionOrder.getSALESORDER());
	                		ybProductionOrder.setOwnerengineer(productionOrder.getOWNERENGINEER());
	                		ybProductionOrder.setComment(productionOrder.getCOMMENT());
	            			ybProductionOrder.setBonded(productionOrder.getBONDED());
	            			ybProductionOrder.setRdInd(productionOrder.getRD_IND());
	                		ybProductionOrder.setMenge(BigDecimal.valueOf(productionOrder.getMENGE()));
	                		ybProductionOrder.setGltrp(gltrp);
	            			ybProductionOrder.setGstrp(gstrp);
	            			ybProductionOrder.setStatus(productionOrder.getSTATUS());
	            			ybProductionOrder.setRdNum(productionOrder.getRD_NUM());
	            			ybProductionOrder.setRdonlylogo(productionOrder.getRD_NUM());
	            			ybProductionOrder.setField1(productionOrder.getFIELD1());
	            			ybProductionOrder.setField2(productionOrder.getFIELD2());
	            			ybProductionOrder.setField3(productionOrder.getFIELD3());
	            			ybProductionOrder.setField4(productionOrder.getFIELD4());
	            			ybProductionOrder.setField5(productionOrder.getFIELD5());


	            			MachineCapacityInfo machineCapacityInfo = machineCapacityInfoService.getMachineCapacityInfo(ybModel.getConductionType(), ybModel.getSpecs(), ybModel.getDopant());
	            			ybProductionOrder.setMachineCapacityId(machineCapacityInfo.getId());

	            			ybProductionOrder.setCreateDate(new Date());
	            			ybProductionOrderService.saveOrUpdate(ybProductionOrder);


	                    	isExist = true;
	                    }

	                    if(!isExist) {
	                    	soapData.setResult(1);
	                        soapData.setTID(productionOrder.getTID());
	                        soapData.setErrorDesc("订单对应的物料号不存在");
	                        soapDataList.add(soapData);
	                        continue;
	                    }

	                }else{
	                    soapData.setResult(1);
	                    soapData.setTID(productionOrder.getTID());
	                    soapData.setErrorDesc("不是六期需要的数据");
	                    soapDataList.add(soapData);
	                }
                }catch (Exception e) {
                	soapData.setResult(1);
                    soapData.setTID(productionOrder.getTID());
                    soapData.setErrorDesc(e.getMessage());
                    soapDataList.add(soapData);
                    continue;
				}
            }
        }
        return  soapDataList;
    }

    public List<SoapDataStore> setStore(String parameter, String baseKey){
        //Long sTime = System.currentTimeMillis();
        log.info("***收到SAP入库的数据***"+parameter);
        List<SoapDataStore> soapDataList=new ArrayList<>();
//        List<SapStoreLog> list = null;
//        try {
//            list = JSONObject.parseArray(parameter, SapStoreLog.class);
//        } catch (JSONException e) {
//            log.info(e.getMessage());
//            throw  new RuntimeException("Json字符串数据格式错误");
//        }
//        if(list!=null&&list.size()>0){
//            StoreInputBill storeInputBill = new StoreInputBill();
//            StoreOutputBill storeOutputBill = new StoreOutputBill();
//            //入库list
//            List<SapStoreLog> listIn = new ArrayList<>();
//            //出库list
//            List<SapStoreLog> listOut = new ArrayList<>();
//            //物料号列表
//            List<String> materialNumberList = new ArrayList<>();
//            for(SapStoreLog sapStoreLog:list){
//                //311 Z03 301移动类型
//                if(SapStoreStatic.move311.equalsIgnoreCase(sapStoreLog.getBwart())
//                    ||SapStoreStatic.moveZ03.equalsIgnoreCase(sapStoreLog.getBwart())
//                        ||SapStoreStatic.move301.equalsIgnoreCase(sapStoreLog.getBwart())){
//                    if(SapStoreStatic.move311.equalsIgnoreCase(sapStoreLog.getBwart())){
//                         if("D023".equalsIgnoreCase(sapStoreLog.getLgort())
//                            ||"D024".equalsIgnoreCase(sapStoreLog.getLgort())){
//                             BigDecimal orgMenge = sapStoreLog.getMenge();
//                             sapStoreLog.setMenge(orgMenge.multiply(new BigDecimal(-1)));
//                             listOut.add(sapStoreLog);
//                         }else{
//                             listIn.add(sapStoreLog);
//                         }
//                    }else if(SapStoreStatic.moveZ03.equalsIgnoreCase(sapStoreLog.getBwart())){
//                        listIn.add(sapStoreLog);
//                    }else if(SapStoreStatic.move301.equalsIgnoreCase(sapStoreLog.getBwart())){
//                        listIn.add(sapStoreLog);
//                    }
//                }
//                //312 Z04 302 移动类型 出库
//                if(SapStoreStatic.move312.equalsIgnoreCase(sapStoreLog.getBwart())
//                        ||SapStoreStatic.moveZ04.equalsIgnoreCase(sapStoreLog.getBwart())
//                         ||SapStoreStatic.move302.equalsIgnoreCase(sapStoreLog.getBwart())){
//                    BigDecimal orgMenge = sapStoreLog.getMenge();
//                    sapStoreLog.setMenge(orgMenge.multiply(new BigDecimal(-1)));
//                    listOut.add(sapStoreLog);
//                }
////                if(sapStoreLog.getMenge().compareTo(new BigDecimal(0))<0){
////                    listOut.add(sapStoreLog);
////                }else if(sapStoreLog.getMenge().compareTo(new BigDecimal(0))>0){
////                    listIn.add(sapStoreLog);
////                }
//                if(org.apache.commons.lang3.StringUtils.isNotBlank(sapStoreLog.getMatnr())){
//                    materialNumberList.add(sapStoreLog.getMatnr());
//                }
//            }
//            //物料模型列表
//            List<FactoryMaterialModel> factoryMaterialModelList = new ArrayList<>();
//            if(materialNumberList.size()>0){
//                factoryMaterialModelList = factoryMaterialModelDao.findByCodeIn(materialNumberList);
//            }
//
//            //生成入库单
//            Integer inputBillId = 0;
//            if(listIn.size()>0){
//                //入库单主表
//                storeInputBill.setCreateUserId(SapStoreStatic.sapUserId);
//                storeInputBill.setCreateUserName(SapStoreStatic.sapUserName);
//                storeInputBill.setInputTypeDictId(SapStoreStatic.inputTypeDictId);
//                storeInputBill.setInputTypeDictName(SapStoreStatic.inputTypeDictName);
//                storeInputBill.setCreateTime(new Date());
//                Integer inputBillCount = storeInputBillMapper.countByToday();
//                storeInputBill.setCode("RK" + DateUtil.formatDate(new Date(), "yyyyMMddHHmmss") + String.format("%04d", inputBillCount + 1));
//                storeInputBillMapper.insert(storeInputBill);
//                inputBillId= storeInputBill.getId();
//            }
//            //生成出库单
//            Integer outputBillId = 0;
//            List<SapStoreLog> successList = new ArrayList<>();
//            for(SapStoreLog sapStoreLog:list){
//                sapStoreLog.setCteateTime(new Date());
//                SoapDataStore soapDataStore =new SoapDataStore();
//                if (WebServiceApiName.MesId.equals(sapStoreLog.getWerks())
//                   ||WebServiceApiName.MesIdFive.equals(sapStoreLog.getWerks())){
//                    try{
//
//                        //Integer i = 1/0;
//                        //物料号
//                        String materialNumber = "";
//                        if(org.apache.commons.lang3.StringUtils.isBlank(sapStoreLog.getMatnr())){
//                            soapDataStore.setResult(1);
//                            soapDataStore.setTorrNumber(sapStoreLog.getMatnr());
//                            soapDataStore.setErrorDesc("物料号为空");
//                            soapDataList.add(soapDataStore);
//                            continue;
//                        }
//                        materialNumber = sapStoreLog.getMatnr();
//                        //根据物料号、物料凭证去重
//                        List<SapStoreLog> sapStoreLogCheckList = sapStoreLogMapper.selectByMatnrAndMblnr(materialNumber,sapStoreLog.getMblnr());
//                        if(sapStoreLogCheckList!=null&&sapStoreLogCheckList.size()>=1){
//                            soapDataStore.setResult(0);
//                            soapDataStore.setTorrNumber(sapStoreLog.getMatnr());
//                            soapDataList.add(soapDataStore);
//                            continue;
//                        }
//                        //MES库位id
//                        String lgort = "";
//                        if(SapStoreStatic.move311.equalsIgnoreCase(sapStoreLog.getBwart())){
//                            if("D023".equalsIgnoreCase(sapStoreLog.getLgort())
//                                    ||"D024".equalsIgnoreCase(sapStoreLog.getLgort())){
//                                lgort = sapStoreLog.getLgort();
//                            }else{
//                                lgort = sapStoreLog.getUmlgo();
//                            }
//                        }else if(SapStoreStatic.move301.equalsIgnoreCase(sapStoreLog.getBwart())){
//                            lgort = sapStoreLog.getUmlgo();
//                        }
//                        else if(SapStoreStatic.move312.equalsIgnoreCase(sapStoreLog.getBwart())){
//                            lgort = sapStoreLog.getLgort();
//                        }else if(SapStoreStatic.move302.equalsIgnoreCase(sapStoreLog.getBwart())){
//                            lgort = sapStoreLog.getUmlgo();
//                        }
//
//                        Integer locationId = 14;
//                        if(SapStoreStatic.materialLocalName.equals(lgort)){
//                            locationId = SapStoreStatic.materialLocalId;
//                        }else if(SapStoreStatic.mainLocalName.equals(lgort)){
//                            locationId = SapStoreStatic.mainLocalId;
//                        }else{
//                            locationId = SapStoreStatic.otherLocalId;
//                        }
//                        //模型ID
//                        Integer materialId = 0;
//                        FactoryMaterialModel factoryMaterialModel =
//                                factoryMaterialModelList.stream().filter(o->o.getCode().equalsIgnoreCase(sapStoreLog.getMatnr()))
//                                        .findAny().orElse(null);
//                        if(factoryMaterialModel==null){
//                            soapDataStore.setResult(1);
//                            soapDataStore.setTorrNumber(sapStoreLog.getMatnr());
//                            soapDataStore.setErrorDesc("找不到该料号的物料模型id");
//                            soapDataList.add(soapDataStore);
//                            continue;
//                        }
//                        materialId = factoryMaterialModel.getId();
//                        if(sapStoreLog.getMenge().compareTo(new BigDecimal(0))==0){
//                            soapDataStore.setResult(0);
//                            soapDataStore.setTorrNumber(sapStoreLog.getMatnr());
//                            soapDataList.add(soapDataStore);
//                            successList.add(sapStoreLog);
//                        }else if(sapStoreLog.getMenge().compareTo(new BigDecimal(0))>0){
//                            if(inputBillId==0){
//                                soapDataStore.setResult(1);
//                                soapDataStore.setTorrNumber(sapStoreLog.getMatnr());
//                                soapDataStore.setErrorDesc("入库单主表生成错误");
//                                soapDataList.add(soapDataStore);
//                                continue;
//                            }
//                            //入库明细处理
//                            StoreInputItem storeInputItem = new StoreInputItem();
//                            storeInputItem.setCount(sapStoreLog.getMenge());//数量
//                            storeInputItem.setGoodsCode(materialNumber);//料号  物品条码
//                            storeInputItem.setGoodsNo(sapStoreLog.getMblnr()); //物料凭证 批次号
//                            storeInputItem.setRemark(sapStoreLog.getMaktx()); //物料描述 备注
//                            storeInputItem.setStoreInputBillId(inputBillId); //主表id
//                            storeInputItem.setLocationId(locationId);//MES库位id
//                            storeInputItem.setMaterialModelId(materialId); //MES物料模型id
//                            storeInputItemMapper.insert(storeInputItem);
//                            //入库加库存
//                            //根据物料号 库位信息查询 库存信息
//                            List<StoreInventoryDetail> storeInventoryDetailList = storeInventoryDetailMapper.selectByGoodsCodeAndStoreLocationId(materialNumber,locationId);
//                            if(storeInventoryDetailList==null||storeInventoryDetailList.size()==0){
//                                StoreInventoryDetail storeInventoryDetail = new StoreInventoryDetail();
//                                storeInventoryDetail.setCount(sapStoreLog.getMenge()); //数量
//                                storeInventoryDetail.setGoodsCode(materialNumber); //料号  物品条码
//                                storeInventoryDetail.setCreateTime(new Date()); //创建时间
//                                storeInventoryDetail.setMaterialModelId(materialId);//物料号id
//                                storeInventoryDetail.setStoreLocationId(locationId);//库位id
//                                storeInventoryDetailMapper.insert(storeInventoryDetail);
//                            }else{
//                                StoreInventoryDetail storeInventoryDetail = storeInventoryDetailList.get(0);
//                                BigDecimal orgCount = storeInventoryDetail.getCount();
//                                storeInventoryDetail.setCount(orgCount.add(sapStoreLog.getMenge()));
//                                storeInventoryDetailMapper.updateByPrimaryKey(storeInventoryDetail);
//                            }
//                            soapDataStore.setResult(0);
//                            soapDataStore.setTorrNumber(sapStoreLog.getMatnr());
//                            soapDataList.add(soapDataStore);
//                            successList.add(sapStoreLog);
//                        }else if(sapStoreLog.getMenge().compareTo(new BigDecimal(0))<0){
//                            //根据物料号 库位信息查询 库存信息
//                            List<StoreInventoryDetail> storeInventoryDetailList = storeInventoryDetailMapper.selectByGoodsCodeAndStoreLocationId(materialNumber,locationId);
//                            if(storeInventoryDetailList==null||storeInventoryDetailList.size()==0){
//                                soapDataStore.setResult(1);
//                                soapDataStore.setTorrNumber(sapStoreLog.getMatnr());
//                                soapDataStore.setErrorDesc(sapStoreLog.getMatnr()+"库存不存在,库位id="+locationId.toString());
//                                soapDataList.add(soapDataStore);
//                                continue;
//                            }
//                            StoreInventoryDetail storeInventoryDetail = storeInventoryDetailList.get(0);
//                            BigDecimal storeCount = storeInventoryDetail.getCount();
//                            BigDecimal outCount = sapStoreLog.getMenge().multiply(new BigDecimal(-1));
//                            if(storeCount.compareTo(outCount)<0){
//                                soapDataStore.setResult(1);
//                                soapDataStore.setTorrNumber(sapStoreLog.getMatnr());
//                                soapDataStore.setErrorDesc(sapStoreLog.getMatnr()+"库存不足,库位id="+locationId.toString());
//                                soapDataList.add(soapDataStore);
//                                continue;
//                            }
//                            //判断是否已生成入库单
//                            if(outputBillId==0){
//                                storeOutputBill.setCreateTime(new Date());
//                                storeOutputBill.setCreateUserId(SapStoreStatic.sapUserId);
//                                storeOutputBill.setCreateUserName(SapStoreStatic.sapUserName);
//                                storeOutputBill.setOutputTypeDictId(SapStoreStatic.outputTypeDictId);
//                                storeOutputBill.setOutputTypeDictName(SapStoreStatic.outputTypeDictName);
//                                Integer outputBillCount =storeOutputBillMapper.countByToday();
//                                storeOutputBill.setCode("CK"+ DateUtil.formatDate(new Date(),"yyyyMMddHHmmss")+ String.format("%04d",outputBillCount+1));
//                                storeOutputBillMapper.insert(storeOutputBill);
//                                outputBillId = storeOutputBill.getId();
//                            }
//                            //出库明细处理
//                            StoreOutputItem storeOutputItem = new StoreOutputItem();
//                            storeOutputItem.setCount(outCount); //数量
//                            storeOutputItem.setGoodsCode(materialNumber); //料号
//                            storeOutputItem.setProperties(SapStoreStatic.whereabouts); //去向
//                            storeOutputItem.setRemark(sapStoreLog.getMblnr());//备注 //物料凭证
//                            storeOutputItem.setMaterialModelId(materialId);//物料模型ID
//                            storeOutputItem.setStoreLocationId(locationId);//MES库位ID
//                            if(outputBillId==0){
//                                soapDataStore.setResult(1);
//                                soapDataStore.setTorrNumber(sapStoreLog.getMatnr());
//                                soapDataStore.setErrorDesc(sapStoreLog.getMatnr()+"物料号出库申请单生成错误");
//                                soapDataList.add(soapDataStore);
//                                continue;
//                            }
//                            storeOutputItem.setStoreOutputBillId(outputBillId);
//                            storeOutputItemMapper.insert(storeOutputItem);
//                            //出库减库存
//                            if(storeCount.compareTo(outCount)==0){
//                                //数量正好  删除库存记录
//                                storeInventoryDetailMapper.deleteByPrimaryKey(storeInventoryDetail.getId());
//                            }else{
//                                //可以出库 减去库存
//                                BigDecimal orgCount = storeInventoryDetail.getCount();
//                                storeInventoryDetail.setCount(orgCount.subtract(outCount));
//                                storeInventoryDetailMapper.updateByPrimaryKey(storeInventoryDetail);
//                            }
//                            soapDataStore.setResult(0);
//                            soapDataStore.setTorrNumber(sapStoreLog.getMatnr());
//                            soapDataList.add(soapDataStore);
//                            successList.add(sapStoreLog);
//                        }
//                    }catch (Exception e){
//                        soapDataStore.setResult(1);
//                        soapDataStore.setTorrNumber(sapStoreLog.getMatnr());
//                        soapDataStore.setErrorDesc(e.getMessage());
//                        e.printStackTrace();
//                        soapDataList.add(soapDataStore);
//                    }
//                }else{
//                    soapDataStore.setResult(1);
//                    soapDataStore.setTorrNumber(sapStoreLog.getMatnr());
//                    soapDataStore.setErrorDesc("不是三期需要的数据");
//                    soapDataList.add(soapDataStore);
//                }
//            }
//            SapStoreRequestLog sapStoreRequestLog = new SapStoreRequestLog();
//            sapStoreRequestLog.setBskey(baseKey);
//            sapStoreRequestLog.setContent(parameter);
//            sapStoreRequestLog.setCreateTime(new Date());
//            sapStoreRequestLog.setErrorMessage(JSONObject.toJSON(soapDataList).toString());
//            Long time = System.currentTimeMillis() - sTime;
//            sapStoreRequestLog.setCode(time.toString());
//            sapStoreRequestLogMapper.insert(sapStoreRequestLog);
//            for(SapStoreLog sapStoreLog:successList){
//                sapStoreLog.setRequestId(sapStoreRequestLog.getId());
//            }
//            if(successList!=null&&successList.size()>0){
//                sapStoreLogMapper.insertList(successList);
//            }
//
//        }
        return soapDataList;
    }




}
