package com.uas.eis.serviceImpl;

import com.uas.eis.core.config.SpObserver;
import com.uas.eis.dao.BaseDao;
import com.uas.eis.dao.SqlRowList;
import com.uas.eis.entity.ErrorMessage;
import com.uas.eis.entity.HelperType;
import com.uas.eis.exception.ApiSystemException;
import com.uas.eis.sdk.entity.ApiResult;
import com.uas.eis.service.MESDataService;
import com.uas.eis.service.MESHelperService;
import com.uas.eis.utils.*;
import flexjson.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.commons.lang.StringUtils;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jackson.JsonObjectDeserializer;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import sun.awt.TimedWindowEvent;

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

import org.dom4j.DocumentHelper;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.InputSource;
import java.io.StringReader;

@Service
public class MESHelperServiceImpl implements MESHelperService {

	@Autowired
	private BaseDao baseDao;

	@Value("${spring.datasource.username}")
	private String username;

	@Override
	public Map<Object,Object> Radium(String data) {
		Map<String, Object> map=null;
		Map<Object, Object> rmap = new HashMap<Object, Object>();
		String oErrMessage="";
		String UserName="";
		try{
			map =BaseUtil.convertJsonToMap(data);
		}catch (Exception e){
			System.out.printf(e.getMessage()) ;
		}
		if(map.get("SN")==null){
			rmap.put("code",-1);
			rmap.put("message","SN号不能为空");
			return rmap;
		}
		if(map.get("MO")==null){
			rmap.put("code",-1);
			rmap.put("message","工单号不能为空");
			return rmap;
		}
		if(map.get("SpecificationName")==null){
			rmap.put("code",-1);
			rmap.put("message","工序不能为空");
			return rmap;
		}
		if(map.get("UserName")==null){
			rmap.put("code",-1);
			rmap.put("message","用户不能为空");
			return rmap;
		}
		String specificationName=map.get("SpecificationName").toString();
		String MO=map.get("MO").toString();

		Map<Object,Object> map1=BaseUtil.parseFormStoreToMap(map.get("SN").toString());
		for (Map.Entry<Object, Object> entry : map1.entrySet()) {
			Object key = entry.getKey();
			Object value = entry.getValue();
			SqlRowList rs=baseDao.queryForRowSet("select 1 from makesnlist where msl_sncode='"+value.toString().toUpperCase()+"'" +
					" and msl_makecode='"+MO+"' and msl_Radium=-1");
			if(rs.next()){
				oErrMessage+="序列号"+value.toString().toUpperCase()+"已镭雕,";

			}else {
				baseDao.execute("update makesnlist set msl_Radium=-1,msl_zone='"+StringUtil.nvl(key,"").replace("sn","").replace("SN","")+"' where msl_sncode='"+value.toString().toUpperCase()+"' and " +
						"msl_makecode='"+MO+"'");
			}
			//启用过站
			if(baseDao.getFieldDataByCondition("configs","data","caller='MESSetting' and code='Radium'").toString().equals("1")){
				oErrMessage+=GoMo(value.toString().toUpperCase(),MO, specificationName);
				if(oErrMessage.equals("null")){
					oErrMessage="";
				}else{
					rmap.put("code",-1);
					rmap.put("message",oErrMessage);
					return rmap;
				}
				oErrMessage+=CheckRoutePassed(value.toString().toUpperCase(),specificationName);
				if(oErrMessage.equals("null")){
					oErrMessage="";
				}else{
					rmap.put("code",-1);
					rmap.put("message",oErrMessage);
					return rmap;
				}
				oErrMessage+=SetPcbaData(value.toString().toUpperCase(),specificationName,UserName,"OK");
				if(oErrMessage.equals("null")){
					oErrMessage="";
				}else{
					rmap.put("code",-1);
					rmap.put("message",oErrMessage);
					return rmap;
				}
			}
		}
		if(oErrMessage.equals("")||oErrMessage==null){
			rmap.put("code",0);
			rmap.put("message","镭射识别绑定成功");
			return rmap;
		}else{
			rmap.put("code",-1);
			rmap.put("message",oErrMessage);
			return rmap;
		}
	}


	@Override
	public Map<Object,Object> SPI(String data) {
		Map<Object, Object> rmap = new HashMap<Object, Object>();
		try{
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			try	{
				try{
					Element root;
					NodeList books;
					Document document = builder.parse(new InputSource(new StringReader(data)));
					root = document.getDocumentElement();
					books = root.getChildNodes();
					String Username="";
					String Shiftname="";
					String MachineNO="";
					String LineNO="";
					String procedure="";
					String Moname="";
					String Lotsn="";
					String Side="";
					String Result="";
					String Defect="";
					String elementQTY="";
					String TestQTY="";
					String Time="";
					for (Node node = books.item(1).getFirstChild(); node != null; node = node.getNextSibling()) {
						{
							if (node.getNodeName().equals("UpdAOISPIRecord")) {
								NodeList books1 = node.getChildNodes();
								for (int i = 0; i < books1.getLength(); i++) {
									Node node1 = books1.item(i);
									if(!node1.getNodeName().equals("#text")){
										switch (node1.getNodeName()){
											case "Username":{
												Username=node1.getTextContent();
												break;
											}
											case "Shiftname":{
												Shiftname=node1.getTextContent();
												break;
											}
											case "MachineNO":{
												MachineNO=node1.getTextContent();												break;
											}
											case "LineNO":{
												LineNO=node1.getTextContent();
												break;
											}
											case "procedure":
												procedure=node1.getTextContent();
												break;
											case "Moname":
												Moname=node1.getTextContent();
												break;
											case "Lotsn":
												Lotsn=node1.getTextContent();
												break;
											case "Side":
												Side=node1.getTextContent();
												break;
											case "Result":
												Result=node1.getTextContent();
												break;
											case "Defect":
												Defect=node1.getTextContent();
												break;
											case "elementQTY":
												elementQTY=node1.getTextContent();
												break;
											case "TestQTY":
												TestQTY=node1.getTextContent();
												break;
											case "Time":
												Time=node1.getTextContent();
												break;
											default:
												break;
										}
										//System.out.printf("名称:"+node1.getNodeName());
										//System.out.printf("值:"+node1.getTextContent());
										//System.out.printf("类型:"+node1.getNodeType());
									}
								}
							}
						}
					}
					Time=Time.substring(0,19).replaceAll("T"," ");
					baseDao.execute("insert into devicetestinfo(DTI_ID, DTI_SNCODE, DTI_USERNAME, DTI_MACHINE, DTI_LINECODE, DTI_RESULT, DTI_MAKECODE, DTI_SHIFTNAME, DTI_PROGRAM, DTI_DEFECT, " +
							"DTI_TESTQTY, DTI_MACHINETYPE, DTI_TYPE, DTI_TIME, DTI_SOURCECONTENT,dti_elementQTY)values(devicetestinfo_seq.nextval,'"+Lotsn+"','"+Username+"','"+MachineNO+"','"+LineNO+"','"+Result+"'" +
							",'"+Moname+"','"+Shiftname+"','"+procedure+"','"+Defect+"','"+TestQTY+"','SPI','SPI',to_date('"+Time+"','yyyy-mm-dd hh24:mi:ss'),'','"+elementQTY+"')");
				}catch (IOException e){
					System.out.printf(e.getMessage());
				}
			}
			catch (SAXException e){

			}
		}catch (ParserConfigurationException e){

		}
		return rmap;
	}

	@Override
	public String AOI(String Username,String Shiftname, String MachineNO, String LineNO, String procedure,String Moname, String Lotsn,String Side,String Result,String Defect,String elementQTY,String TestQTY,String Type,String Time) {
		baseDao.execute("insert into devicetestinfo(DTI_ID, DTI_SNCODE, DTI_USERNAME, DTI_MACHINE, DTI_LINECODE, DTI_RESULT, DTI_MAKECODE, DTI_SHIFTNAME, DTI_PROGRAM, DTI_DEFECT, " +
				"DTI_TESTQTY, DTI_MACHINETYPE, DTI_TYPE, DTI_TIME, DTI_SOURCECONTENT,dti_elementQTY)values(devicetestinfo_seq.nextval,'"+Lotsn+"','"+Username+"','"+MachineNO+"','"+LineNO+"','"+Result+"'" +
				",'"+Moname+"','"+Shiftname+"','"+procedure+"','"+Defect+"','"+TestQTY+"','"+Type+"','AOI',to_date('"+Time+"','yyyy-mm-dd hh24:mi:ss'),'','"+elementQTY+"')");
		return "";
	}

	@Override
	public String  UploadSteel(String SteelMeshCode,String scraperCode, String SteelMeshCount, String scraperCount, String datatime) {
		String err = CheckSteel(SteelMeshCode);
		//判断钢网编号
		if(SteelMeshCode!=null&&!"".equals(SteelMeshCode)){
			baseDao.execute("insert into devicetestinfo(DTI_ID, DTI_SNCODE,DTI_TESTQTY, DTI_MACHINETYPE, DTI_TYPE, DTI_TIME, DTI_SOURCECONTENT)values(devicetestinfo_seq.nextval,'"+scraperCode+"','"+scraperCount+"','钢网','钢网',to_date('"+datatime+"','yyyy-mm-dd hh24:mi:ss'),'')");
			baseDao.execute("update stencil set  st_usecount=nvl(st_usecount,0)+"+scraperCount +" where st_code='"+SteelMeshCode+"'");
		}
		//判断刮刀编号
		if(scraperCode!=null&&!"".equals(scraperCode)){
			baseDao.execute("insert into devicetestinfo(DTI_ID, DTI_SNCODE,DTI_TESTQTY, DTI_MACHINETYPE, DTI_TYPE, DTI_TIME, DTI_SOURCECONTENT)values(devicetestinfo_seq.nextval,'"+scraperCode+"','"+scraperCount+"','刮刀','刮刀',to_date('"+datatime+"','yyyy-mm-dd hh24:mi:ss'),'')");
			baseDao.execute("update stencil set  st_usecount=nvl(st_usecount,0)+"+scraperCount +" where st_code='"+scraperCode+"'");
		}
		return err;
	}

	@Override
	public String CheckSteel(String SteelMeshCode) {
		Map<Object, Object> rmap = new HashMap<Object, Object>();
		SqlRowList rs=baseDao.queryForRowSet("select st_kind,nvl(st_usecount,0)st_usecount,nvl(st_maxusecount,0)st_maxusecount from stencil where st_code='"+SteelMeshCode+"'");
		if(rs.next()){
			String st_usecount=rs.getString("st_usecount");
			String st_maxusecount=rs.getString("st_maxusecount");
			String st_kind=rs.getString("st_kind");
			if(Integer.parseInt(st_usecount)>=Integer.parseInt(st_maxusecount)){
				return rs.getString("st_kind")+"已使用"+st_usecount+",超出最大使用次数"+st_maxusecount;
			}
		}else{
			return "编号不存在";
		}
		return "";
	}

	@Override
	public Map<Object,Object> SetupResultDataInterface(String data) {
		Map<Object, Object> rmap = new HashMap<Object, Object>();

		JSONObject object = JSONObject.fromObject(data);
		Object object1 = object.get("data");
		JSONObject obj = JSONObject.fromObject(object1);
		JSONObject SetupResultDetail=obj.getJSONObject("SetupResultDetail");
		if(SetupResultDetail!=null){
			String ActionType=SetupResultDetail.get("ActionType").toString();
			String MessageSendTime=Time(SetupResultDetail.getString("MessageSendTime"));
			String LineName=SetupResultDetail.get("LineName").toString();
			String MachineName=SetupResultDetail.get("MachineName").toString();
			String OrderNumber=SetupResultDetail.get("OrderNumber").toString();
			String DockingStationID=SetupResultDetail.get("DockingStationID").toString();
			String Operator=SetupResultDetail.get("Operator").toString();
			String TableLocation=SetupResultDetail.get("TableLocation").toString();
			String TableId=SetupResultDetail.get("TableId").toString();
			String Track=SetupResultDetail.get("Track").toString();
			String FeederTypeName=SetupResultDetail.get("FeederTypeName").toString();
			String FeederID=SetupResultDetail.get("FeederID").toString();
			JSONObject PackagingUnitDetail=SetupResultDetail.getJSONObject("PackagingUnit");
			if(PackagingUnitDetail!=null){
				String PUID=PackagingUnitDetail.getString("PUID");
				String ComponentBarcode=PackagingUnitDetail.getString("ComponentBarcode");
				String OriginalQuantity=PackagingUnitDetail.getString("OriginalQuantity");
				String Quantity=PackagingUnitDetail.getString("Quantity");
				String CreateDate=Time(PackagingUnitDetail.getString("CreateDate"));
				String DateCode=PackagingUnitDetail.getString("DateCode");
				String BatchId=PackagingUnitDetail.getString("BatchId");
				String MsdLevel=PackagingUnitDetail.getString("MsdLevel");
				JSONObject LockInfoList=null;
				try{
					LockInfoList=PackagingUnitDetail.getJSONObject("LockInfoList");
				}catch (Exception e){

				}
				JSONObject SplicedPackagingUnitList=null;
				try{
					SplicedPackagingUnitList=PackagingUnitDetail.getJSONObject("SplicedPackagingUnitList");
				}catch (Exception e){

				}
				int sr_id=baseDao.getSeqId("SETUPRESULTDETAIL_seq");
				baseDao.execute("insert into SETUPRESULTDETAIL(sr_id,ACTIONTYPE,LINENAME,ORDERNUMBER,MACHINENAME," +
						"TABLEID,DOCKINGSTATIONID,OPERATOR,TableLocation,FeederTypeName,FeederID,MessageSendTime)values('"+sr_id+"'," +
						"'"+ActionType+"','"+LineName+"','"+OrderNumber+"','"+MachineName+"','"+TableId+"','"+DockingStationID+"'," +
						"'"+Operator+"','"+TableLocation+"','"+FeederTypeName+"','"+FeederID+"',to_date('"+MessageSendTime+"','yyyy-mm-dd hh24:mi:ss'))");
				int pu_id=baseDao.getSeqId("PACKAGINGUNIT_seq");
				baseDao.execute("insert into PACKAGINGUNIT(PU_ID,PU_SRID,ComponentBarcode,OriginalQuantity,Quantity,CreateDate," +
						"DateCode,BatchId,MsdLevel)values('"+pu_id+"','"+sr_id+"','"+ComponentBarcode+"','"+OriginalQuantity+"','"+Quantity+"',to_date('"+CreateDate+"','yyyy-mm-dd hh24:mi:ss')," +
						"'"+DateCode+"','"+BatchId+"','"+MsdLevel+"')");
				if(LockInfoList!=null){
					JSONArray LockInfoItem=LockInfoList.getJSONArray("LockInfoItem");
					for(int i=0;i<LockInfoItem.size();i++){
						JSONObject map=LockInfoItem.getJSONObject(i);
						String Date=Time(map.getString("Date"));
						String Message=map.getString("Message");
						String Reason=map.getString("Reason");
						String Source=map.getString("Source");
						baseDao.execute("insert into LOCKINFOLIST(LF_ID,lf_puid,INDATE,MESSAGE,REASON,SOURCE)" +
								"values(LOCKINFOLIST_seq.nextval,'"+pu_id+"',to_date('"+Date+"','yyyy-mm-dd hh24:mi:ss'),'"+Message+"'," +
								"'"+Reason+"','"+Source+"')");
					}
				}
				if(SplicedPackagingUnitList!=null){
					JSONArray SplicedPackagingUnitItem=SplicedPackagingUnitList.getJSONArray("SplicedPackagingUnitItem");
					for(int i=0;i<SplicedPackagingUnitItem.size();i++){
						JSONObject map=SplicedPackagingUnitItem.getJSONObject(i);
						String UID1=map.getString("PUID");
						String ComponentBarcode1=map.getString("ComponentBarcode");
						String ComponentBarcodeFragment=map.getString("ComponentBarcodeFragment");
						String ComponentName=map.getString("ComponentName");
						String OriginalQuantity1=map.getString("OriginalQuantity");
						String Quantity1=map.getString("Quantity");
						String ManufacturePartNumber=map.getString("ManufacturePartNumber");
						String Manufacturer=map.getString("Manufacturer");
						String Supplier=map.getString("Supplier");
						baseDao.execute("insert into SPLICEDPACKAGING (SP_ID,SP_PUID,PUID,COMPONENTBARCODE,ORIGINALQUANTITY,QUANTITY)" +
								"values(SPLICEDPACKAGING_seq.nextval,'"+pu_id+"','"+UID1+"','"+ComponentBarcode1+"','"+OriginalQuantity1+"','"+Quantity1+"')");
					}
				}
			}
			rmap.put("code","0");
			rmap.put("result","OK");
			rmap.put("ServerMessage","MES:贴片机数据记录成功");
		}
		return rmap;
	}

	@Override
	public Map<Object,Object> StateEventDetail(String data) {
		Map<Object, Object> rmap = new HashMap<Object, Object>();
		JSONObject object = JSONObject.fromObject(data);
		Object object1 = object.get("data");
		JSONObject obj = JSONObject.fromObject(object1);
		JSONObject StateEventDetail=obj.getJSONObject("StateEventDetail");
		if(StateEventDetail!=null){
			int st_id=baseDao.getSeqId("StateEventDetail_seq");
			String MessageSendTime=Time(StateEventDetail.getString("MessageSendTime"));
			String CompletionStatusType=StateEventDetail.getString("CompletionStatusType");
			String LineFullPath=StateEventDetail.getString("LineFullPath");
			String LineName=StateEventDetail.getString("LineName");
			String MachineFullPath=StateEventDetail.getString("MachineFullPath");
			String MachineName=StateEventDetail.getString("MachineName");
			String JobFullPath=StateEventDetail.getString("JobFullPath");
			String JobName=StateEventDetail.getString("JobName");
			String RecipeFullPath=StateEventDetail.getString("RecipeFullPath");
			String RecipeName=StateEventDetail.getString("RecipeName");
			String SetupFullPath=StateEventDetail.getString("SetupFullPath");
			String SetupName=StateEventDetail.getString("SetupName");
			String BoardFullPath=StateEventDetail.getString("BoardFullPath");
			String BoardName=StateEventDetail.getString("BoardName");
			String OrderNumber=StateEventDetail.getString("OrderNumber");
			String ConveyorMode=StateEventDetail.getString("ConveyorMode");
			String DownloadMode=StateEventDetail.getString("DownloadMode");
			String FactoryLayoutPath=StateEventDetail.getString("FactoryLayoutPath");
			String MachineId=StateEventDetail.getString("MachineId");
			String MachineType=StateEventDetail.getString("MachineType");
			String TypeName=StateEventDetail.getString("TypeName");
			String ProcessingAreaCount=StateEventDetail.getString("ProcessingAreaCount");
			String StationSoftwareVersion=StateEventDetail.getString("StationSoftwareVersion");
			String MonitoringServiceVersion=StateEventDetail.getString("MonitoringServiceVersion");
			String ComputerAddress=StateEventDetail.getString("ComputerAddress");
			baseDao.execute("insert into StateEventDetail(ST_ID, MESSAGESENDTIME, COMPLETIONSTATUSTYPE, LINEFULLPATH, LINENAME, MACHINEFULLPATH, MACHINENAME, JOBFULLPATH, JOBNAME, RECIPEFULLPATH, RECIPENAME, SETUPFULLPATH, SETUPNAME, BOARDFULLPATH, BOARDNAME, ORDERNUMBER, CONVEYORMODE, DOWNLOADMODE, FACTORYLAYOUTPATH, MACHINEID, MACHINETYPE, TYPENAME, PROCESSINGAREACOUNT, STATIONSOFTWAREVERSION, MONITORINGSERVICEVERSION, COMPUTERADDRESS)" +
					"values("+st_id+", to_date('"+MessageSendTime+"','yyyy-mm-dd hh24:mi:ss'), '"+CompletionStatusType+"', '"+LineFullPath+"', '"+LineName+"', '"+MachineFullPath+"', '"+MachineName+"', '"+JobFullPath+"', '"+JobName+"', '"+RecipeFullPath+"', '"+RecipeName+"', '"+SetupFullPath+"', '"+SetupName+"', '"+BoardFullPath+"', '"+BoardName+"', '"+OrderNumber+"', '"+ConveyorMode+"', '"+DownloadMode+"', '"+FactoryLayoutPath+"', '"+MachineId+"', '"+MachineType+"', '"+TypeName+"', '"+ProcessingAreaCount+"', '"+StationSoftwareVersion+"', '"+MonitoringServiceVersion+"', '"+ComputerAddress+"')");
			JSONArray ProcessingAreaStateList=StateEventDetail.getJSONArray("ProcessingAreaStateList");
			for (int i=0;i<ProcessingAreaStateList.size();i++){
				JSONObject map1=ProcessingAreaStateList.getJSONObject(i);
				String ProcessingArea=map1.getString("ProcessingArea");
				String Conveyor=map1.getString("Conveyor");
				String CurrentStateBegin=map1.getString("CurrentStateBegin");
				String CurrentStateCode=map1.getString("CurrentStateCode");
				String CurrentStateDescription=map1.getString("CurrentStateDescription");
				String PreviousStateCode=map1.getString("PreviousStateCode");
				String PreviousStateDescription=map1.getString("PreviousStateDescription");
				baseDao.execute("insert into ProcessingAreaStateList(RAS_ID, RAS_STID, PROCESSINGAREA, CONVEYOR, CURRENTSTATEBEGIN, CURRENTSTATECODE, CURRENTSTATEDESCRIPTION, PREVIOUSSTATECODE, PREVIOUSSTATEDESCRIPTION)" +
						"values(ProcessingAreaStateList_seq.nextval,'"+st_id+"','"+ProcessingArea+"','"+Conveyor+"','"+CurrentStateBegin+"'," +
						"'"+CurrentStateCode+"','"+CurrentStateDescription+"','"+PreviousStateCode+"','"+PreviousStateDescription+"')");
			}
		}
		rmap.put("code","0");
		rmap.put("result","OK");
		rmap.put("ServerMessage","MES:贴片机数据记录成功");
		return rmap;
	}

	@Override
	public Map<Object,Object> SendPlaceData(String data) {
		Map<Object, Object> rmap = new HashMap<Object, Object>();
		JSONObject object = JSONObject.fromObject(data);
		Object object1 = object.get("data");
		JSONObject obj = JSONObject.fromObject(object1);
		JSONObject PlacedDataDetail=obj.getJSONObject("PlacedDataDetail");
		if(PlacedDataDetail!=null){
			int pd_id=baseDao.getSeqId("PlacedDataDetail_seq");
			String MESSAGESENDTIME=Time(PlacedDataDetail.getString("MessageSendTime"));
			String COMPLETIONSTATUSTYPE=PlacedDataDetail.getString("CompletionStatusType");
			String LINEFULLPATH=PlacedDataDetail.getString("LineFullPath");
			String MACHINEFULLPATH=PlacedDataDetail.getString("MachineFullPath");
			String RECIPEFULLPATH=PlacedDataDetail.getString("RecipeFullPath");
			String RECIPENAME=PlacedDataDetail.getString("RecipeName");
			String SETUPFULLPATH=PlacedDataDetail.getString("SetupName");
			String BOARDFULLPATH=PlacedDataDetail.getString("BoardFullPath");
			String FACTORYLAYOUTPATH=PlacedDataDetail.getString("FactoryLayoutPath");
			String MACHINEID=PlacedDataDetail.getString("MachineId");
			String MACHINETYPE=PlacedDataDetail.getString("MachineType");
			String STATIONSOFTWAREVERSION=PlacedDataDetail.getString("StationSoftwareVersion");
			String MONITORINGSERVICEVERSION=PlacedDataDetail.getString("MonitoringServiceVersion");
			String COMPUTERADDRESS=PlacedDataDetail.getString("ComputerAddress");
			baseDao.execute("insert into PlacedDataDetail(pd_id,MessageSendTime,CompletionStatusType,LineFullPath,MachineFullPath,RecipeFullPath," +
					"RecipeName,SETUPFULLPATH,BoardFullPath,FactoryLayoutPath,MachineId,MachineType,StationSoftwareVersion,MonitoringServiceVersion," +
					"ComputerAddress)values('"+pd_id+"',to_date('"+MESSAGESENDTIME+"','yyyy-mm-dd hh24:mi:ss'),'"+COMPLETIONSTATUSTYPE+"'," +
					"'"+LINEFULLPATH+"','"+MACHINEFULLPATH+"','"+RECIPEFULLPATH+"','"+RECIPENAME+"','"+SETUPFULLPATH+"','"+BOARDFULLPATH+"'," +
					"'"+FACTORYLAYOUTPATH+"','"+MACHINEID+"','"+MACHINETYPE+"','"+STATIONSOFTWAREVERSION+"','"+MONITORINGSERVICEVERSION+"','"+COMPUTERADDRESS+"')");
			JSONArray PanelList=PlacedDataDetail.getJSONArray("PlacedComponentList");
			for (int i=0;i<PanelList.size();i++){
				JSONObject map1=PanelList.getJSONObject(i);
				String TABLELOCATION =map1.getString("TableLocation");
				String TRACK=map1.getString("Track");
				String DIVISION=map1.getString("Division");
				String COMPONENTFULLPATH=map1.getString("ComponentFullPath");
				String COMPONENTNAME=map1.getString("ComponentName");
				String COMPONENTSHAPEFULLPATH=map1.getString("ComponentShapeFullPath");
				String FEEDERCATEGORY=map1.getString("FeederCategory");
				String FEEDERTYPENAME=map1.getString("FeederTypeName");
				String FEEDERID=map1.getString("FeederID");
				String ACCESSTOTAL=map1.getString("AccessTotal");
				String PlacedComponents=map1.getString("PlacedComponents");
				String REJECTQTY=map1.getString("RejectQty");
				String REJECTIDENT=map1.getString("RejectIdent");
				String REJECTVACUUM=map1.getString("RejectVacuum");
				String TRACKEMPTY=map1.getString("TrackEmpty");
				String IDENTERRROR=map1.getString("IdentErrror");
				String MATERIALDEFECT=map1.getString("MaterialDefect");
				String ABSENCEAFTERPICK=map1.getString("AbsenceAfterPick");
				String ABSENCEBEFOREPLACEMENT=map1.getString("AbsenceBeforePlacement");
				String TREATMENTERROR=map1.getString("TreatmentError");
				baseDao.execute("insert into PlacedComponentList(pc_id,pc_pdid,TABLELOCATION,TRACK,DIVISION,COMPONENTFULLPATH," +
						"COMPONENTNAME,COMPONENTSHAPEFULLPATH,FEEDERCATEGORY,FEEDERTYPENAME,FEEDERID,ACCESSTOTAL,PlacedComponents," +
						"REJECTQTY,REJECTIDENT,REJECTVACUUM,TRACKEMPTY,IDENTERRROR,MATERIALDEFECT,ABSENCEAFTERPICK,ABSENCEBEFOREPLACEMENT,TREATMENTERROR)" +
						"values(PlacedComponentList_seq.nextval,'"+pd_id+"','"+TABLELOCATION+"','"+TRACK+"','"+DIVISION+"','"+COMPONENTFULLPATH+"'" +
						",'"+COMPONENTNAME+"','"+COMPONENTSHAPEFULLPATH+"','"+FEEDERCATEGORY+"','"+FEEDERTYPENAME+"','"+FEEDERID+"'," +
						"'"+ACCESSTOTAL+"','"+PlacedComponents+"','"+REJECTQTY+"','"+REJECTIDENT+"','"+REJECTVACUUM+"','"+TRACKEMPTY+"'," +
						"'"+IDENTERRROR+"','"+MATERIALDEFECT+"','"+ABSENCEAFTERPICK+"','"+ABSENCEBEFOREPLACEMENT+"','"+TREATMENTERROR+"')");
			}
			JSONArray PickupErrorList=PlacedDataDetail.getJSONArray("PickupErrorList");
			for (int i=0;i<PickupErrorList.size();i++){
				JSONObject map1=PickupErrorList.getJSONObject(i);
				String GANTRY=map1.getString("Gantry");
				String HEAD=map1.getString("Head");
				String SEGMENT1=map1.getString("Segment");
				String NOZZLE=map1.getString("Nozzle");
				String TABLELOCATION=map1.getString("TableLocation");
				String TRACK=map1.getString("Track");
				String DIVISION=map1.getString("Division");
				String TOWER=map1.getString("Tower");
				String LEVEL1=map1.getString("Level");
				String COMPONENTFULLPATH=map1.getString("ComponentFullPath");
				String COMPONENTNAME=map1.getString("ComponentName");
				String COMPONENTSHAPEFULLPATH=map1.getString("ComponentShapeFullPath");
				String COMPONENTSHAPENAME=map1.getString("ComponentShapeName");
				String FEEDERCATEGORY=map1.getString("FeederCategory");
				String FEEDERTYPENAME=map1.getString("FeederTypeName");
				String FEEDERID=map1.getString("FeederID");
				String ERRORTYPE=map1.getString("ErrorType");
				String ERRORDESCRIPTION=map1.getString("ErrorDescription");
				baseDao.execute("insert into PickupErrorList(pe_id,pe_pdid,Gantry,Head,SEGMENT1,NOZZLE,TABLELOCATION,TRACK,DIVISION,TOWER" +
						",LEVEL1,COMPONENTFULLPATH,COMPONENTNAME,COMPONENTSHAPEFULLPATH,COMPONENTSHAPENAME,FEEDERCATEGORY,FEEDERTYPENAME," +
						"FEEDERID,ERRORTYPE,ERRORDESCRIPTION)values(PickupErrorList_seq.nextval,'"+pd_id+"','"+GANTRY+"','"+HEAD+"','"+SEGMENT1+"','"+NOZZLE+"'," +
						"'"+TABLELOCATION+"','"+TRACK+"','"+DIVISION+"','"+TOWER+"','"+LEVEL1+"','"+COMPONENTFULLPATH+"','"+COMPONENTNAME+"'," +
						"'"+COMPONENTSHAPEFULLPATH+"','"+COMPONENTSHAPENAME+"','"+FEEDERCATEGORY+"','"+FEEDERTYPENAME+"','"+FEEDERID+"','"+ERRORTYPE+"'," +
						"'"+ERRORDESCRIPTION+"')");
			}
		}
		rmap.put("code","0");
		rmap.put("result","OK");
		rmap.put("ServerMessage","MES:贴片机数据记录成功");
		return  rmap;
	}

	@Override
	public Map<Object,Object> TraceabilityDataInterface(String data) {
		Integer td_id=baseDao.getSeqId("TRACEDATA_seq");
		Map<Object, Object> rmap = new HashMap<Object, Object>();
		JSONObject object = JSONObject.fromObject(data);
		Object object1 = object.get("data");
		JSONObject obj = JSONObject.fromObject(object1);
		JSONObject TraceabilityDataDetail=obj.getJSONObject("TraceabilityDataDetail");
		if(TraceabilityDataDetail!=null){
			String DateBegin=Time(TraceabilityDataDetail.get("DateBegin").toString());
			String DateCompleted=Time(TraceabilityDataDetail.get("DateCompleted").toString());
			String LineName=TraceabilityDataDetail.get("LineName").toString();
			String MachineName=TraceabilityDataDetail.get("MachineName").toString();
			String BoardName=TraceabilityDataDetail.get("BoardName").toString();
			String MachineID=TraceabilityDataDetail.get("MachineID").toString();
			String BoardSide=TraceabilityDataDetail.get("BoardSide").toString();
			String OrderNumber=TraceabilityDataDetail.get("OrderNumber").toString();
			String PCBBarcode=TraceabilityDataDetail.get("PCBBarcode").toString();
			baseDao.execute("insert into TRACEDATA(TD_ID,DateBegin,DateCompleted,LineName,MachineName,BoardName,MachineID,BoardSide,OrderNumber,PCBBarcode,TD_INDATE)" +
					"values("+td_id+",to_date('"+DateBegin+"','yyyy-mm-dd hh24:mi:ss'),to_date('"+DateCompleted+"','yyyy-mm-dd hh24:mi:ss')," +
					"'"+LineName+"','"+MachineName+"','"+BoardName+"','"+MachineID+"','"+BoardSide+"','"+OrderNumber+"','"+PCBBarcode+"',sysdate)");

			JSONObject MaterialTraceabilityDetail=null;
			try{
				MaterialTraceabilityDetail=TraceabilityDataDetail.getJSONObject("MaterialTraceabilityDetail");
			}catch (Exception e){

			}
			JSONObject MaterialConsumptionDetail=null;
			try{
				MaterialConsumptionDetail=TraceabilityDataDetail.getJSONObject("MaterialConsumptionDetail");
			}catch (Exception e){

			}
			//上料信息
			if(MaterialTraceabilityDetail!=null){
				JSONArray PanelList=MaterialTraceabilityDetail.getJSONArray("PanelList");
				for (int i=0;i<PanelList.size();i++){
					JSONObject map=PanelList.getJSONObject(i);
					String PanelName=map.get("PanelName").toString();
					JSONArray PackagingUnitRefList=map.getJSONArray("PackagingUnitRefList");
					System.out.println(PackagingUnitRefList.size());
					if(PackagingUnitRefList!=null){
						for (int j=0;j<PackagingUnitRefList.size();j++){
							String PlaceRefID="";
							JSONObject map1=PackagingUnitRefList.getJSONObject(j);
							String PUID=map1.getString("PUID");
							String TableLocation=map1.getString("TableLocation");
							String Track=map1.getString("Track");
							String ComponentBarcode=map1.getString("ComponentBarcode");
							String OriginalQuantity=map1.getString("OriginalQuantity");
							String Quantity=map1.getString("Quantity");
							String CreateDate=Time(map1.getString("CreateDate"));
							String DateCode=map1.getString("DateCode");
							String Batch2=map1.getString("Batch2");
							String MsdLevel=map1.getString("MsdLevel");
							String VerifiedDate=Time(map1.getString("VerifiedDate"));
							String Operator=map1.getString("Operator");
							JSONArray PlaceRefList=map1.getJSONArray("PlaceRefList");
							if(PlaceRefList!=null){
								for (int k=0;k<PlaceRefList.size();k++){
									JSONObject map2=PlaceRefList.getJSONObject(k);
									PlaceRefID+=map2.getString("PlaceRefID")+",";
								}
							}
							baseDao.execute("insert into MATERIALTRACE(MT_ID,MT_TDID,PANELNAME,PUID,PlaceRefList,TableLocation,Track,ComponentBarcode,OriginalQuantity,Quantity,CreateDate,DateCode,Batch2,MsdLevel,VerifiedDate,Operator)" +
									"values(MATERIALTRACE_seq.nextval,'"+td_id+"','"+PanelName+"','"+PUID+"','"+PlaceRefID+"','"+TableLocation+"','"+Track+"','"+ComponentBarcode+"','"+OriginalQuantity+"','"+Quantity+"',to_date('"+CreateDate+"','yyyy-mm-dd hh24:mi:ss'),'"+DateCode+"','"+Batch2+"'," +
									"'"+MsdLevel+"',to_date('"+CreateDate+"','yyyy-mm-dd hh24:mi:ss'),'"+Operator+"')");
						}
					}
				}
			}
			//扣料信息
			if(MaterialConsumptionDetail!=null){
				JSONArray ConsumedPackagingUnitList=MaterialConsumptionDetail.getJSONArray("ConsumedPackagingUnitList");
				for (int i=0;i<ConsumedPackagingUnitList.size();i++){
					JSONObject map1=ConsumedPackagingUnitList.getJSONObject(i);
					String PUID=map1.getString("PUID");
					String AccessTotal=map1.getString("AccessTotal");
					String RejectIdent=map1.getString("RejectIdent");
					String RejectVacuum=map1.getString("RejectVacuum");
					String TrackEmpty=map1.getString("TrackEmpty");
					baseDao.execute("insert into CONSUMEDPACKAGING(cp_id,cp_tdid,puid,AccessTotal,RejectIdent,RejectVacuum" +
							",TrackEmpty) values(CONSUMEDPACKAGING_seq.nextval,'"+td_id+"','"+PUID+"','"+AccessTotal+"','"+RejectIdent+"','"+RejectVacuum+"'," +
							"'"+TrackEmpty+"')");
				}
			}
			rmap.put("code","0");
			rmap.put("result","OK");
			rmap.put("ServerMessage","MES:贴片机数据记录成功");
		}
		return rmap;
	}

	public Map<Object,Object> XrayTestDataSave(String data){
		Map<Object, Object> rmap = new HashMap<Object, Object>();
		Map<String, Object> map=null;
		JSONObject object = JSONObject.fromObject(data);
		Object object1 = object.get("data");
		JSONObject obj = JSONObject.fromObject(object1);
		JSONArray object2=obj.getJSONArray("NonconformData");

		Object Barcode=obj.get("Barcode");
		Object EquipmentEncode=obj.get("EquipmentEncode");
		Object ModelType=obj.get("ModelType");
		Object CheckNumber=obj.get("CheckNumber");
		Object NcmNumber=obj.get("NcmNumber");
		Object NonconformNumber=obj.get("NonconformNumber");
		Object CheckDate=obj.get("CheckDate");
		Object ShiftName=obj.get("ShiftName");
		Object LineBody=obj.get("LineBody");
		Object Inspector=obj.get("Inspector");
		int XT_ID = baseDao.getSeqId("xraytest_seq");
		baseDao.execute("insert into xraytest(XT_ID, BARCODE, EQUIPMENTENCODE, MODELTYPE, CHECKNUMBER, NCMNUMBER, NONCONFORMNUMBER, CHECKDATE, SHIFTNAME, LINEBODY, INSPECTOR)" +
				"values("+XT_ID+",'"+Barcode+"','"+EquipmentEncode+"','"+ModelType+"','"+CheckNumber+"','"+NcmNumber+"','"+NonconformNumber+"',to_date('"+CheckDate+"','yyyy-mm-dd hh24:mi:ss')" +
				",'"+ShiftName+"','"+LineBody+"','"+Inspector+"')");
		for (int i=0;i<object2.size();i++){
			JSONObject map1=object2.getJSONObject(i);
			String NonconformANo=map1.getString("NonconformANo");
			String NonconformDescription=map1.getString("NonconformDescription");
			baseDao.execute("insert into XrayTestdetail(xtd_xtid,xtd_id,NONCONFORMANO, NONCONFORMDESCRIPTION)" +
					"values("+XT_ID+",XrayTestdetail_seq.nextval,'"+NonconformANo+"','"+NonconformDescription+"')");
		}
		rmap.put("code","0");
		rmap.put("result","OK");
		rmap.put("ServerMessage","MES:检查数据上传成功！");
		return rmap;
	}

	public String Time(String time){
		return time.replaceAll("T"," ").substring(0,19);
	}

	@Override
	public Map<Object,Object> Weigh(String data) {
		Map<Object, Object> rmap = new HashMap<Object, Object>();
		String oErrMessage="";
		String lotSN="";
		String specificationName="";
		String weight="";
		String moName="";
		String workcenterName="";
		Map<String, Object> map=null;
		try{
			map =BaseUtil.convertJsonToMap(data);
		}catch (Exception e){
			System.out.printf(e.getMessage()) ;
		}
		if(map.get("lotSN")==null){
			oErrMessage = "SN不能为空";
			rmap.put("oErrMessage",oErrMessage);
			return rmap;
		}
		if(map.get("lotSN")==null){
			oErrMessage = "SN不能为空";
			rmap.put("oErrMessage",oErrMessage);
			return rmap;
		}
		if(map.get("specificationName")==null){
			oErrMessage = "工序不能为空";
			rmap.put("oErrMessage",oErrMessage);
			return rmap;
		}
		if(map.get("weight")==null){
			oErrMessage = "重量不能为空";
			rmap.put("oErrMessage",oErrMessage);
			return rmap;
		}
		lotSN=map.get("lotSN").toString();
		SqlRowList rs=baseDao.queryForRowSet("select ms_sncode from  makeserial where ms_imei1='"+lotSN+"' or ms_imei2='"+lotSN+"' or ms_imei3='"+lotSN+"'");
		if(rs.next()){
			lotSN=rs.getString("ms_sncode");
		}else{
			rs=baseDao.queryForRowSet("select mil_sncode from  makeimeilist where mil_imei1='"+lotSN+"' or mil_imei2='"+lotSN+"' or mil_imei3='"+lotSN+"'");
			if(rs.next()){
				lotSN=rs.getString("mil_sncode");
			}
		}
		specificationName=map.get("specificationName").toString();
		weight=map.get("weight").toString().replaceAll("KG","");
		oErrMessage=CheckRoutePassed(lotSN,specificationName);
		if(oErrMessage!=null){
			rmap.put("code",-1);
			rmap.put("message",oErrMessage);
			Map<String, String> rmap1 = new HashMap<String, String>();
			rmap1.put("minWeight","");
			rmap1.put("maxWeightc","");
			rmap1.put("machineModel","");
			rmap.put("dataInfo",rmap1);
			return rmap;
		}
		Object[] obj = baseDao.getFieldsDataByCondition("makeserial left join product on pr_code=ms_prodcode","pr_colorboxminw,pr_colorboxmaxw","ms_id =(select max(ms_id) from makeserial where ms_sncode='"+lotSN+"')");
		if(obj[0]!=null&&obj[1]!=null){
			//不在设置的重量范围内
			if(Double.parseDouble(weight)<Double.parseDouble(obj[0].toString())||Double.parseDouble(weight)>Double.parseDouble(obj[1].toString())){
				rmap.put("code",-1);
				rmap.put("message","SN["+lotSN+"]重量为"+weight+",不符合重量范围"+obj[0]+"-"+obj[1]);
				Map<String, String> rmap1 = new HashMap<String, String>();
				rmap1.put("minWeight",obj[0].toString());
				rmap1.put("maxWeight",obj[1].toString());
				rmap1.put("machineModel","");
				rmap.put("dataInfo",rmap1);
				return rmap;
			}
			Object oErr=SetPcbaData(lotSN,specificationName,specificationName,"OK");
			if(oErr==null){
				rmap.put("code",0);
				rmap.put("message","SN["+lotSN+"]重量为"+weight+",符合重量范围"+obj[0]+"-"+obj[1]+",称重通过");
				Object ms_id=baseDao.getFieldDataByCondition("makeserial","max(ms_id)","ms_sncode='"+lotSN+"'");
				baseDao.execute("update makeserial set ms_grossw ='"+weight+"' where ms_id="+ms_id);
			}else{
				rmap.put("code",-1);
				rmap.put("message",oErr);
			}
			Map<String, String> rmap1 = new HashMap<String, String>();
			rmap1.put("minWeight",obj[0].toString());
			rmap1.put("maxWeight",obj[1].toString());
			rmap1.put("machineModel","");
			rmap.put("dataInfo",rmap1);
			return rmap;
		}
		return rmap;
	}

	@Override
	public Map<Object,Object> DLLMain(String accessKey, String requestId, String data) {
		String AE_MASTER = "MES";
		SpObserver.putSp(AE_MASTER);
		String Master=AE_MASTER;
		Map<Object, Object> map = BaseUtil.parseFormStoreToMap(data);
		//解析map
		if(!StringUtil.hasText(map.get("type"))){
			throw new ApiSystemException(new ApiResult(ErrorMessage.BUSINESS_TYPENULL,requestId));
		}
		if(!StringUtil.hasText(map.get("detail"))){
			throw new ApiSystemException(new ApiResult(ErrorMessage.BUSINESS_DATAILLEGAL,requestId));
		}
		String type = map.get("type").toString();
		JSONObject json = JSONObject.fromObject(map.get("detail"));
		HelperType helperType = HelperType.getTypeByCode(type);
		if(null == helperType){
			throw new ApiSystemException(new ApiResult(ErrorMessage.BUSINESS_TYPEILLEGAL,requestId));
		}
		baseDao.execute("insert into "+Master+".EISDATA(ed_id,ed_data,ed_indate)values("+Master+".EISDATA_seq.nextval,?,sysdate)",data);
		int err = 0;
		//返回值
		Map<Object, Object> remap = new HashMap<Object, Object>();
		switch(helperType){
			case CheckRoutePassed:
				remap = CheckRoutePassed(json);
				break;
			case CheckUserAndResourcePassed:
				remap = CheckUserAndResourcePassed(json);
				break;
			case GetAddressRangeByMO:
				remap = GetAddressRangeByMO(json);
				break;
			case GetMEIOrNetCodeRange:
				remap = GetMEIOrNetCodeRange(json);
				break;
			case GetRcardMOInfo:
				remap = GetRcardMOInfo(json);
				break;
			case GetMobileAllInfo:
				remap = GetMobileAllInfo(json);
				break;
			case SetAddressInfo:
				remap = SetAddressInfo(json);
				break;
			case GetMaster:
				remap = GetMaster(json);
				break;
			case SetMobileData:
				remap = SetMobileData(json);
				break;
			case SetIMEIInfo:
				remap = SetIMEIInfo(json);
				break;
			case SetTestDetail:
				remap = SetTestDetail(json);
				break;
			case SetPcbaData:
				remap = SetPcbaData(json);
				break;
			case GetInfoByMaterial:
				remap = GetInfoByMaterial(json);
				break;
			case GoMo:
				remap = GoMo(json);
				break;
			case GetMakeInfoBySN:
				remap = GetMakeInfoBySN(json);
				break;
			case SetBpMaterial:
				remap = SetBpMaterial(json);
				break;
			default:
				err = -1;
				break;
		}
		if(err == -1){
			throw new ApiSystemException(new ApiResult(ErrorMessage.BUSINESS_TYPEILLEGAL,requestId));
		}
		SpObserver.putSp(username);
		return remap;
	}

	private Map<Object,Object> GoMo(JSONObject map){
		Map<Object, Object> rmap = new HashMap<Object, Object>();
		String iSN=null;
		String iResCode=null;
		String iMo=null;
		String oErrMessage=null;
		if(map.get("iMo")==null){
			oErrMessage = "工单号不能为空";
			rmap.put("oErrMessage",oErrMessage);
			return rmap;
		}
		if(map.get("iResCode")==null){
			oErrMessage = "岗位资源不能为空";
			rmap.put("oErrMessage",oErrMessage);
			return rmap;
		}
		if(map.get("iSN")==null){
			oErrMessage = "SN不能为空";
			rmap.put("oErrMessage",oErrMessage);
			return rmap;
		}
		iSN=map.get("iSN").toString();
		iResCode=map.get("iResCode").toString();
		iMo=map.get("iMo").toString();
		List<String> list = new ArrayList<String>();
		list = baseDao.callProcedureWithOut("CS_CHECKSTEPSNANDMACODE", new Object[]{
				String.valueOf(iMo),
				String.valueOf(iResCode),
				String.valueOf(iSN),
				String.valueOf("")
		}, new Integer[]{1, 2, 3, 4}, new Integer[]{5, 6, 7});
		oErrMessage=list.get(2);

		SqlRowList rs = baseDao.queryForRowSet("select ms_status,ms_stepcode,ms_nextstepcode from makeserial where ms_id=(  select max(ms_id) from makeserial where ms_sncode  in ( select '" + iSN + "' from dual union select sn from makesnrelation where beforesn='" + iSN + "' and sn<>' '  union select beforesn from makesnrelation where sn='" + iSN + "' and beforesn<>' '))");
		String ms_status = "";
		String ms_stepcode = "";
		String ms_nextstepcode = "";
		if(rs.next()){
			ms_status= rs.getString("ms_status");
			ms_stepcode=rs.getString("ms_stepcode");
			ms_nextstepcode=rs.getString("ms_nextstepcode");
		}
		String stepcode = GetStepCodeBySource(iResCode);
		if ( oErrMessage == null || (ms_status == "3" && ms_stepcode == stepcode))
		{
			if (ms_status == "3")
			{
				oErrMessage =  null;
			}
		}
		rmap.put("oErrMessage",oErrMessage);
		return rmap;
	}

	private String GoMo(String iSN,String iMo,String iResCode){
		Map<Object, Object> rmap = new HashMap<Object, Object>();
		String oErrMessage=null;
		List<String> list = new ArrayList<String>();
		list = baseDao.callProcedureWithOut("CS_CHECKSTEPSNANDMACODE", new Object[]{
				String.valueOf(iMo),
				String.valueOf(iResCode),
				String.valueOf(iSN),
				String.valueOf("")
		}, new Integer[]{1, 2, 3, 4}, new Integer[]{5, 6, 7});
		oErrMessage=list.get(2);

		SqlRowList rs = baseDao.queryForRowSet("select ms_status,ms_stepcode,ms_nextstepcode from makeserial where ms_id=(  select max(ms_id) from makeserial where ms_sncode  in ( select '" + iSN + "' from dual union select sn from makesnrelation where beforesn='" + iSN + "' and sn<>' '  union select beforesn from makesnrelation where sn='" + iSN + "' and beforesn<>' '))");
		String ms_status = "";
		String ms_stepcode = "";
		String ms_nextstepcode = "";
		if(rs.next()){
			ms_status= rs.getString("ms_status");
			ms_stepcode=rs.getString("ms_stepcode");
			ms_nextstepcode=rs.getString("ms_nextstepcode");
		}
		String stepcode = GetStepCodeBySource(iResCode);
		if ( oErrMessage == null || (ms_status == "3" && ms_stepcode == stepcode))
		{
			if (ms_status == "3")
			{
				oErrMessage =  null;
			}
		}
		return oErrMessage;
	}

	private Map<Object,Object> GetInfoByMaterial(JSONObject map){
		Map<Object, Object> rmap = new HashMap<Object, Object>();
		String iPCBA=null;
		String oErrMessage=null;
		if(map.get("iPCBA")==null){
			oErrMessage = "主板SN不能为空";
			rmap.put("oErrMessage",oErrMessage);
			return rmap;
		}
		iPCBA=map.get("iPCBA").toString();
		SqlRowList rs=baseDao.queryForRowSet("select nvl(max(ms_id),0)ms_id from CRAFTMATERIAL left join makeserial on ms_firstsn=cm_firstsn  where cm_barcode='"+iPCBA+"' and nvl(cm_status,0)<>-1 order by cm_id desc");
		if(rs.next()){
			if(!rs.getString("ms_id").equals("0")){
				rs=baseDao.queryForRowSet("select ma_bios,ma_ec,ms_sncode,ma_hardware from makeserial left join make on ms_makecode=ma_code where ms_id='"+rs.getString("ms_id")+"'");
				if (rs.next()){
					rmap.put("oSN",rs.getString("ms_sncode"));
					rmap.put("oBIOS",rs.getString("ma_bios"));
					rmap.put("oEC",rs.getString("ma_ec"));
					rmap.put("oHardWare",rs.getString("ma_hardware"));
				}
			}else{
				oErrMessage = "主板SN未查询到关联信息";
				rmap.put("oErrMessage",oErrMessage);
				return rmap;
			}
		}
		return rmap;
	}

	private Map<Object,Object> CheckRoutePassed(JSONObject map){
		//实际业务数据
		Map<Object, Object> rmap = new HashMap<>();
		String iSN=map.get("iSN").toString();
		String iResCode=map.get("iResCode").toString();
		String oErrMessage="";
		if (iSN ==null)
		{
			oErrMessage = "SN不能为空";
		}
		List<String> list = new ArrayList<String>();
		list = baseDao.callProcedureWithOut("CS_CHECKSTEPSNANDMACODE", new Object[]{
				String.valueOf(""),
				String.valueOf(iResCode),
				String.valueOf(iSN),
				String.valueOf("")
		}, new Integer[]{1, 2, 3, 4}, new Integer[]{5, 6, 7});
		oErrMessage=list.get(2);
		if(oErrMessage!=null){
			rmap.put("oErrMessage",oErrMessage);
			return rmap;
		}
		SqlRowList rs = baseDao.queryForRowSet("select ms_status,ms_stepcode,ms_nextstepcode from makeserial where ms_id=(  select max(ms_id) from makeserial where ms_sncode  in ( select '" + iSN + "' from dual union select sn from makesnrelation where beforesn='" + iSN + "' and sn<>' '  union select beforesn from makesnrelation where sn='" + iSN + "' and beforesn<>' '))");
		String ms_status = "";
		String ms_stepcode = "";
		String ms_nextstepcode = "";
		if(rs.next()){
			ms_status= rs.getString("ms_status");
			ms_stepcode=rs.getString("ms_stepcode");
			ms_nextstepcode=rs.getString("ms_nextstepcode");
		}
		String stepcode = GetStepCodeBySource(iResCode);
		if (ms_nextstepcode != "" && !ms_nextstepcode.equals(stepcode)&& !ms_stepcode.equals(stepcode))
		{
			oErrMessage = "当前序列号下一工序" + ms_nextstepcode;
		}
		rmap.put("oErrMessage",oErrMessage);
		return rmap;
	}

	private String CheckRoutePassed(String iSN,String iResCode){
		//实际业务数据
		Map<Object, Object> rmap = new HashMap<>();
		String oErrMessage;
		if (iSN ==null)
		{
			oErrMessage = "SN不能为空";
		}
		List<String> list = new ArrayList<String>();
		list = baseDao.callProcedureWithOut("CS_CHECKSTEPSNANDMACODE", new Object[]{
				String.valueOf(""),
				String.valueOf(iResCode),
				String.valueOf(iSN),
				String.valueOf("")
		}, new Integer[]{1, 2, 3, 4}, new Integer[]{5, 6, 7});
		oErrMessage=list.get(2);
		if(oErrMessage!=null){
			return oErrMessage;
		}
		SqlRowList rs = baseDao.queryForRowSet("select ms_status,ms_stepcode,ms_nextstepcode from makeserial where ms_id=(  select max(ms_id) from makeserial where ms_sncode  in ( select '" + iSN + "' from dual union select sn from makesnrelation where beforesn='" + iSN + "' and sn<>' '  union select beforesn from makesnrelation where sn='" + iSN + "' and beforesn<>' '))");
		String ms_status = "";
		String ms_stepcode = "";
		String ms_nextstepcode = "";
		if(rs.next()){
			ms_status= rs.getString("ms_status");
			ms_stepcode=rs.getString("ms_stepcode");
			ms_nextstepcode=rs.getString("ms_nextstepcode");
		}
		String stepcode = GetStepCodeBySource(iResCode);
		if (ms_nextstepcode != "" && !ms_nextstepcode.equals(stepcode))
		{
			oErrMessage = "当前序列号"+iSN+"下一工序" + ms_nextstepcode;
		}
		if(ms_stepcode!=null&&ms_stepcode.equals(stepcode)){
			oErrMessage = "当前序列号"+iSN+"已执行工序" + stepcode;
		}
		return oErrMessage;
	}

	private Map<Object,Object> CheckUserAndResourcePassed(JSONObject map){
		//实际业务数据
		Map<Object, Object> rmap = new HashMap<>();
		String oErrMessage = null;
		if (map.get("iUserCode") == null || map.get("iResCode") == null || map.get("iPassWord") == null)
		{
			oErrMessage = "用户名,密码,岗位资源必须填写";
			rmap.put("oErrMessage",oErrMessage);
			return rmap;
		}
		String iUserCode=map.get("iUserCode").toString();
		String iPassWord=map.get("iPassWord").toString();
		String iResCode=map.get("iResCode").toString();
		if (CheckUserLogin(iUserCode, iPassWord))
		{
			String SQL = "select em_code,em_type,em_name from employee where em_code=? ";
			SqlRowList rs = baseDao.queryForRowSet(SQL,  iUserCode);
			if (rs.next())
			{
				String em_name = rs.getString("em_name");
				String em_type = rs.getString("em_type");
				if (iResCode ==null)
				{
					oErrMessage = "岗位资源不允许为空";
					rmap.put("oErrMessage",oErrMessage);
					return rmap;
				}
				if (em_type.equals("admin"))
				{
					if (!baseDao.checkIf("Source", "sc_code='" + iResCode + "' and sc_statuscode='AUDITED'"))
					{
						oErrMessage = "岗位资源编号错误或者未审核！";
					}
				}
				else
				{
					SqlRowList rs1=baseDao.queryForRowSet("select ur_resourcecode from cs$empgroup left join cs$userresource on ur_groupcode=eg_groupcode left join source on ur_resourcecode=sc_code where eg_emcode = '"+ iUserCode + "' and sc_statuscode='AUDITED'");
					//如果存在该编号
					if (rs1.next())
					{
						//判断如果多个岗位资源存在，用户输入的只要在其中就行
						while (rs.next())
						{
							if (!rs.getString("ur_resourcecode").equals("iResCode")){
								oErrMessage = "用户不处于当前资源所属分组!";
							}else
							{
								oErrMessage=null;
								continue;
							}
						}
					}
					else
						oErrMessage = "岗位资源编号错误或者未审核！";
				}
			}
			else
				oErrMessage = "用户不存在!";
		}else{
			oErrMessage = "用户名密码不正确!";
		}
		rmap.put("oErrMessage",oErrMessage);
		return rmap;
	}
	private Map<Object,Object> GetAddressRangeByMO(JSONObject map){
		//实际业务数据
		Map<Object, Object> rmap = new HashMap<>();
		String iSN="";
		String oErrMessage = null;
		String oWIFI = "";
		String oBT = "";
		String oCode1 = "";
		String oCode2 = "";
		String oCode3 = "";
		if(map.get("iSN")==null){
			oErrMessage = "SN不能为空";
			rmap.put("oErrMessage",oErrMessage);
			return rmap;
		}
		iSN=map.get("iSN").toString();
		//判断工单是否归属
		JSONObject map3=new JSONObject();
		map3.put("iSN",iSN);
		Map<Object, Object> map2=GetRcardMOInfo(map3);
		if(map2.get("oErrMessage")!=null){
			oErrMessage=map2.get("oErrMessage").toString();
			rmap.put("oErrMessage",oErrMessage);
			return rmap;
		}
		List<String> list = new ArrayList<String>();
		list = baseDao.callProcedureWithOut("CS_GETADDRESSBYMAKECODE", new Object[]{
				String.valueOf(iSN),
				String.valueOf(map2.get("oMoCode").toString()),
		}, new Integer[]{1,2}, new Integer[]{3,4,5,6,7,8});
		oWIFI = list.get(0);
		oBT =  list.get(1);
		oCode1 =  list.get(2);
		oCode2 = list.get(3);
		oCode3 =  list.get(4);
		oErrMessage= list.get(5);
		if (oErrMessage == "" || oErrMessage == null || oErrMessage == "null"){
			rmap.put("oWIFI",oWIFI);
			rmap.put("oBT",oBT);
			rmap.put("oCode1",oCode1);
			rmap.put("oCode2",oCode2);
			rmap.put("oCode3",oCode3);
		}
		else
			rmap.put("oErrMessage",oErrMessage);
		return rmap;
	}

	private Map<Object,Object> GetMEIOrNetCodeRange(JSONObject map){
		//实际业务数据
		Map<Object, Object> rmap = new HashMap<>();
		String iSN="";
		String oErrMessage = null;
		String oIMEI1 = "";
		String oIMEI2 = "";
		String oMEID = "";
		String oNetCode = "";
		String oPSN = "";
		String oID1 = "";
		String oID2 = "";
		String oID3 = "";
		String oID4 = "";
		String oID5 = "";
		if(map.get("iSN")==null){
			oErrMessage = "SN不能为空";
			rmap.put("oErrMessage",oErrMessage);
			return rmap;
		}
		if(map.get("iIMEI1")!=null){
			oIMEI1=map.get("iIMEI1").toString();
		}
		if(map.get("iNetCode")!=null){
			oNetCode=map.get("iNetCode").toString();
		}
		iSN=map.get("iSN").toString();
		List<String> list = new ArrayList<String>();
		list = baseDao.callProcedureWithOut("CS_GETIMEIORNETCODERANGE", new Object[]{
				String.valueOf(iSN),
				String.valueOf(""),
				String.valueOf(oIMEI1),
				String.valueOf(oNetCode),
		}, new Integer[]{1,2,3,4}, new Integer[]{5,6,7,8,9,10,11,12,13,14});
		oIMEI1 = list.get(0);
		oIMEI2 =  list.get(1);
		oMEID =  list.get(2);
		oNetCode = list.get(3);
		oID1 =  list.get(4);
		oID2 =  list.get(5);
		oID3 =  list.get(6);
		oID4 =  list.get(7);
		oID5 =  list.get(8);
		oErrMessage= list.get(9);
		if (oErrMessage == "" || oErrMessage == null || oErrMessage == "null"){
			rmap.put("oIMEI1",oIMEI1);
			rmap.put("oIMEI2",oIMEI2);
			rmap.put("oMEID",oMEID);
			rmap.put("oNetCode",oNetCode);
			rmap.put("oPSN",oPSN);
			rmap.put("oID1",oID1);
			rmap.put("oID2",oID2);
			rmap.put("oID3",oID3);
			rmap.put("oID4",oID4);
			rmap.put("oID5",oID5);
		}
		else
			rmap.put("oErrMessage",oErrMessage);
		return rmap;
	}

	private Map<Object,Object> GetRcardMOInfo(JSONObject map){
		//实际业务数据
		Map<Object, Object> rmap = new HashMap<>();
		//取MakeProcess表中的执行记录ID最大的一个工单的号码
		String oErrMessage = null;
		if(map.get("iSN")==null){
			oErrMessage = "SN不能为空";
			rmap.put("oErrMessage",oErrMessage);
			return rmap;
		}
		String iSN=map.get("iSN").toString();
		StringBuffer sql=new StringBuffer();
		sql.append("select max(ms_id)ms_id from makeserial where ms_sncode in (select '" + iSN + "' from dual union select sn from ");
		sql.append("makesnrelation where beforesn='" + iSN + "' and sn<>' '  union select beforesn from makesnrelation where sn='" + iSN + "' and beforesn<>' ')");
		SqlRowList rs = baseDao.queryForRowSet(sql.toString());
		String ms_id="";
		if(rs.next()){
			if(rs.getString("ms_id")==null){
				oErrMessage = "序列号:" + iSN + " 未归属工单";
				rmap.put("oErrMessage",oErrMessage);
				return rmap;
			}
			else{
				ms_id= rs.getString("ms_id");
			}
		}
		Object oMoCode = baseDao.getFieldDataByCondition("MakeSerial", "ms_makecode", "ms_id='" + ms_id + "'");
		if (oMoCode != null){
			rmap.put("oMoCode",oMoCode);
			oErrMessage= null;
		}
		else
		{
			oErrMessage = "序列号:" + iSN + " 未归属工单";
		}
		rmap.put("oErrMessage",oErrMessage);
		return rmap;
	}



	private Map<Object,Object> GetMobileAllInfo(JSONObject map){
		//实际业务数据
		Map<Object, Object> rmap = new HashMap<>();
		String iSN="";
		String oErrMessage = null;
		String oIMEI1 = "";
		String oIMEI2 = "";
		String oMEID = "";
		String oNetCode = "";
		String oPSN = "";
		String oID1 = "";
		String oID2 = "";
		String oID3 = "";
		String oID4 = "";
		String oID5 = "";
		String oWIFI = "";
		String oBT = "";
		String oCode1 = "";
		String oCode2 = "";
		String oCode3 = "";
		if(map.get("iSN")==null){
			oErrMessage = "SN不能为空";
			rmap.put("oErrMessage",oErrMessage);
			return rmap;
		}
		iSN=map.get("iSN").toString();
		Object ms_id =baseDao.getFieldDataByCondition("makeserial", "max(ms_id)", "ms_sncode='" + iSN + "'");
		if(ms_id!=null)
		{
			SqlRowList rs=baseDao.queryForRowSet("select ms_id, ms_mac, ms_bt, ms_meid, ms_netcode, ms_psn, ms_imei1, ms_imei2, ms_imei3, ms_othcode1, ms_othcode2, ms_othcode3, ms_othid1, ms_othid2, ms_othid3 from MakeSerial where ms_id="+ms_id.toString());
			if(rs.next()){
				oWIFI = rs.getString("ms_mac");
				oBT = rs.getString("ms_bt");
				oPSN = rs.getString("ms_psn");
				oNetCode = rs.getString("ms_netcode");
				oMEID = rs.getString("ms_meid");
				oIMEI1 = rs.getString("ms_imei1");
				oIMEI2 = rs.getString("ms_imei2");
				oCode1 = rs.getString("ms_othcode1");
				oCode2 = rs.getString("ms_othcode2");
				oCode3 = rs.getString("ms_othcode3");
				oID1 = rs.getString("ms_othid3");
				oID2 = rs.getString("ms_othid3");
				oID3 = rs.getString("ms_othid3");
			}
		}else
		{
			oErrMessage = "序列号" + iSN + "不存在";
			rmap.put("oErrMessage",oErrMessage);
			return rmap;
		}
		if (oErrMessage == "" || oErrMessage == null || oErrMessage == "null"){
			rmap.put("oIMEI1",oIMEI1);
			rmap.put("oIMEI2",oIMEI2);
			rmap.put("oMEID",oMEID);
			rmap.put("oNetCode",oNetCode);
			rmap.put("oPSN",oPSN);
			rmap.put("oID1",oID1);
			rmap.put("oID2",oID2);
			rmap.put("oID3",oID3);
			rmap.put("oID4",oID4);
			rmap.put("oID5",oID5);
			rmap.put("oWIFI",oWIFI);
			rmap.put("oBT",oBT);
			rmap.put("oCode1",oCode1);
			rmap.put("oCode2",oCode2);
			rmap.put("oCode3",oCode3);
		}
		else
			rmap.put("oErrMessage",oErrMessage);
		return rmap;
	}

	private Map<Object,Object> SetAddressInfo(JSONObject map){
		//实际业务数据
		Map<Object, Object> rmap = new HashMap<>();
		String oErrMessage = null;
		if(map.get("iSN")==null){
			oErrMessage = "SN不能为空";
			rmap.put("oErrMessage",oErrMessage);
			return rmap;
		}
		String iSN=map.get("iSN").toString();
		String iWIFI = null;
		String iBT = null;
		String iCode1 = null;
		String iCode2 = null;
		String iCode3 = null;
		if(map.get("iWIFI")!=null){
			iWIFI=map.get("iWIFI").toString();
		}
		if(map.get("iBT")!=null){
			iBT=map.get("iBT").toString();
		}
		if(map.get("iCode1")!=null){
			iCode1=map.get("iCode1").toString();
		}
		if(map.get("iCode2")!=null){
			iCode2=map.get("iCode2").toString();
		}
		if(map.get("iCode3")!=null){
			iCode3=map.get("iCode3").toString();
		}
		List<String> list = new ArrayList<String>();
		list = baseDao.callProcedureWithOut("CS_SETADDRESSINFO", new Object[]{
				String.valueOf(iSN),
				String.valueOf(iWIFI),
				String.valueOf(iBT),
				String.valueOf(iCode1),
				String.valueOf(iCode2),
				String.valueOf(iCode3)
		}, new Integer[]{1, 2, 3, 4, 5, 6}, new Integer[]{7});
		oErrMessage = list.get(0);
		rmap.put("oErrMessage",oErrMessage);
		return rmap;
	}

	private Map<Object,Object> GetMaster(JSONObject map){
		//实际业务数据
		Map<Object, Object> rmap = new HashMap<>();
		SqlRowList rs=baseDao.queryForRowSet("select ma_user from mes.master");
		while(rs.next())
		{
			rmap.put(rs.getString("ma_user"),rs.getString("ma_user"));
		}
		return rmap;
	}

	private Map<Object,Object> SetMobileData(JSONObject map){
		//实际业务数据
		Map<Object, Object> rmap = new HashMap<>();
		String oErrMessage = null;
		if(map.get("iSN")==null||map.get("iTSN")==null){
			oErrMessage = "SN不能为空";
			rmap.put("oErrMessage",oErrMessage);
			return rmap;
		}
		String iSN=map.get("iSN").toString();
		String iTSN=map.get("iTSN").toString();
		String iSourceCode = null;
		String iOperater = null;
		String iResult = null;
		String flag = null;
		String iErrCode = null;
		if(map.get("iResCode")!=null){
			iSourceCode=map.get("iResCode").toString();
		}
		if(map.get("iOperater")!=null){
			iOperater=map.get("iOperater").toString();
		}
		if(map.get("iResult")!=null){
			iResult=map.get("iResult").toString();
		}
		if(map.get("flag")!=null){
			flag=map.get("flag").toString();
		}
		if(map.get("iErrCode")!=null){
			iErrCode=map.get("iErrCode").toString();
		}
		List<String> list = new ArrayList<String>();
		list = baseDao.callProcedureWithOut("CS_DLLSNCHANGE", new Object[]{
				String.valueOf(iTSN),
				String.valueOf(iSN),
				String.valueOf(iSourceCode),
				String.valueOf(iOperater),
				String.valueOf(iResult),
				String.valueOf(iErrCode),
		}, new Integer[]{1, 2, 3, 4, 5, 6}, new Integer[]{7});
		oErrMessage = list.get(0);
		rmap.put("oErrMessage",oErrMessage);
		return rmap;
	}
	private Map<Object,Object> SetIMEIInfo(JSONObject map){
		//实际业务数据
		Map<Object, Object> rmap = new HashMap<>();
		String oErrMessage = null;
		if(map.get("iSN")==null){
			oErrMessage = "SN不能为空";
			rmap.put("oErrMessage",oErrMessage);
			return rmap;
		}
		String iSN=map.get("iSN").toString();
		String iIMEI1=null;
		String iIMEI2 = null;
		String iIMEI3 = null;
		String iMEID = null;
		String iNET = null;
		String iID1 = null;
		String iID2 = null;
		String iID3 = null;
		if(map.get("iIMEI1")!=null){
			iIMEI1=map.get("iIMEI1").toString();
		}
		if(map.get("iIMEI2")!=null){
			iIMEI2=map.get("iIMEI2").toString();
		}
		if(map.get("iIMEI3")!=null){
			iIMEI3=map.get("iIMEI3").toString();
		}
		if(map.get("iMEID")!=null){
			iMEID=map.get("iMEID").toString();
		}
		if(map.get("iNET")!=null){
			iNET=map.get("iNET").toString();
		}
		if(map.get("iID1")!=null){
			iID1=map.get("iID1").toString();
		}
		if(map.get("iID2")!=null){
			iID2=map.get("iID2").toString();
		}
		if(map.get("iID3")!=null){
			iID3=map.get("iID3").toString();
		}
		List<String> list = new ArrayList<String>();
		list = baseDao.callProcedureWithOut("CS_SETIMEIINFO", new Object[]{
				String.valueOf(iSN),
				String.valueOf(iIMEI1),
				String.valueOf(iIMEI2),
				String.valueOf(iIMEI3),
				String.valueOf(iMEID),
				String.valueOf(iNET),
				String.valueOf(""),
				String.valueOf(iID1),
				String.valueOf(iID2),
				String.valueOf(iID3),
		}, new Integer[]{1, 2, 3, 4, 5, 6,7,8,9,10}, new Integer[]{11});
		oErrMessage = list.get(0);
		rmap.put("oErrMessage",oErrMessage);
		return rmap;
	}
	private Map<Object,Object> SetTestDetail(JSONObject map){
		//实际业务数据
		Map<Object, Object> rmap = new HashMap<>();
		String oErrMessage=null;
		if(map.get("iSN")==null){
			oErrMessage = "SN不能为空";
			rmap.put("oErrMessage",oErrMessage);
			return rmap;
		}
		String iSN=map.get("iSN").toString();
		String iTestResult= "";
		String iResCode= "";
		String iClassName="";
		String iTestDetail= "";
		if(map.get("iTestResult")!=null){
			iTestResult=map.get("iTestResult").toString();
		}
		if(map.get("iClassName")!=null){
			iClassName=map.get("iClassName").toString();
		}
		if(map.get("iResCode")!=null){
			iResCode=map.get("iResCode").toString();
		}
		if(map.get("iTestDetail")!=null){
			iTestDetail=map.get("iTestDetail").toString();
		}
		JSONObject map3=new JSONObject();
		map3.put("iSN",iSN);
		Map<Object, Object> map2=GetRcardMOInfo(map3);
		String omakeCode = "";
		StringBuffer sql=new StringBuffer();
		String[] name=iClassName.split("\\|");
		String[] result=iTestResult.split("\\|");
		String[] value=iTestDetail.split("\\|");
		if(name.length!=value.length||name.length!=result.length){
			rmap.put("oErrMessage","测试项目名称和值的项次不一致");
			return rmap;
		}
		for (int i=0;i<name.length;i++){
			sql.setLength(0);
			sql.append("Insert into STEPTESTDETAIL (STD_ID,STD_CLASS,STD_SN,STD_MAKECODE,STD_ACTUALVALUE,STD_TESTRESULT,STD_INDATE,STD_RESCODE)");
			sql.append("values(STEPTESTDETAIL_SEQ.nextval,'"+name[i]+"','" + iSN + "','" + map2.get("oMoCode") + "','" + value[i] + "','" + result[i] + "',sysdate,'" + iResCode + "')");
			baseDao.execute(sql.toString());
		}
		rmap.put("oErrMessage",oErrMessage);
		return rmap;
	}

	private Map<Object,Object> SetPcbaData(JSONObject map){
		//实际业务数据
		Map<Object, Object> rmap = new HashMap<>();
		String oErrMessage = null;
		if(map.get("iSN")==null||map.get("iSN").toString().equals("")){
			oErrMessage = "SN不能为空";
			rmap.put("oErrMessage",oErrMessage);
			return rmap;
		}
		if(map.get("iResCode")==null||map.get("iResCode").toString().equals("")){
			oErrMessage = "岗位资源不能为空";
			rmap.put("oErrMessage",oErrMessage);
			return rmap;
		}

		String iSN=map.get("iSN").toString();
		String iResCode = null;
		String iOperator = null;
		String iResult = null;
		String iErrCode = null;

		if(map.get("iResCode")!=null){
			iResCode=map.get("iResCode").toString();
		}
		if(map.get("iOperater")!=null){
			iOperator=map.get("iOperater").toString();
		}else{
			iOperator = "SetPcbaDataEis";
		}
		if(map.get("iResult")!=null){
			iResult=map.get("iResult").toString();
		}
		if(map.get("iErrCode")!=null){
			iErrCode=map.get("iErrCode").toString();
		}
		oErrMessage=CheckRoutePassed(iSN,iResCode);
		if(oErrMessage!=null){
			rmap.put("oErrMessage",oErrMessage);
			return rmap;
		}
		JSONObject map3=new JSONObject();
		map3.put("iSN",iSN);
		Map<Object, Object> map2=GetRcardMOInfo(map3);
		String oMoCode=null;
		if(map2.get("oMoCode")!=null){
			oMoCode=map2.get("oMoCode").toString();
		}
		if (map2.get("oErrMessage")==null)
			return SetStepFinish(oMoCode, iResCode, iSN, "", iResult, iOperator, iErrCode);
		return rmap;
	}

	private Object SetPcbaData(String iSN,String iResCode,String iOperator,String iResult){
		//实际业务数据
		Map<Object, Object> rmap = new HashMap<>();
		String iErrCode = null;
		if(iSN==null){
			iErrCode = "SN不能为空";
			return iErrCode;
		}
		JSONObject map3=new JSONObject();
		map3.put("iSN",iSN);
		Map<Object, Object> map2=GetRcardMOInfo(map3);
		String oMoCode=null;
		if(map2.get("oMoCode")!=null){
			oMoCode=map2.get("oMoCode").toString();
		}
		if (map2.get("oErrMessage")==null)
			map2= SetStepFinish(oMoCode, iResCode, iSN, "", iResult, iResCode, iErrCode);
		return map2.get("oErrMessage");
	}

	/// <summary>
	/// 获取步骤代码
	/// </summary>
	/// <param name="Source"></param>
	/// <returns></returns>
	private String GetStepCodeBySource(String Source)
	{
		Object o=baseDao.getFieldDataByCondition("source", "sc_stepcode", "sc_code='" + Source + "'");
		if(o!=null)
			return o.toString();
		else
			return "";
	}

	private Boolean CheckUserLogin(String iUserCode, String iPassWord)
	{
		SqlRowList rs =baseDao.queryForRowSet("select em_code from employee where em_code='"+iUserCode+"' and em_password =?",iPassWord);
		if (rs.next())
			return true;
		else
		{
			return false;
		}
	}

	private Map<Object,Object> GetMakeInfoBySN(JSONObject map)
	{
		Map<Object, Object> rmap = new HashMap<Object, Object>();
		String iSN=null;
		String oErrMessage=null;
		if(map.get("iSN")==null){
			oErrMessage = "SN不能为空";
			rmap.put("oErrMessage",oErrMessage);
			return rmap;
		}
		iSN=map.get("iSN").toString();
		SqlRowList rs=baseDao.queryForRowSet("select ma_remark1,ma_remark2,ma_remark3,ma_remark4,ma_remark5,ma_remark6,ma_remark7,ma_remark8,ma_remark9,ma_remark10,ma_remark11,ma_remark12,ma_remark13,ma_remark14,ma_remark15,ma_remark16 from  make  " +
				"left join makeserial on ms_makecode=ma_code  where ms_sncode='"+iSN+"'");
		if(rs.next()){
			rmap.put("oMaremark1",rs.getString("ma_remark1"));
			rmap.put("oMaremark2",rs.getString("ma_remark2"));
			rmap.put("oMaremark3",rs.getString("ma_remark3"));
			rmap.put("oMaremark4",rs.getString("ma_remark4"));
			rmap.put("oMaremark5",rs.getString("ma_remark5"));
			rmap.put("oMaremark6",rs.getString("ma_remark6"));
			rmap.put("oMaremark7",rs.getString("ma_remark7"));
			rmap.put("oMaremark8",rs.getString("ma_remark8"));
			rmap.put("oMaremark9",rs.getString("ma_remark9"));
			rmap.put("oMaremark10",rs.getString("ma_remark10"));
			rmap.put("oMaremark11",rs.getString("ma_remark11"));
			rmap.put("oMaremark12",rs.getString("ma_remark12"));
			rmap.put("oMaremark13",rs.getString("ma_remark13"));
			rmap.put("oMaremark14",rs.getString("ma_remark14"));
			rmap.put("oMaremark15",rs.getString("ma_remark15"));
			rmap.put("oMaremark16",rs.getString("ma_remark16"));
			return rmap;
		}else{
			oErrMessage = "SN未查询到关联信息";
			rmap.put("oErrMessage",oErrMessage);
			return rmap;
		}
	}

	public Map<Object,Object> SetStepFinish(String iMakeCode, String iSourceCode, String iSN, String iMPKind, String iResult, String iUserCode, String iErrCode)
	{
		String oErrMessage = null;
		Object StepCode = baseDao.getFieldDataByCondition("Makeserial", "ms_stepcode", "ms_sncode='" + iSN + "' and ms_makecode='" + iMakeCode + "'");
		String CurrentStep = GetStepCodeBySource(iSourceCode);
		Object BgCode = baseDao.getFieldDataByCondition("step", "nvl(st_badgroupcode,' ')", "st_code='" + CurrentStep + "'");
		String mscode = baseDao.getFieldDataByCondition("Makeserial", "ms_code", "ms_sncode='" + iSN + "' and ms_makecode='" + iMakeCode + "'").toString();
		Map<Object, Object> rmap = new HashMap<>();
		switch (iResult)
		{
			case "OK":
				break;
			case "NG":
				if (iErrCode == "")
				{
					oErrMessage = "测试结果为NG时必须传递不良代码";
					rmap.put("oErrMessage",oErrMessage);
					return rmap;
				}
				else
				{

					String[] BadCode = iErrCode.split(",");
					Set<String> uniqueStrings = new HashSet<>();
					for (String str : BadCode) {
						uniqueStrings.add(str);
					}
					BadCode = uniqueStrings.toArray(new String[0]);
					if (!mscode.equals(iSN))
					{
						List<String> sqls = new ArrayList<>();
						sqls.add("update makeserial set ms_sncode = '"+mscode+"',ms_beforesn = '' where ms_sncode='" + iSN + "' and ms_makecode='" + iMakeCode + "'");
						sqls.add(" update makesnlist set msl_status = '' where msl_sncode = '"+iSN+"' and msl_makecode = '"+iMakeCode+"' ");
						sqls.add("delete makesnrelation where sn = '"+iSN+"'");
						if (sqls!=null&&sqls.size()>0){
							baseDao.execute(sqls);
						}
						iSN = mscode;
					}

					baseDao.updateByCondition("makebad", "mb_status=-1", "mb_sncode='" + iSN + "' and mb_makecode='" + iMakeCode + "' and mb_stepcode='" + CurrentStep + "' and mb_status=0");

					StringBuffer sql=new StringBuffer();
					for (int i = 0; i < BadCode.length; i++)
					{
						if(!baseDao.checkIf("badcode","bc_code='"+ BadCode[i].split(";")[0]+"'")){
							oErrMessage = "不良代码"+BadCode[i].split(";")[0]+"不存在";
							rmap.put("oErrMessage",oErrMessage);
							return rmap;
						}
						int mb_id = baseDao.getSeqId("makebad_seq");
						String badlocation = null;
						try {
							badlocation = BadCode[i].split(";")[1];
						}catch (Exception ex)
						{
							badlocation = "";
						}
						BgCode = baseDao.getFieldDataByCondition("badcode","bc_groupcode","bc_code = '"+BadCode[i].split(";")[0]+"'").toString();
						sql.setLength(0);
						sql.append("insert into makebad(mb_id,mb_makecode,mb_mscode,mb_sncode,mb_inman,mb_indate,mb_stepcode");
						sql.append(",mb_sourcecode,mb_badremark,mb_badcode,mb_badtable,mb_bgcode,mb_soncode,mb_status) select '" + mb_id + "'");
						sql.append(",ma_code,ms_code,ms_sncode,'" + iUserCode + "',sysdate,'" + CurrentStep + "','" + iSourceCode + "','"+badlocation+"','" + BadCode[i].split(";")[0] + "','',");
						sql.append("'" + BgCode + "',sp_soncode,'0' from make left join makeSerial on ms_makecode=ma_code left join stepProduct on ");
						sql.append("sp_mothercode=ma_prodcode and sp_stepcode=ms_nextstepcode where ms_sncode='" + iSN + "' and ms_makecode='" + iMakeCode + "'");
						baseDao.execute(sql.toString());
					}
					//将不良的序列号的状态码设为3
					baseDao.execute("update makeserial set ms_status='3' where ms_sncode='" + iSN + "' and ms_makecode='" + iMakeCode + "'");
				}
				break;
			default:
				oErrMessage = "测试结果必须为NG或者OK";
				rmap.put("oErrMessage",oErrMessage);
				return rmap;
		}
		//不良采集为良品是更新
		if (StepCode!=null &&StepCode.toString().equals(CurrentStep) && iResult == "OK")
		{
			Object[] ob = baseDao.getFieldsDataByCondition("makeserial", "ms_status,ms_craftcode,ms_prodcode", "ms_sncode='" + iSN + "' and ms_makecode='" + iMakeCode + "'");
			if (ob!=null)
			{
				String ms_status =ob[0].toString();
				String ms_craftcode= ob[1].toString();
				String ms_prodcode = ob[2].toString();
				if (ms_status == "3")
				{
					String nextstepcode =baseDao.getFieldDataByCondition("craft left join craftdetail on cr_id=cd_crid ", "cd_nextstepcode", "cr_code='" + ms_craftcode + "' and cr_prodcode='" + ms_prodcode + "' and cd_stepcode='" + CurrentStep + "'").toString();
					baseDao.updateByCondition("makeserial", "ms_status=1,ms_nextstepcode='" + nextstepcode + "'", "ms_sncode='" + iSN + "' and ms_makecode='" + iMakeCode + "'");
					baseDao.updateByCondition("makebad", "mb_status=-1", "mb_sncode='" + iSN + "' and mb_makecode='" + iMakeCode + "'");
				}
			}
		}
		return CS_SetFinish(iMakeCode, iSourceCode, iSN, iUserCode, iResult);
	}

	private Map<Object,Object> CS_SetFinish(String iMakeCode, String iSourceCode, String iSN, String iUserCode, String iResult)
	{
		Map<Object, Object> rmap = new HashMap<>();
		String oErrMessage=null;
		List<String> list = new ArrayList<String>();
		list = baseDao.callProcedureWithOut("CS_SETSTEPRESULT", new Object[]{
				String.valueOf(iMakeCode),
				String.valueOf(iSourceCode),
				String.valueOf(iSN),
				String.valueOf(iUserCode),
				String.valueOf(iResult),
		}, new Integer[]{1, 2, 3, 4, 5}, new Integer[]{6});
		oErrMessage = list.get(0);
		rmap.put("oErrMessage",oErrMessage);
		return rmap;
	}



	private String checkAccessKey(String accessKey,String requestId){
		Object accessSecret_O = baseDao.getFieldDataByCondition("APIEMPLOYEE", "AE_SECRET", "AE_KEY='" + accessKey + "'");
		Object AE_MASTER = baseDao.getFieldDataByCondition("APIEMPLOYEE", "AE_MASTER", "AE_KEY='" + accessKey + "'");
		String accessSecret = accessSecret_O == null ? "" : accessSecret_O.toString();
		// 检查KEY是否合理
		if (StringUtils.isEmpty(accessKey) || StringUtils.isEmpty(accessSecret) || AE_MASTER== null || "".equals(AE_MASTER.toString())) {
			ApiResult apiResult = new ApiResult(ErrorMessage.ACCESSKEY_ILLEGAL.getCode(),ErrorMessage.ACCESSKEY_ILLEGAL.getMessage(),requestId);
			throw new ApiSystemException(apiResult);
		}
		return AE_MASTER.toString();
	}

	@Override
	public Map<Object,Object> getMESSnCode(String data) {
		Map<String, Object> map=null;
		Map<Object, Object> rmap = new HashMap<Object, Object>();
		try{
			map =BaseUtil.convertJsonToMap(data);
		}catch (Exception e){
			rmap.put("code",-1);
			rmap.put("message",e.getMessage());
			System.out.printf(e.getMessage()) ;
			return rmap;
		}
		String macode = map.get("moid") == null ? "" : String.valueOf(map.get("moid"));
		if("".equals(macode)){
			rmap.put("code",-1);
			rmap.put("message","工单不能为空");
			return rmap;
		}
		if (!baseDao.checkIf("make","ma_code='"+macode+"'")){
			rmap.put("code",-1);
			rmap.put("message","工单不存在");
			return rmap;
		}
		if (baseDao.checkIf("make","nvl(ma_statuscode,' ')<>'STARTED' and ma_code='"+macode+"'")){
			rmap.put("code",-1);
			rmap.put("message","工单不是已下放状态");
			return rmap;
		}
		if (!baseDao.checkIf("MakeSnList","msl_makecode='"+macode+"'")){
			rmap.put("code",-1);
			rmap.put("message","工单未维护SN");
			return rmap;
		}
		double sncount = map.get("count") == null ? 0 : Double.parseDouble(map.get("count").toString());
		if(sncount<=0){
			rmap.put("code",-1);
			rmap.put("message","SN数量必须大于0");
			return rmap;
		}
		int count = baseDao.getCountByCondition("MakeSnList", "msl_makecode='" + macode + "' and nvl(msl_status,0)=0");
		if (count<sncount){
			rmap.put("code",-1);
			rmap.put("message","SN不足！");
			return rmap;
		}
		List<String> sqls = new ArrayList<>();
		List<Map<String, Object>> maps = new ArrayList<>();
		Map<String, Object> snmap=null;
		SqlRowList rs = baseDao.queryForRowSet("select msl_sncode,msl_id from (select msl_sncode,msl_id from MakeSnList where msl_makecode='" + macode + "' and nvl(msl_status,0)=0 order by msl_sncode) where rownum<="+sncount +"  order by msl_sncode ");
		String mainbarcode="";
		String msl_id="";
		while (rs.next()){
			snmap=new HashMap<String, Object>();
			snmap.put("serialNo",rs.getGeneralString("msl_sncode"));
			mainbarcode=rs.getGeneralString("msl_sncode");
			maps.add(snmap);
			sqls.add("update MakeSnList set msl_signtime=sysdate,msl_status=-1 where msl_id="+rs.getGeneralInt("msl_id"));
			msl_id+=rs.getGeneralInt("msl_id")+",";
		}
		msl_id+="0";
		baseDao.execute("update MakeSnList set msl_mainbarcode='"+mainbarcode+"' where msl_id in ("+msl_id+")");

		if (sqls!=null&&sqls.size()>0){
			baseDao.execute(sqls);
		}
		rmap.put("code",0);
		rmap.put("data",maps);
		return rmap;
	}

	@Override
	public Map<Object, Object> getMakeSnCode(String data) {
		Map<String, Object> map=null;
		Map<Object, Object> rmap = new HashMap<Object, Object>();
		try{
			map =BaseUtil.convertJsonToMap(data);
		}catch (Exception e){
			rmap.put("code",-1);
			rmap.put("message",e.getMessage());
			System.out.printf(e.getMessage()) ;
			return rmap;
		}
		String macode = map.get("moid") == null ? "" : String.valueOf(map.get("moid"));
		if("".equals(macode)){
			rmap.put("code",-1);
			rmap.put("message","工单不能为空");
			return rmap;
		}
		if (!baseDao.checkIf("make","ma_code='"+macode+"'")){
			rmap.put("code",-1);
			rmap.put("message","工单不存在");
			return rmap;
		}
		if (baseDao.checkIf("make","nvl(ma_statuscode,' ')<>'STARTED' and ma_code='"+macode+"'")){
			rmap.put("code",-1);
			rmap.put("message","工单不是已下放状态");
			return rmap;
		}
		if (!baseDao.checkIf("MakeSnList","msl_makecode='"+macode+"'")){
			rmap.put("code",-1);
			rmap.put("message","工单未维护SN");
			return rmap;
		}
		double sncount = map.get("count") == null ? 1 : Double.parseDouble(map.get("count").toString());
		if(sncount<=0){
			rmap.put("code",-1);
			rmap.put("message","SN数量必须大于0");
			return rmap;
		}
		String mType = map.get("mType") == null ? "" : String.valueOf(map.get("mType"));
		if("".equals(mType)){
			rmap.put("code",-1);
			rmap.put("message","类型不能为空");
			return rmap;
		}
		int count = baseDao.getCountByCondition("MakeSnList", "msl_makecode='" + macode + "' and nvl(msl_type,' ')='"+mType+"' and nvl(msl_status,0)=0");
		if (count<sncount){
			rmap.put("code",-1);
			rmap.put("message","SN不足！");
			return rmap;
		}
		List<String> sqls = new ArrayList<>();
		List<Map<String, Object>> maps = new ArrayList<>();
		Map<String, Object> snmap=null;
		SqlRowList rs = baseDao.queryForRowSet("select msl_sncode,msl_id from (select msl_sncode,msl_id from MakeSnList where msl_makecode='" + macode + "' and nvl(msl_type,' ')='"+mType+"' and nvl(msl_status,0)=0 order by msl_sncode) where rownum<="+sncount +"  order by msl_sncode ");
		String mainbarcode="";
		String msl_id="";
		while (rs.next()){
			snmap=new HashMap<String, Object>();
			snmap.put("serialNo",rs.getGeneralString("msl_sncode"));
			mainbarcode=rs.getGeneralString("msl_sncode");
			maps.add(snmap);
			sqls.add("update MakeSnList set msl_signtime=sysdate,msl_status=-1 where msl_id="+rs.getGeneralInt("msl_id"));
			msl_id+=rs.getGeneralInt("msl_id")+",";
		}
		msl_id+="0";
		baseDao.execute("update MakeSnList set msl_mainbarcode='"+mainbarcode+"' where msl_id in ("+msl_id+")");

		if (sqls!=null&&sqls.size()>0){
			baseDao.execute(sqls);
		}
		rmap.put("code",0);
		rmap.put("data",maps);
		return rmap;
	}

	@Override
	public Map<Object, Object> getMainAllSnCode(String data) {
		Map<String, Object> map=null;
		Map<Object, Object> rmap = new HashMap<Object, Object>();
		try{
			map =BaseUtil.convertJsonToMap(data);
		}catch (Exception e){
			rmap.put("code",-1);
			rmap.put("message",e.getMessage());
			System.out.printf(e.getMessage()) ;
			return rmap;
		}
		String sn = StringUtil.nvl(map.get("sn"),"");
		if("".equals(sn)){
			rmap.put("code",-1);
			rmap.put("message","SN不能为空");
			return rmap;
		}
		List<Map<String, Object>> maps = baseDao.queryForList("select sb_barcode serialNo, '' zone from smtbind where sb_maincode=(select sb_maincode from smtbind where sb_barcode='"+sn+"')");
		rmap.put("code",0);
		rmap.put("data",maps);
		return rmap;
	}

	@Override
	public Map<Object, Object> countQTY(String data) {
		Map maps =  BaseUtil.parseFormStoreToMap(data);
		String barcode  = maps.get("reel_id").toString();
		String qty  = maps.get("QTY").toString();
		Map<Object, Object> map = new HashMap<>();
		SqlRowList rs = baseDao.queryForRowSet(" select VE_SHORTNAME,pr_detail,pr_spec,bar_prodcode,to_char(bar_madedate,'YYYY-MM-DD')bar_madedate,bar_code,bar_remain,bar_id from barcode left join product on pr_code = bar_prodcode LEFT JOIN VENDOR@WP ON BAR_VENDCODE  = VE_CODE where bar_code = '"+barcode+"'  ");
		if(rs.next()) {
			baseDao.updateByCondition("barcode","bar_remain = '"+qty+"',bar_status = 1 " +
					" ","bar_code = '"+barcode+"' ");
			baseDao.execute("insert into barcodelogger(bl_id,bl_barcode,bl_barid,bl_prodcode,bl_whcode,bl_date,bl_inman,bl_action,bl_description)"
					+ " values(barcodelogger_seq.nextval,?,?,?,?,sysdate,?,'点料机更新条码数量',?)",barcode,rs.getInt("bar_id"),rs.getString("bar_prodcode"),"","ADMIN","原数量:"+rs.getDouble("bar_remain")+",新数量:"+qty);
			//点料机接口调整，先实时更新条码数（ERP+MES），再生成条码入库申请单（主从表，一小时内的数据合并一张单，点料间隔超1小时则产生新单据）
			// 单据审核后更新条码的库存状态
			SqlRowList rs1 = baseDao.queryForRowSet("select bar_id,bar_remain,bar_prodcode from barcode@WP where bar_code=?",barcode);
			if(rs1.next()) {
				baseDao.execute("update barcode@WP set bar_remain=?,bar_outno = '',bar_status = 2 where bar_id=?", qty, rs1.getString("bar_id"));
				baseDao.execute("insert into barcodelogger@WP(bl_id,bl_barcode,bl_barid,bl_prodcode,bl_whcode,bl_date,bl_inman,bl_action,bl_description)"
						+ " values(barcodelogger_seq.nextval@WP,?,?,?,?,sysdate,?,'点料机更新条码数量',?)",barcode,rs1.getInt("bar_id"),rs1.getString("bar_prodcode"),"","ADMIN","原数量:"+rs1.getDouble("bar_remain")+",新数量:"+qty);
				//插入条码状态更新单
				String ctcode = null;
				int cddetno = 0;
				boolean has = false;
				Integer ctid = baseDao.getJdbcTemplate().queryForObject(" select max(ct_id) from customtable@WP WHERE CT_CALLER='RF-TMSC' AND " +
						"  to_char(ct_recorddate,'yyyy-mm-dd hh24') =to_char(sysdate,'yyyy-mm-dd hh24') and CT_SOURCETYPE='点料机' and ct_statuscode='ENTERING' ",Integer.class);
				if(null == ctid){
					//插入主表
					String sql = "select customtable_seq.nextval@WP from dual";
					SqlRowList rs2 = baseDao.queryForRowSet(sql);
					if (rs2.next()) {
						ctid = rs2.getInt(1);
						//插入主表
						ctcode = baseDao.callProcedure("Sp_GetMaxNumber@WP", new Object[] { "RF-TMSC", 2 });
						baseDao.execute("insert into customtable@WP(ct_id,ct_caller,ct_code,ct_sourcekind,ct_sourcetype," +
								" ct_recorddate,ct_statuscode,ct_status,ct_recorder,ct_varchar50_1) " +
								" select ?,'RF-TMSC',? ,'条码删除申请','点料机',sysdate,'ENTERING','在录入','点料机','点料机对接自动生成' from dual ",ctid,ctcode);
					}
				}else{
					SqlRowList rs2 = baseDao.queryForRowSet("select ct_code, " +
							" nvl((select max(cd_detno) from customtabledetail@WP where cd_ctid=ct_id),0) cd_detno ," +
							" nvl((select max(cd_detno) from customtabledetail@WP where cd_ctid=ct_id and cd_varchar50_1=?),0) detno" +
							" from customtable@WP WHERE CT_ID="+ctid,barcode);
					if(rs2.next()){
						ctcode = rs2.getString("ct_code");
						cddetno = rs2.getInt("cd_detno");
						has = rs2.getInt("detno")>0 ? true:false;
					}
				}
				if(null != ctid && ctid.intValue()>0 && !has){
					//如果当前条码不存在明细行则插入到明细行
					cddetno = cddetno+1;
					baseDao.execute("insert into customtabledetail@WP(cd_id,cd_ctid,CD_DETNO,cd_varchar50_1) " +
							" select customtabledetail_seq.nextval@WP,?,?,? from dual",ctid,cddetno,barcode);
				}
			}
			map.put("ret_code","0");
			map.put("ret_msg","OK");
			map.put("PN",rs.getString("bar_prodcode"));
			map.put("VE",rs.getString("VE_SHORTNAME"));
			map.put("DETAIL",rs.getString("pr_detail"));
			map.put("DESCR",rs.getString("pr_spec"));
			map.put("DC",rs.getString("bar_madedate"));
		}else
		{
			map.put("ret_code","130");
			map.put("ret_msg","条码:"+barcode+"不存在于MES");
			map.put("PN","");
			map.put("VE","");
			map.put("DETAIL","");
			map.put("DESCR","");
			map.put("DC","");
		}
		return map;
	}


	private Map<Object,Object> SetBpMaterial(JSONObject map)
	{
		Map<Object, Object> rmap = new HashMap<Object, Object>();
		String iSN=null;
		String oErrMessage=null;
		String iZJ=null;
		String iResCode = null;
		String linecode = null;
		String stepcode =  null;
		if(map.get("iSN")==null){
			oErrMessage = "SN不能为空";
			rmap.put("oErrMessage",oErrMessage);
			return rmap;
		}
		if(map.get("iZJ")==null){
			oErrMessage = "载具号不能为空";
			rmap.put("oErrMessage",oErrMessage);
			return rmap;
		}
		iSN=map.get("iSN").toString();
		iZJ=map.get("iZJ").toString();
		iResCode=map.get("iResCode").toString();
		linecode = GetlineCodeBySource(iResCode);
		stepcode = GetStepCodeBySource(iResCode);

		JSONObject map3=new JSONObject();
		map3.put("iSN",iSN);
		Map<Object, Object> map2=GetRcardMOInfo(map3);
		String oMoCode=null;
		if(map2.get("oMoCode")!=null){
			oMoCode=map2.get("oMoCode").toString();
		}
		if(!baseDao.checkIf("BEFOREHANDPROCESS","bhp_maincode = '"+iZJ+"' and nvl(BHP_STATUS,0) = 0"))
		{
			oErrMessage = "载具号"+iZJ+"内无材料";
			rmap.put("oErrMessage",oErrMessage);
			return rmap;
		}

		baseDao.execute("update Craftmaterial set cm_status = -1 where cm_sncode = '"+iSN+"' and cm_makecode = '"+oMoCode+"'");

		baseDao.execute("insert into Craftmaterial (cm_id ,cm_makecode,cm_maid,cm_maprodcode, cm_soncode, cm_mscode, cm_sncode, cm_stepcode, cm_stepname,cm_fsoncode," +
				" cm_craftcode,cm_craftname,cm_barcode,cm_inqty,cm_indate,cm_inman,cm_linecode,cm_wccode,cm_sourcecode,cm_spid,cm_status,cm_materialtype,cm_firstsn) " +
				" select Craftmaterial_seq.nextval,ma_code, ma_id, ma_prodcode,sp_soncode,ms_code,ms_sncode,mcd_stepcode,mcd_stepname,sp_fsoncode," +
				"  ms_craftcode,ms_craftname,bhp_barcode,1,sysdate,'','" + linecode +"',ma_wccode,'" + iResCode + "',sp_id,0,1,ms_firstsn" +
				" from make left join makecraftdetail on mcd_macode=ma_code left join stepproduct on sp_stepcode=mcd_stepcode and sp_mothercode = ma_prodcode left join" +
				"  makeserial on ms_makecode=ma_code and sp_craftcode=ms_craftcode left join (select * from " +
				"  BEFOREHANDPROCESS where bhp_maincode='" + iZJ + "' and nvl(bhp_status,0) =0 ) on sp_fsoncode=bhp_prodcode" +
				"  where ma_code='" + oMoCode + "' and mcd_stepcode = '" + stepcode + "' and ms_sncode='" + iSN + "' and bhp_barcode is not null ");


		baseDao.execute(" update BEFOREHANDPROCESS set bhp_status = -1 where bhp_maincode = '"+iZJ+"' and nvl(bhp_status,0) =0   ");


		return SetStepFinish(oMoCode, iResCode, iSN, "", "OK", "ADMIN", "");
	}


	private String GetlineCodeBySource(String Source)
	{
		Object o=baseDao.getFieldDataByCondition("source", "sc_linecode", "sc_code='" + Source + "'");
		if(o!=null)
			return o.toString();
		else
			return "";
	}

}
