package com.dev.swms.server.service.interfaceLog.pojo;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.pdfbox.io.IOUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.dev.energy.server.exception.BusinessException;
import com.dev.energy.server.model.EntityFactory;
import com.dev.energy.server.model.security.User;
import com.dev.energy.server.service.pojo.DefaultBaseManager;
import com.dev.energy.server.web.security.UserHolder;
import com.dev.swms.server.model.abstractEntity.Pinfan;
import com.dev.swms.server.model.base.BillType;
import com.dev.swms.server.model.base.Item;
import com.dev.swms.server.model.base.ItemKey;
import com.dev.swms.server.model.base.ItemRelation;
import com.dev.swms.server.model.base.Location;
import com.dev.swms.server.model.base.LotInfo;
import com.dev.swms.server.model.base.NewLotInfo;
import com.dev.swms.server.model.base.Warehouse;
import com.dev.swms.server.model.base.WarehouseArea;
import com.dev.swms.server.model.interfaceLog.InterfaceLog;
import com.dev.swms.server.model.inventory.Inventory;
import com.dev.swms.server.model.inventory.InventoryLog;
import com.dev.swms.server.model.inventory.InventoryLogType;
import com.dev.swms.server.model.inventory.Task;
import com.dev.swms.server.model.inventory.TaskLog;
import com.dev.swms.server.model.receiving.ASN;
import com.dev.swms.server.model.receiving.ASNDetail;
import com.dev.swms.server.model.receiving.ASNStatus;
import com.dev.swms.server.model.receiving.MoveDoc;
import com.dev.swms.server.model.receiving.MoveDocDetail;
import com.dev.swms.server.model.receiving.MoveDocStatus;
import com.dev.swms.server.model.receiving.ReceivedRecord;
import com.dev.swms.server.model.shipping.PickTicket;
import com.dev.swms.server.model.shipping.PickTicketDetail;
import com.dev.swms.server.model.shipping.PickTicketStatus;
import com.dev.swms.server.model.shipping.PlanPickTicketDetail;
import com.dev.swms.server.model.shipping.PlanShipDetail;
import com.dev.swms.server.model.shipping.PrintXppRecord;
import com.dev.swms.server.model.shipping.RkEwmRecord;
import com.dev.swms.server.service.base.ItemManager;
import com.dev.swms.server.service.interfaceLog.InterfaceManager;
import com.dev.swms.server.service.interfaceLog.XbtlManager;
import com.dev.swms.server.service.receiving.ASNManager;
import com.dev.swms.server.service.sequence.BussinessCodeManager;
import com.dev.swms.server.utils.DateUtil;
import com.dev.swms.server.utils.DoubleUtils;
import com.dev.swms.server.web.filter.WarehouseHolder;
public class DefaultXbtlManager extends DefaultBaseManager implements XbtlManager{
	
	@Override
	public String readJson(String jsonStr) {
		String data="";
		JSONObject json = JSONObject.fromObject(jsonStr);
		System.out.println(json.toString());
		String methodType=json.getString("methodType");
		if(methodType.equals("queryRkList")){//查询列表
			data=queryRkList(json);
		}else if(methodType.equals("scanRkErm")){//扫描发动机二维码（包含品番）
			data=scanRkErm(json);
//		}else if(methodType.equals("scanRkDstLoc")){//扫描库位上架
//			System.out.println(data+"===");
		}else if(methodType.equals("queryRkDetailList")){//入库清单
			data=queryRkDetailList(json);
		}else if(methodType.equals("queryBhListKams")){//发货列
			data=queryBhListKams(json);
		}else if(methodType.equals("queryFhDetailKams")){//发货明细
			data=queryFhDetailKams(json);
		}else if(methodType.equals("queryBhDetailKams")){//备货明细
			data=queryBhDetailKams(json);
		}else if(methodType.equals("scanFhTph")){//发动机发货出库
			data=scanFhTph(json);
		}else if(methodType.equals("scanXbTph")){//线边接收扫描托盘号
			data=scanXbTph(json);
		}else if(methodType.equals("queryXbjsDetail")){//线边接收明细列表
			data=queryXbjsDetail(json);
		}else if(methodType.equals("scanXppHcTl")){//缓存投料
			data=scanXppTl(json,"HCTL");
		}else if(methodType.equals("scanXppZzTl")){//制造库位投料
			data=scanXppTl(json,"ZZTL");
		}else if(methodType.equals("queryXbInv")){//查询线边库存
			data=queryXbInv(json);
		}else if(methodType.equals("queryKamsInv")){//查询协同库存
			data=queryKamsInv(json);
		}else if(methodType.equals("scanFdjItemCode")){//扫描发动机品番
			data=scanFdjItemCode(json);
		}else if(methodType.equals("scanFdjJh")){//扫描入库发动机机号
			data=scanFdjJh(json);
		}else if(methodType.equals("scanFdjJhItemCode")){//扫描出库发动机品番备货
				data=scanFdjJhItemCode(json);
		}
		return data;
	}
	
	public String queryRkList(JSONObject json) {
		String data="";
		String returnMsg="";
		String returnCode="200";
		String returnData="";
		InterfaceLog log=storeInterfaceLog(null,"Android", "WMS", "发动机入库清单列表查询", json.toString(), null);
		String queryInfo=json.getString("queryInfo");
		Session session = ((HibernateDaoSupport)this.commonDao).getSessionFactory().openSession();
    	String sql="select asn.RELATED_BILL2,IFNULL(asn.RELATED_BILL1,asn.code) fph,DATE_FORMAT(asn.ORDER_DATE,'%Y-%m-%d') dhr,"
    			+ "sum(d.EXPECTED_QUANTITY),sum(d.RECEIVED_QUANTITY) "
    			+ " from ASN asn "
    			+ " left join asn_detail d on d.asn_id=asn.id "
    			+ " left join item it on it.id=d.item_id"
    			+ " where 1=1 and asn.status not in ('OPEN','CLOSE') and asn.warehouse_id=1  and it.BE_WEIGHT=1"
    			+ " ";
    	if(queryInfo!=null&&!queryInfo.equals("")){
    		sql+=" and (asn.RELATED_BILL2='"+queryInfo+"' or asn.RELATED_BILL1='"+queryInfo+"') ";
    	}
//	    	sql+=" GROUP BY relatedBill2";
    	sql+=" GROUP BY asn.RELATED_BILL2,fph";
    	sql+=" ORDER BY asn.id";
    	System.out.println(sql);
	    Query   query   =   session.createSQLQuery(sql); 
		List<Object> list= (List<Object>)query.list();
		JSONArray  array = new JSONArray();
		for (int i=0;i<list.size();i++) {
			try {
				Object[] objarr = (Object[])list.get(i);
				String tps=objarr[3]==null?"":objarr[3].toString();
				String put_ts=objarr[4]==null?"":objarr[4].toString();
				if(tps.equals(put_ts)){
					continue;
				}
				JSONObject obj = new JSONObject();
				String jzxh=objarr[0]==null?"":objarr[0]+"";
				String fph=objarr[1]==null?"":objarr[1]+"";
				String jzfp=jzxh;
				if(jzfp.equals("")){
					jzfp=fph;
				}
				obj.put("jzfp", jzfp);
				obj.put("jzxh", jzxh);
				obj.put("fph", fph);
				obj.put("tps", tps);
				obj.put("put_ts", put_ts);
				obj.put("dhr",objarr[2]==null?"":objarr[2]+"");
				array.add(obj);
			} catch (Exception e) {
				session.close();
				data=returnJson("400", "操作失败", e.getMessage());
			    return data;
			}
		}
		session.close();
		returnData=array.toString();
		data=returnJson(returnCode, returnMsg, returnData);
		return data;
	}
	
	public String scanRkErm(JSONObject json) {
		String data="";
		String returnMsg="";
		String returnCode="200";
		String returnData="";
		String errorMes="";
		InterfaceLog log=storeInterfaceLog(null,"Android", "WMS", "发动机入库二维码扫描", json.toString(), null);
		String ewm =json.has("ewm")?json.getString("ewm"):"";
		String jzfp =json.has("jzfp")?json.getString("jzfp"):"";
	    	JSONObject obj= new JSONObject();
	    	try{
			if(ewm!=null&&!ewm.equals("")&&ewm.length()>10){
				 String item_code=ewm.substring(0, 10);
				 String fdj=ewm.substring(10, ewm.length());
				 if(ewm.indexOf("1J81420000")>0){
					 //样例：PIN MD1J81420000 SN7NT3189 WGN EMC ESN
					//样例： PIN MD1J81420000 SN7PM0642 WGN EMC ESN
					 item_code="1J81420000";
					 fdj=ewm.substring(19, 26);
				 }
				 //是否重复
				 List<RkEwmRecord> rs=this.commonDao.findByQuery("from RkEwmRecord r where r.ewm='"+ewm+"'");
				 if(rs.size()>0){
					 errorMes="该机号已入库";
				 }else{
					 String sql="from ASNDetail d where 1=1 and (d.asn.relatedBill2='"+jzfp+"' or d.asn.relatedBill1='"+jzfp+"' or d.asn.code='"+jzfp+"')";
					 sql+=" and d.item.code='"+item_code+"' and d.receivedQuantity<d.expectedQuantity " ;
		    		List<ASNDetail> ds=this.commonDao.findByQuery(sql);
				    if(ds.size()<=0){
				    	 errorMes="无该品番"+item_code+"或已收完";
					 }else{
						 ASNDetail d=ds.get(0);
						 if(d.getReceivedQuantity()==d.getExpectedQuantity()){
				    			errorMes=item_code+"订单号品番已全部收货";
				    		}else{
				    			LotInfo info=d.getLotInfo();
				    			String tax=d.getTemperature();
				    			if(info!=null){
					    			if(info.getPropC1()!=null&&info.getPropC1().equals("一般贸易")){
					    				tax="课税";
					    			}else{
					    				tax="保税";
					    			}
				    			}
				    			Item it=commonDao.get(Item.class, d.getItem().getId());
				    			obj.put("d_id", d.getId());
				    			obj.put("item_code", it.getCode());
							    obj.put("item_name", it.getName());
							    obj.put("tax", tax);
							    obj.put("fdj", fdj);
								int shsl=1;
							    obj.put("qty",shsl);
							    obj.put("tp_qty",d.getExpectedQuantity());
								obj.put("tp_put_qty",d.getReceivedQuantity());
								obj.put("tp_sysl",d.getExpectedQuantity()-d.getReceivedQuantity());
				    			List<Pinfan> pfs=this.commonDao.findByQuery("from Pinfan pf where pf.item.id="+d.getItem().getId()+" and pf.bonded='"+tax+"'");
				    			if(pfs.size()<=0){
				    				throw new BusinessException("请维护品番关联");
				    			}else{
				    				Pinfan pf=pfs.get(0);
				    				Location loc=pf.getLocation();
									if(loc!=null){
										String str[]= loc.getCode().split("/");
										if(str.length>1){
											obj.put("src_loc", str[1]);
										}else{
											obj.put("src_loc", str[0]);
										}
										obj.put("src_loc2", loc.getCode());
									}
								obj.put("pf_id", pf.getId());
				    		}
			    		}
				 	}
				 }
			}else{
				errorMes = "发动机二维码不能为空";
			}
	    	if(errorMes!=null&&!errorMes.equals("")){
    			data=returnJson("400", errorMes, returnData);
    			return data;
    		}
	    
		} catch (Exception e) {
			data=returnJson("400", "操作失败", e.getMessage());
		    return data;
		}
		returnData=obj.toString();
		data=returnJson(returnCode, returnMsg, returnData);
		return data;
	}
	public String scanFdjItemCode(JSONObject json) {
		String data="";
		String returnMsg="";
		String returnCode="200";
		String returnData="";
		String errorMes="";
		InterfaceLog log=storeInterfaceLog(null,"Android", "WMS", "发动机入库品番扫描", json.toString(), null);
		String item_code =json.has("item_code")?json.getString("item_code"):"";
		String jzfp =json.has("jzfp")?json.getString("jzfp"):"";
	    JSONObject obj= new JSONObject();
	    try{
			 String sql="from ASNDetail d where 1=1 and (d.asn.relatedBill2='"+jzfp+"' or d.asn.relatedBill1='"+jzfp+"' or d.asn.code='"+jzfp+"')";
			 sql+=" and d.item.code='"+item_code+"' and d.receivedQuantity<d.expectedQuantity " ;
    		 List<ASNDetail> ds=this.commonDao.findByQuery(sql);
		     if(ds.size()<=0){
		    	 errorMes="无该品番"+item_code+"或已收完";
			 }else{
				 ASNDetail d=ds.get(0);
				 if(d.getReceivedQuantity()==d.getExpectedQuantity()){
		    			errorMes=item_code+"订单号品番已全部收货";
		    		}else{
		    			LotInfo info=d.getLotInfo();
		    			String tax=d.getTemperature();
		    			if(info!=null){
			    			if(info.getPropC1()!=null&&info.getPropC1().equals("一般贸易")){
			    				tax="课税";
			    			}else{
			    				tax="保税";
			    			}
		    			}
			    			Item it=commonDao.get(Item.class, d.getItem().getId());
			    			obj.put("d_id", d.getId());
			    			obj.put("item_code", it.getCode());
						    obj.put("item_name", it.getName());
						    obj.put("tax", tax);
							int shsl=1;
						    obj.put("qty",shsl);
						    obj.put("tp_qty",d.getExpectedQuantity());
							obj.put("tp_put_qty",d.getReceivedQuantity());
							obj.put("tp_sysl",d.getExpectedQuantity()-d.getReceivedQuantity());
			    			List<Pinfan> pfs=this.commonDao.findByQuery("from Pinfan pf where pf.item.id="+d.getItem().getId()+" and pf.bonded='"+tax+"'");
			    			if(pfs.size()<=0){
			    				throw new BusinessException("请维护品番关联");
			    			}else{
			    				Pinfan pf=pfs.get(0);
			    				Location loc=pf.getLocation();
								if(loc!=null){
									String str[]= loc.getCode().split("/");
									if(str.length>1){
										obj.put("src_loc", str[1]);
									}else{
										obj.put("src_loc", str[0]);
									}
									obj.put("src_loc2", loc.getCode());
								}
							obj.put("pf_id", pf.getId());
			    		}
			    	}
			 }
	    	if(errorMes!=null&&!errorMes.equals("")){
    			data=returnJson("400", errorMes, returnData);
    			return data;
    		}
	    
		} catch (Exception e) {
			data=returnJson("400", "操作失败", e.getMessage());
		    return data;
		}
		returnData=obj.toString();
		data=returnJson(returnCode, returnMsg, returnData);
		return data;
	}
	
	public String scanFdjJh(JSONObject json) {
		String data="";
		String returnMsg="";
		String returnCode="200";
		String returnData="";
		String errorMes="";
		InterfaceLog log=storeInterfaceLog(null,"Android", "WMS", "发动机入库二维码扫描", json.toString(), null);
		String fdj =json.has("fdj")?json.getString("fdj"):"";
    	JSONObject obj= new JSONObject();
    	try{
		if(fdj!=null&&!fdj.equals("")){
			 //是否重复
			 List<RkEwmRecord> rs=this.commonDao.findByQuery("from RkEwmRecord r where r.fdj='"+fdj+"'");
			 if(rs.size()>0){
				 errorMes="该机号已入库";
			 }else{
				 obj.put("fdj", fdj);
			 }
		}else{
			errorMes = "发动机机号不能为空";
		}
    	if(errorMes!=null&&!errorMes.equals("")){
			data=returnJson("400", errorMes, returnData);
			return data;
		}
	    
		} catch (Exception e) {
			data=returnJson("400", "操作失败", e.getMessage());
		    return data;
		}
		returnData=obj.toString();
		data=returnJson(returnCode, returnMsg, returnData);
		return data;
	}
	public String scanFdjJhItemCode(JSONObject json) {
		String data="";
		String returnMsg="";
		String returnCode="200";
		String returnData="";
		String errorMes="";
		InterfaceLog log=storeInterfaceLog(null,"Android", "WMS", "发动机出库品番扫描", json.toString(), null);
		String item_code =json.has("item_code")?json.getString("item_code"):"";
		Long pt_id=json.getLong("pt_id");
	    JSONObject obj= new JSONObject();
	    try{
	    	List<Task> ts=this.commonDao.findByQuery("from Task t where t.pickTicketDetail.pickTicket.id="+pt_id+" and t.itemKey.item.code='"+item_code+"'"
					+" and t.planQuantityMU>0 and t.planQuantityMU>t.movedQuantityMU");
		     if(ts.size()<=0){
		    	 errorMes="无该品番"+item_code+"或已收完";
			 }else{
				 Task t=ts.get(0);
				 PickTicketDetail ptd=t.getPickTicketDetail();
				 obj.put("item_code", ptd.getItem().getCode());
				 obj.put("item_name", ptd.getItem().getName());
				 obj.put("src_loc", t.getSrcLoc().getCode());
				 PickTicket pt=this.commonDao.get(PickTicket.class, pt_id);
				 String sql="select t.id from TaskLog t where  t.task.pickTicketDetail.pickTicket.id="+pt_id;
				 obj.put("cds",pt.getAllocatedQuantity());
				 obj.put("ybhs",pt.getPickedQuantity());
				 obj.put("ybhxs",commonDao.findByQuery(sql).size());
			 }
	    	if(errorMes!=null&&!errorMes.equals("")){
    			data=returnJson("400", errorMes, returnData);
    			return data;
    		}
	    
		} catch (Exception e) {
			data=returnJson("400", "操作失败", e.getMessage());
		    return data;
		}
		returnData=obj.toString();
		data=returnJson(returnCode, returnMsg, returnData);
		return data;
	}
	
	
	public String scanBhFdjJh(JSONObject json) {
		String data="";
		String returnMsg="";
		String returnCode="200";
		String returnData="";
		String errorMes="";
		InterfaceLog log=storeInterfaceLog(null,"Android", "WMS", "发动机出库机号品番扫描", json.toString(), null);
		String fdj =json.has("fdj")?json.getString("fdj"):"";
    	JSONObject obj= new JSONObject();
    	try{
		if(fdj!=null&&!fdj.equals("")){
			 //是否重复
			 List<RkEwmRecord> rs=this.commonDao.findByQuery("from RkEwmRecord r where r.fdj='"+fdj+"'");
			 if(rs.size()>0){
				 errorMes="该机号已入库";
			 }else{
				 obj.put("fdj", fdj);
			 }
		}else{
			errorMes = "发动机机号不能为空";
		}
    	if(errorMes!=null&&!errorMes.equals("")){
			data=returnJson("400", errorMes, returnData);
			return data;
		}
	    
		} catch (Exception e) {
			data=returnJson("400", "操作失败", e.getMessage());
		    return data;
		}
		returnData=obj.toString();
		data=returnJson(returnCode, returnMsg, returnData);
		return data;
	}
	public String queryRkDetailList(JSONObject json) {
		String data="";
		String returnMsg="";
		String returnCode="200";
		String returnData="";
		InterfaceLog log=storeInterfaceLog(null,"Android", "WMS", "入库清单明细查询", json.toString(), null);
		String jzfp =json.has("jzfp")?json.getString("jzfp"):"";
		String sql="from ASNDetail d where 1=1 and (d.asn.relatedBill2='"+jzfp+"' or d.asn.relatedBill1='"+jzfp+"' or d.asn.code='"+jzfp+"')";
		List<ASNDetail> ds=this.commonDao.findByQuery(sql);
	    	JSONArray  array = new JSONArray();
		for(ASNDetail ad:ds) {
			try {
				JSONObject d = new JSONObject();
				LotInfo info=ad.getLotInfo();
				String tax="保税";
				String tph="";
				if(info!=null){
	    			if(info.getPropC1()!=null&&info.getPropC1().equals("一般贸易")){
	    				tax="课税";
	    			}
	    			tph=info.getPropC2();
				}else{
					tax=ad.getTemperature();
				}
    			Item it=commonDao.get(Item.class, ad.getItem().getId());
    			d.put("d_id", ad.getId());
    			d.put("item_code", it.getCode());
				d.put("item_name", it.getName());
				d.put("tph",tph);
				d.put("tax", tax);
				d.put("quantity", (int)ad.getExpectedQuantity());
				d.put("put_qty",  (int)ad.getReceivedQuantity());
				array.add(d);
			} catch (Exception e) {
				data=returnJson("400", "操作失败", e.getMessage());
			    return data;
			}
		}
		returnData=array.toString();
		data=returnJson(returnCode, returnMsg, returnData);
		return data;
	}
	public String queryBhListKams(JSONObject json) {
		String data="";
		String returnMsg="";
		String returnCode="200";
		String returnData="";
		InterfaceLog log=storeInterfaceLog(null,"Android", "WMS", "发动机备货单列表查询", json.toString(), null);
    	String queryInfo=json.getString("queryInfo");
//    	String bhType=json.getString("bhType");
    	String hql="select d.pickTicket.id from "
    			+ " PickTicketDetail d  where d.pickTicket.warehouse.id=1 "
    			+ " and d.pickTicket.relatedBill1 in ('日出库单','成套出库')";
    	if(queryInfo!=null&&!queryInfo.equals("")){
    		hql+=" and (d.pickTicket.relatedBill2='"+queryInfo+"' or d.pickTicket.code='"+queryInfo+"')";
    	}else{
    		hql+=" and d.pickTicket.allocatedQuantity>d.pickTicket.pickedQuantity and d.pickTicket.shippedQuantity<=0";
    	}
    	hql+=" group by d.pickTicket.id order by d.pickTicket.id ";
//    	if(bhType.equals("QTCK")){
//    		hql+=" and p.billType.code='QTCK'";
//    	}else{
//    		hql+=" and p.billType.code!='QTCK'";
//    	}
    	List<Long> objs=this.commonDao.findByQuery(hql);
    	JSONArray  array = new JSONArray();
		for(Long o:objs) {
			try {
				JSONObject d = new JSONObject();
				PickTicket pt=this.commonDao.get(PickTicket.class, o);
				d.put("pt_id", pt.getId());
				d.put("order_date", DateUtil.formatDateYMD01ToStr(pt.getOrderDate()));
				d.put("order_quantity", pt.getOrderQuantity());
				d.put("allocated_quantity",pt.getAllocatedQuantity());
				d.put("picked_quantity", pt.getPickedQuantity());
				d.put("pt_code", pt.getCode());
				d.put("gw", pt.getRelatedBill3());
				d.put("sb", pt.getApplyDoc());
//				d.put("ybhxs", getPickBhxs(pt.getId())+"");
				array.add(d);
			} catch (Exception e) {
				data=returnJson("400", "操作失败", e.getMessage());
			    return data;
			}
		}
		returnData=array.toString();
		data=returnJson(returnCode, returnMsg, returnData);
		return data;
	}
	
	public String queryBhDetailKams(JSONObject json) {
		String data="";
		String returnMsg="";
		String returnCode="200";
		String returnData="";
		InterfaceLog log=storeInterfaceLog(null,"Android", "WMS", "发动机备货单明细查询", json.toString(), null);
    	Long pt_id=json.getLong("pt_id");
    	List<Object[]> objs=this.commonDao.findByQuery("select t.itemKey.item.code,t.itemKey.item.name,cast(t.planQuantityMU,int),"
    			+ "cast(t.movedQuantityMU,int),t.srcLoc.code  "
    			+ " from Task t where t.pickTicketDetail.pickTicket.id="+pt_id+" and t.planQuantityMU>0 "
    			+ "order by t.itemKey.item.code,t.srcLoc.code");
    	JSONArray  array = new JSONArray();
		for(Object[] o:objs) {
			try {
				int j=0;
				String item_code=o[j++].toString();
				String item_name=o[j++].toString();
				String dd_qty=o[j++].toString();
				String bh_qty=o[j++].toString();
				String src_loc=o[j++].toString();
				JSONObject d = new JSONObject();
				d.put("item_code", item_code);
				d.put("item_name", item_name);
				d.put("dd_qty", dd_qty);
				d.put("bh_qty", bh_qty);
				d.put("src_loc", src_loc);
				array.add(d);
			} catch (Exception e) {
				data=returnJson("400", "操作失败", e.getMessage());
			    return data;
			}
		}
		returnData=array.toString();
		data=returnJson(returnCode, returnMsg, returnData);
		return data;
	}
	
	
	public String queryFhDetailKams(JSONObject json) {
		String data="";
		String returnMsg="";
		String returnCode="200";
		String returnData="";
		InterfaceLog log=storeInterfaceLog(null,"Android", "WMS", "发货明细查询", json.toString(), null);
    	Long pt_id=json.getLong("pt_id");
    	String hql="select l.srcLPCode,l.itemKey.item.code,l.itemKey.item.name,cast(sum(l.movedQuantity),int),"
    			+ "cast(sum(l.shipQuantity),int),cast(sum(l.xbQuantity),int)   "
    			+ " from TaskLog l where l.task.pickTicketDetail.pickTicket.id="+pt_id+" and l.itemKey.item.beWeight=1"
    			+ " group by l.srcLPCode,l.itemKey.item.code";
    	List<Object[]> objs=this.commonDao.findByQuery(hql);
    	JSONArray  array = new JSONArray();
		for(Object[] o:objs) {
			try {
				int j=0;
				j++;
				String tph="";//o[j++].toString();
				String item_code=o[j++].toString();
				String item_name=o[j++].toString();
				String bh_qty=o[j++].toString();
				String fh_qty=o[j++].toString();
				String xb_qty=o[j++].toString();
				JSONObject d = new JSONObject();
				d.put("tph", tph);
				d.put("item_code", item_code);
				d.put("item_name", item_name);
				d.put("bh_qty", bh_qty);
				d.put("fh_qty", fh_qty);
				d.put("xb_qty", xb_qty);
				array.add(d);
			} catch (Exception e) {
				data=returnJson("400", "操作失败", e.getMessage());
			    return data;
			}
		}
		returnData=array.toString();
		data=returnJson(returnCode, returnMsg, returnData);
		return data;
	}
	
	public String queryXbjsDetail(JSONObject json) {
		String data="";
		String returnMsg="";
		String returnCode="200";
		String returnData="";
		InterfaceLog log=storeInterfaceLog(null,"Android", "WMS", "线边接收明细查询", json.toString(), null);
    	Long pt_id=json.getLong("pt_id");
    	String hql="select l.srcLPCode,l.itemKey.item.code,l.itemKey.item.name,"
    			+ "cast(sum(l.shipQuantity),int),cast(l.xbQuantity,int)   "
    			+ " from TaskLog l where l.task.pickTicketDetail.pickTicket.id="+pt_id 
    			+ " group by l.srcLPCode,l.itemKey.item.code "
    			+ " order BY l.srcLoc.code ";
    	List<Object[]> objs=this.commonDao.findByQuery(hql);
    	JSONArray  array = new JSONArray();
		for(Object[] o:objs) {
			try {
				int j=0;
				j++;
				String tph="";//o[j++].toString();
				String item_code=o[j++].toString();
				String item_name=o[j++].toString();
//				String bh_qty=o[j++].toString();
				String fh_qty=o[j++].toString();
				String xb_qty=o[j++].toString();
				JSONObject d = new JSONObject();
				d.put("tph", tph);
				d.put("item_code", item_code);
				d.put("item_name", item_name);
//				d.put("bh_qty", bh_qty);
				d.put("fh_qty", fh_qty);
				d.put("xb_qty", xb_qty);
				array.add(d);
			} catch (Exception e) {
				data=returnJson("400", "操作失败", e.getMessage());
			    return data;
			}
		}
		returnData=array.toString();
		data=returnJson(returnCode, returnMsg, returnData);
		return data;
	}
	public String scanXppTl(JSONObject json,String type) {
		String data="";
		String returnMsg="";
		String returnCode="200";
		String returnData="";
		String errorMes="";
		InterfaceLog log=storeInterfaceLog(null,"Android", "WMS", "扫描现品票投料", json.toString(), null);
		JSONObject obj= new JSONObject();
		try {
			String xpp=json.getString("xpp");
	    	String hql="select id from PrintXppRecord p where p.xpp='"+xpp+"'";
	    	List<Long> objs=this.commonDao.findByQuery(hql);
	    	if(objs.size()>0){
	    		
	    		PrintXppRecord p=this.commonDao.get(PrintXppRecord.class, objs.get(0));
	    		if(p.getTaskLog()==null){
		    		List<TaskLog> ls=this.commonDao.findByQuery("from TaskLog l where l.barCode='"+xpp+"'");
			    	if(ls.size()>0){
			    		p.setTaskLog(ls.get(0));
			    		this.commonDao.store(p);
			    	}
	    		}
				if(type.equals("HCTL")){
					if(p.getHcBy()!=null||p.getZzBy()!=null){
			    		errorMes = "现品票已投缓存／制造库位";
			    	}
				}
				if(type.equals("ZZTL")){
					if(p.getZzBy()!=null){
						errorMes = "现品票已投制造库位";
					}
				}
				if(errorMes==null||errorMes.equals("")){
					PickTicket pt=p.getPtd().getPickTicket();
					if(pt.getPackageQuantity()<pt.getShippedQuantity()){
						errorMes = "该出库单未全部接收";
					}else{
						String status="已收货";
						if(pt.getStatus().equals(PickTicketStatus.CLOSE)){
							status="已收货";
						}else if(pt.getStatus().equals(PickTicketStatus.FEEDING)){
							status="投料中";
						}else if(pt.getStatus().equals(PickTicketStatus.FEEDED)){
							status="投料完成";
						}else{
							status=pt.getStatus();
						}
						obj.put("ckd", pt.getRelatedBill2());
			    		obj.put("status", status);
			    		obj.put("item_code", p.getItem().getCode());
			    		obj.put("gw", pt.getRelatedBill3());
			    		obj.put("item_name", p.getItem().getName());
			    		obj.put("hckw_code", p.getPtd().getZzkw().getHckwCode()==null?"": p.getPtd().getZzkw().getHckwCode());
			    		obj.put("qty", p.getShsl());
			    		obj.put("sb", p.getPf().getBonded());
			    		obj.put("zzkw_code",p.getPtd().getZzkw().getCode());
			    		obj.put("src_inv_id","0");
			    		obj.put("xpp_id",p.getId());
			    		obj.put("task_log_id",p.getTaskLog()==null?"0":p.getTaskLog().getId());
			    		obj.put("total_tl_qty",(int)pt.getShippedQuantity());
			    		obj.put("tl_qty",(int)pt.getTlQty());
			    		obj.put("dd_tl_qty",(int)pt.getShippedQuantity()-(int)pt.getTlQty());
					}
				}
	    		
	    	}else{
	    		errorMes = "现品票不存在";
	    	}
    	
		} catch (Exception e) {
			data=returnJson("400", "操作失败", e.getMessage());
		    return data;
		}
		if(errorMes!=null&&!errorMes.equals("")){
    		data=returnJson("400", errorMes, returnData);
			return data;
    	}
		returnData=obj.toString();
		data=returnJson(returnCode, returnMsg, returnData);
		return data;
	}
	
	public String queryXbInv(JSONObject json) {
		String data="";
		String returnMsg="";
		String returnCode="200";
		String returnData="";
		InterfaceLog log=storeInterfaceLog(null,"Android", "WMS", "线边库存查询", json.toString(), null);
    	String xpp=json.getString("xpp");
    	String loc_code=json.getString("loc_code");
    	Boolean temp=Boolean.TRUE;
    	String hql="select inv.itemKey.item.code,inv.zone.code,inv.itemKey.item.name,"
    			+ "inv.location.code,inv.qtyOfMasterPack,inv.itemKey.pinfan.bonded,inv.zzkw.code,inv.zzkw.hckwCode "
    			+ " from Inventory inv where 1=1 and inv.barCode='XB' and inv.qtyOfMasterPack!=0 ";
    	if(xpp!=null&&!xpp.equals("")){
    		String item_code=xpp.substring(3, 13);
    		hql+=" and inv.itemKey.item.code='"+item_code+"'";
    		temp=Boolean.FALSE;
    	}
    	if(loc_code!=null&&!loc_code.equals("")){
    		hql+=" and inv.location.code='"+loc_code+"'";
    		temp=Boolean.FALSE;
    	}
    	hql+=" order by inv.zone.code,inv.itemKey.item.code ";
    	JSONArray  array = new JSONArray();
    	if(temp){
    		data=returnJson("400", "查询条件必填",  "查询条件必填");
		    return data;
    	}else{
    		try {
	    		List<Object[]> objs=this.commonDao.findByQuery(hql);
	    	
				for(Object[] o:objs) {
					int j=0;
					String item_code=o[j++].toString();
					String zone_code=o[j++].toString();
					String item_name=o[j++].toString();
					String loc_code1=o[j++].toString();
					String qty=o[j++].toString();
					String sb=o[j++].toString();
					String zzkw_code=o[6]==null?"":o[6].toString();
					String hckw_code=o[7]==null?"":o[7].toString();
					JSONObject d = new JSONObject();
					d.put("item_code", item_code);
					d.put("zone_code", zone_code);
					d.put("item_name", item_name);
					d.put("loc_code", loc_code1);
					d.put("qty", qty);
					d.put("sb", sb);
					d.put("zzkw_code", zzkw_code);
					d.put("hckw_code", hckw_code);
					array.add(d);
				}
			} catch (Exception e) {
				data=returnJson("400", "操作失败", e.getMessage());
			    return data;
			}
    	}
		returnData=array.toString();
		data=returnJson(returnCode, returnMsg, returnData);
		return data;
	}
	
	public String queryKamsInv(JSONObject json) {
		String data="";
		String returnMsg="";
		String returnCode="200";
		String returnData="";
		InterfaceLog log=storeInterfaceLog(null,"Android", "WMS", "KAMS库存查询", json.toString(), null);
    	String item_code=json.getString("item_code");
    	String loc_code=json.getString("loc_code");
    	Boolean temp=Boolean.TRUE;
    	String hql="select inv.itemKey.item.code,inv.zone.code,inv.itemKey.item.name,"
    			+ "inv.location.code,inv.qtyOfMasterPack,inv.itemKey.pinfan.bonded,'','' "
    			+ " from Inventory inv where 1=1 and inv.zone.code not like '%SL' and inv.qtyOfMasterPack!=0 ";
    	if(item_code!=null&&!item_code.equals("")){
    		if(item_code.length()==82){
    			item_code=item_code.substring(3, 13);
    		}
    		hql+=" and inv.itemKey.item.code='"+item_code+"'";
    		temp=Boolean.FALSE;
    	}
    	if(loc_code!=null&&!loc_code.equals("")){
    		hql+=" and (inv.location.code='"+loc_code+"' or inv.location.barCode='"+loc_code+"')";
    		temp=Boolean.FALSE;
    	}
    	hql+=" order by inv.zone.code,inv.itemKey.item.code ";
    	JSONArray  array = new JSONArray();
    	if(temp){
    		data=returnJson("400", "查询条件必填",  "查询条件必填");
		    return data;
    	}else{
    		try {
	    		List<Object[]> objs=this.commonDao.findByQuery(hql);
	    	
				for(Object[] o:objs) {
					int j=0;
					item_code=o[j++].toString();
					String zone_code=o[j++].toString();
					String item_name=o[j++].toString();
					String loc_code1=o[j++].toString();
					String qty=o[j++].toString();
					String sb=o[j++].toString();
					String zzkw_code=o[6]==null?"":o[6].toString();
					String hckw_code=o[7]==null?"":o[7].toString();
					JSONObject d = new JSONObject();
					d.put("item_code", item_code);
					d.put("zone_code", zone_code);
					d.put("item_name", item_name);
					d.put("loc_code", loc_code1);
					d.put("qty", qty);
					d.put("sb", sb);
					d.put("zzkw_code", zzkw_code);
					d.put("hckw_code", hckw_code);
					array.add(d);
				}
			} catch (Exception e) {
				data=returnJson("400", "操作失败", e.getMessage());
			    return data;
			}
    	}
		returnData=array.toString();
		data=returnJson(returnCode, returnMsg, returnData);
		return data;
	}
	
	@Override
	public InterfaceLog storeInterfaceLog(String request,String fromSys,String toSys,String type,String content,Long id) {
		InterfaceLog log=EntityFactory.getEntity(InterfaceLog.class);
		log.setRequest(request);
		log.setFromSYS(fromSys);
		log.setToSYS(toSys);
		log.setType(type);
		log.setRequestContent(content);
		log.setRequestTime(new Date());
		log.setLogID(id);
		log.setStatus("OPEN");
		commonDao.store(log);
		return log;
	}
	public String scanFhTph(JSONObject json) {
		String data="";
		String returnMsg="";
		String returnCode="200";
		String returnData="";
		String errorMes="";
		InterfaceLog log=storeInterfaceLog(null,"Android", "WMS", "发动机发货托盘号扫描", json.toString(), null);
		JSONObject obj= new JSONObject();
		try {
//			Long pt_id=null;//json.getLong("pt_id");
			String tph=json.getString("tph");
	    	List<TaskLog> logs=this.commonDao.findByQuery("from TaskLog l where (l.task.pickTicketDetail.pickTicket.code='"+tph+"' or l.task.pickTicketDetail.pickTicket.relatedBill2='"+tph+"')"
	    			+ " and l.shipQuantity<=0 and l.itemKey.item.beWeight=1");
	    	if(logs.size()>0){
	    		TaskLog l=logs.get(0);
	    		PickTicket pt=l.getTask().getPickTicketDetail().getPickTicket();
	    		Long pt_id=pt.getId();
	    		String ship_type="tph";
	    		if(pt.getCode().equals(tph)){
	    			tph=null;
	    			ship_type="ckd";
	    		}
	    		obj.put("sku_qty", getPickTpSku(pt_id));
	    		obj.put("tp_xs", logs.size());
	    		obj.put("pt_id", pt_id);
	    		obj.put("ship_type", ship_type);
	    	}else{
	    		errorMes = "发货号不存在或已出库";
	    	}
    	
		} catch (Exception e) {
			data=returnJson("400", "操作失败", e.getMessage());
		    return data;
		}
		if(errorMes!=null&&!errorMes.equals("")){
    		data=returnJson("400", errorMes, returnData);
			return data;
    	}
		returnData=obj.toString();
		data=returnJson(returnCode, returnMsg, returnData);
		return data;
	}
	
	public String scanXbTph(JSONObject json) {
		String data="";
		String returnMsg="";
		String returnCode="200";
		String returnData="";
		String errorMes="";
		InterfaceLog log=storeInterfaceLog(null,"Android", "WMS", "线边托盘号扫描", json.toString(), null);
		JSONObject obj= new JSONObject();
		try {
//			Long pt_id=json.getLong("pt_id");
			String tph=json.getString("tph");
			//操作完成支持查询
			List<TaskLog> logs=this.commonDao.findByQuery("from TaskLog l where (l.task.pickTicketDetail.pickTicket.code='"+tph+"' or l.task.pickTicketDetail.pickTicket.relatedBill2='"+tph+"' or l.srcLPCode='"+tph+"')");
//			List<TaskLog> logs=this.commonDao.findByQuery("from TaskLog l where (l.task.pickTicketDetail.pickTicket.code='"+tph+"' or l.srcLPCode='"+tph+"') and l.xbQuantity<=0");
	    	if(logs.size()>0){
	    		TaskLog l=logs.get(0);
	    		PickTicket pt=l.getTask().getPickTicketDetail().getPickTicket();
	    		Long pt_id=pt.getId();
	    		String ship_type="tph";
	    		if(pt.getCode().equals(tph)||pt.getRelatedBill2().equals(tph)){
	    			tph=null;
	    			ship_type="ckd";
	    		}
	    		String ckkq="";
	    		if( pt.getZone2()!=null){
	    			ckkq=pt.getZone2().getCode();
	    		}
	    		String rkkq="";
	    		if( pt.getZone1()!=null){
	    			rkkq=pt.getZone1().getCode();
	    		}
	    		String status=pt.getStatus();
	    		if(status.equals("SHIP_ALL")){
	    			status="已出货";
	    		}else if(status.equals("CLOSE")){
	    			status="已收货";
	    		}
	    		String sql="select distinct(t.itemKey.id) from TaskLog t where t.task.pickTicketDetail.pickTicket.id="+pt_id+" and t.movedQuantity>0 ";
				if(tph!=null){
					sql+=" and t.srcLPCode='"+tph+"'";
				}
				List<Task> ts=this.commonDao.findByQuery(sql);
	    		obj.put("pfs", ts.size());
	    		obj.put("ckd",pt.getCode());
	    		obj.put("status",status);
	    		obj.put("ckkq", ckkq);
	    		obj.put("rkkq", rkkq);
	    		obj.put("hs", logs.size());
	    		obj.put("pt_id", pt_id);
	    		obj.put("ship_type", ship_type);
	    	}else{
	    		errorMes = "发货号不存在或状态不对";
	    	}
    	
		} catch (Exception e) {
			data=returnJson("400", "操作失败", e.getMessage());
		    return data;
		}
		if(errorMes!=null&&!errorMes.equals("")){
    		data=returnJson("400", errorMes, returnData);
			return data;
    	}
		returnData=obj.toString();
		data=returnJson(returnCode, returnMsg, returnData);
		return data;
	}
	
	//托盘箱数
		public int getPickTpxs(Long pt_id,String tph){
			String sql="select t.id from TaskLog t where t.task.pickTicketDetail.pickTicket.id="+pt_id+" and t.movedQuantity>0 ";
			if(tph!=null){
				sql+=" and t.srcLPCode='"+tph+"'";
			}
			List<Task> ts=this.commonDao.findByQuery(sql);
			return ts.size();
		}
		//托盘SKU品种数
		public int getPickTpSku(Long pt_id){
			String sql="select distinct(t.itemKey.id) from TaskLog t where t.task.pickTicketDetail.pickTicket.id="+pt_id+" and t.movedQuantity>0 "
					+ "and t.itemKey.item.beWeight=1";
			List<Task> ts=this.commonDao.findByQuery(sql);
			return ts.size();
		}
	
	private String  returnJson(String returnCode,String returnMsg,String returnData){
		JSONObject returnJson = new JSONObject();
		if(returnCode.equals("200")){
			returnCode="1";
		}else{
			returnCode="0";
		}
		returnJson.put("status",returnCode);
		returnJson.put("msg",returnMsg);
		returnJson.put("data",returnData);
		String data=returnJson.toString();
		return data;
	}
	
	private String conventNullStr(Object obj){
		if(obj==null){
			return null;
		}else{
			String str=obj.toString();
			if(str.equals("null")){
				return null;
			}else{
				return str;
			}
		}
		
	}
	
	private Date conventNullDate(Object obj){
		if(obj==null){
			return null;
		}else{
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
			String str=obj.toString();
			Date date=null;
			if(str.equals("null")){
				return null;
			}else{
				try {
					date= sdf.parse(str);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return date;
		}
		
	}
	
	private double conventNullStrDouble(Object obj){
		String str=obj.toString();
		if(str.equals("null")){
			return 0;
		}else{
			return Double.parseDouble(str);
		}
	}
	 
}
