package com.dev.swms.server.web.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.dev.energy.server.dao.CommonDao;
import com.dev.swms.server.model.base.Item;
import com.dev.swms.server.model.base.Location;
import com.dev.swms.server.model.base.LocationType;
import com.dev.swms.server.model.base.Worker;
import com.dev.swms.server.model.interfaceLog.InterfaceLog;
import com.dev.swms.server.model.inventory.Task;
import com.dev.swms.server.model.inventory.TaskLog;
import com.dev.swms.server.model.receiving.ASNDetail;
import com.dev.swms.server.model.shipping.PickTicketDetail;
import com.dev.swms.server.service.interfaceLog.InterfaceManager;
import com.dev.swms.server.service.interfaceLog.XbtlManager;
import com.dev.swms.server.service.inventory.InventoryManager;
import com.dev.swms.server.service.receiving.ASNManager;
import com.dev.swms.server.service.shipping.PickKamsManager;
import com.dev.swms.server.service.shipping.PickTicketManager;

import net.sf.json.JSONObject;

/**
 * Servlet implementation class LoginAppServlet
 */
public class XbtlServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected static ApplicationContext ac;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public XbtlServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    public void init(ServletConfig sc) throws ServletException {
		super.init(sc);
		ac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc.getServletContext());
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(request, response);
	}
	 private String reqMailbox(HttpServletRequest request) throws IOException {
	        // 读取请求内容
	        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
	        String line = null;
	        StringBuilder sb = new StringBuilder();
	        while ((line = br.readLine()) != null) {
	            sb.append(line);
	        }
	        // 将资料解码
	        return sb.toString();
	 }
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("xbtlServlet join   "+new Date());
		response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        // 返回JSON数据
        JSONObject resultObject = new JSONObject();
        // 获取post提交的回复案件的信息
        String postResult = reqMailbox(request);
        String result="";
        if(postResult!=null&&!"".equals(postResult)){
        	//判断类型，根据不同类型进入不同方法
        	JSONObject json = JSONObject.fromObject(postResult);
        	System.out.println(json.toString());
        	String methodType=json.getString("methodType");
        	if(methodType.equals("scanRkDstLoc")){//收货确认
      		  	  result=scanRkDstLoc(json);
	       	 }else if(methodType.equals("pickKamsForApp")){//发动机二维码备货确认
     		  	  result=pickKamsForApp(json);
	       	 }else if(methodType.equals("pickKamsForFdj")){//发动机机号备货确认
    		  	  result=pickKamsForFdj(json);
	       	 }else if(methodType.equals("confirmShipKams")){//发货确认
    		  	  result=confirmShipKams(json);
	       	 }else if(methodType.equals("confirmXbjs")){//线边接收
	       		 result=confirmXbjs(json);
	       	 }else if(methodType.equals("moveHctl")){//缓存库位投料
	       		 result=moveHctl(json,null);
	       	 }else if(methodType.equals("moveZztl")){//制造库位投料
	       		 result=moveZztl(json,null);
	       	 }else if(methodType.equals("updatePwd")){//更改密码
	       		 result=updatePwd(json,null);
	       	 }else{
	       		XbtlManager app = (XbtlManager) ac.getBean("xbtlManager");
      	        result=app.readJson(postResult);
	        }
        }else{
        	resultObject.put("status", -1);
        	resultObject.put("msg","接口信息：空的传值");
        	resultObject.put("data",postResult);
        	result=resultObject.toString();
        }
      //实现逻辑...
        response.getOutputStream().write(result.toString().getBytes("UTF-8"));
        System.out.println(result);
        System.out.println("end   "+new Date());
	}
	
	public synchronized String scanRkDstLoc(JSONObject json) {
		String data="";
		String returnMsg="";
		String returnCode="400";
		String returnData="";
//		String errorMes="";
		CommonDao commonDao = (CommonDao) ac.getBean("commonDao");
		//InterfaceLog log=storeInterfaceLog(null,"Android", "WMS", "入库现品票收货确认", json.toString(), commonDao);
		String dst_loc =json.has("dst_loc")?json.getString("dst_loc"):"";
		String d_id =json.has("d_id")?json.getString("d_id"):"";
		String pf_id =json.has("pf_id")?json.getString("pf_id"):"";
		String qty =json.has("qty")?json.getString("qty"):"";
		String fdj =json.has("fdj")?json.getString("fdj"):"";
		String item_code =json.has("item_code")?json.getString("item_code"):"";
		String oper=json.has("user_name")?json.getString("user_name"):"";
		String ewm=json.has("ewm")?json.getString("ewm"):"";
	    JSONObject obj= new JSONObject();
	    InterfaceManager app = (InterfaceManager) ac.getBean("interfaceManager");
			if((ewm!=null&&!ewm.equals(""))||(fdj!=null&&!fdj.equals(""))){
				List<Location> ls=commonDao.findByQuery("from Location l where (l.code='"+dst_loc+"' or l.barCode='"+dst_loc+"') and l.id!=7104 and l.flagStatus!='WAIT_ADD'" );
				if(ls.size()<=0&&dst_loc!=null&&!dst_loc.equals("")){
					returnMsg = dst_loc+"库位不存在";
				}else{
					try{
						ASNManager asnManager = (ASNManager) ac.getBean("asnManager");
						if(item_code!=null&&!item_code.equals("")){
							ewm=item_code+fdj;
						}
						asnManager.confirmReceivingKamsApp(new Long(d_id), dst_loc, new Long(pf_id), Double.parseDouble(qty), ewm, new Date(), oper);
						returnMsg="收货成功";
						returnCode="200";
						List<Object[]> qtys=commonDao.findByQuery("select  sum(d.expectedQuantity), sum(d.receivedQuantity),sum(d.expectedQuantity-d.receivedQuantity) from ASNDetail d where 1=1 and d.id='"+d_id+"'");
						obj.put("tp_qty",qtys.get(0)[0]);
						obj.put("tp_put_qty",qtys.get(0)[1]);
						obj.put("tp_sysl",qtys.get(0)[2]);
						InterfaceLog log=app.storeInterfaceLog(null,"Android", "WMS", "发动机入库上架确认", json.toString(), null);
					}catch(Exception e){
						returnMsg=e.getMessage();
					}
				 }
			}else{
				returnMsg = "发动机二维码不正确";
			}
	    
//		} catch (Exception e) {
//			returnMsg=e.toString();
//		}
		returnData=obj.toString();
		data=returnJson(returnCode, returnMsg, returnData);
		return data;
	}
	
	public synchronized String scanFdjsRkDstLoc(JSONObject json) {
		String data="";
		String returnMsg="";
		String returnCode="400";
		String returnData="";
//		String errorMes="";
		CommonDao commonDao = (CommonDao) ac.getBean("commonDao");
		//InterfaceLog log=storeInterfaceLog(null,"Android", "WMS", "入库现品票收货确认", json.toString(), commonDao);
		String dst_loc =json.has("dst_loc")?json.getString("dst_loc"):"";
		String d_id =json.has("d_id")?json.getString("d_id"):"";
		String fdj =json.has("fdj")?json.getString("fdj"):"";
		String pf_id =json.has("pf_id")?json.getString("pf_id"):"";
		String oper=json.has("user_name")?json.getString("user_name"):"";
	    JSONObject obj= new JSONObject();
	    InterfaceManager app = (InterfaceManager) ac.getBean("interfaceManager");
			if(fdj!=null&&!fdj.equals("")){
				List<Location> ls=commonDao.findByQuery("from Location l where (l.code='"+dst_loc+"' or l.barCode='"+dst_loc+"') and l.id!=7104 and l.flagStatus!='WAIT_ADD'" );
				if(ls.size()<=0&&dst_loc!=null&&!dst_loc.equals("")){
					returnMsg = dst_loc+"库位不存在";
				}else{
					try{
						ASNManager asnManager = (ASNManager) ac.getBean("asnManager");
						asnManager.confirmReceivingKamsAppFdjs(new Long(d_id), new Long(pf_id), dst_loc,fdj, oper);
						returnMsg="收货成功";
						returnCode="200";
						List<Object[]> qtys=commonDao.findByQuery("select  sum(d.expectedQuantity), sum(d.receivedQuantity),sum(d.expectedQuantity-d.receivedQuantity) from ASNDetail d where 1=1 and d.id='"+d_id+"'");
						obj.put("tp_qty",qtys.get(0)[0]);
						obj.put("tp_put_qty",qtys.get(0)[1]);
						obj.put("tp_sysl",qtys.get(0)[2]);
						InterfaceLog log=app.storeInterfaceLog(null,"Android", "WMS", "发动机入库上架确认", json.toString(), null);
					}catch(Exception e){
						returnMsg=e.getMessage();
					}
				 }
			}else{
				returnMsg = "发动机二维码不正确";
			}
	    
//		} catch (Exception e) {
//			returnMsg=e.toString();
//		}
		returnData=obj.toString();
		data=returnJson(returnCode, returnMsg, returnData);
		return data;
	}
	
	public synchronized String pickKamsForApp(JSONObject json) {
		String data="";
		String returnMsg="";
		String returnCode="400";
		String returnData="";
		CommonDao commonDao = (CommonDao) ac.getBean("commonDao");
		String ewm=json.getString("ewm");
		String bhr=json.getString("bhr");
		String user_name=json.getString("user_name");
    	Long pt_id=json.getLong("pt_id");
	    JSONObject obj= new JSONObject();
//	    InterfaceManager app = (InterfaceManager) ac.getBean("interfaceManager");
	    PickKamsManager ptManager = (PickKamsManager) ac.getBean("pickKamsManager");
		try{
			obj=ptManager.pickKamsForFdj(pt_id, ewm, user_name,bhr);
			returnMsg="备货成功";
			returnCode="200";
//			List<Object[]> qtys=commonDao.findByQuery("select  sum(d.allocatedQuantity), sum(d.pickedQuantity), sum(d.caCoefficient) "
//					+ " from PickTicketDetail d where 1=1 and d.pickTicket.id="+pt_id);
//			String sql="select t.id from TaskLog t where  t.task.pickTicketDetail.pickTicket.id="+pt_id;
//			List ts=commonDao.findByQuery(sql);
//			obj.put("cds",qtys.get(0)[0]);
//			obj.put("ybhs",qtys.get(0)[1]);
//			obj.put("ybhxs",ts.size());
//			InterfaceLog log=app.storeInterfaceLog(null,"Android", "WMS", "出库现品票备货确认", json.toString(), null);
		}catch(Exception e){
			returnMsg=e.getMessage();
		}
		returnData=obj.toString();
		data=returnJson(returnCode, returnMsg, returnData);
		return data;
	}
	
	public synchronized String pickKamsForFdj(JSONObject json) {
		String data="";
		String returnMsg="";
		String returnCode="400";
		String returnData="";
		CommonDao commonDao = (CommonDao) ac.getBean("commonDao");
		String fdj=json.getString("fdj");
		String item_code=json.getString("item_code");
		String bhr=json.getString("bhr");
		String user_name=json.getString("user_name");
    	Long pt_id=json.getLong("pt_id");
	    JSONObject obj= new JSONObject();
	    PickKamsManager ptManager = (PickKamsManager) ac.getBean("pickKamsManager");
		try{
			String ewm=item_code+fdj;
			obj=ptManager.pickKamsForFdj(pt_id, ewm, user_name,bhr);
			returnMsg="备货成功";
			returnCode="200";

		}catch(Exception e){
			returnMsg=e.getMessage();
		}
		returnData=obj.toString();
		data=returnJson(returnCode, returnMsg, returnData);
		return data;
	}
	
	public String confirmShipKams(JSONObject json) {
		String data="";
		String returnMsg="";
		String returnCode="400";
		String returnData="";
		String errorMes="";
		CommonDao commonDao = (CommonDao) ac.getBean("commonDao");
		InterfaceManager app = (InterfaceManager) ac.getBean("interfaceManager");
	    PickKamsManager ptManager = (PickKamsManager) ac.getBean("pickKamsManager");
		
		JSONObject obj= new JSONObject();
		try {
	    	Long pt_id=json.getLong("pt_id");
	    	String cph=json.getString("cph");
	    	String tph=json.getString("tph");
	    	String user_name=json.getString("user_name");
	    	if(cph==null||cph.equals("")){
	    		errorMes = "车牌号必填";
	    	}else if(tph==null||tph.equals("")){
	    		errorMes = "发货单号必填";
	    	}else{
	    		String hql="select id from TaskLog l where l.task.pickTicketDetail.pickTicket.id="+pt_id+" and l.shipQuantity<=0 and l.itemKey.item.beWeight=1";
	    		List<Long> ids=commonDao.findByQuery(hql);
		    	//全部发运
	    		if(ids.size()<=0){
	    			errorMes = "发动机全部出库";
	    		}else{
	    			try{
	    				ptManager.shipConfirmTphKAMS(pt_id,ids, cph,user_name);
	    				returnMsg="发货成功";
	    				returnCode="200";
	    				InterfaceLog log=app.storeInterfaceLog(null,"Android", "WMS", "发货确认", json.toString(), null);
	    			}catch(Exception e){
	    				returnMsg=e.getMessage();
	    			}
	    		}
	    	}
		} 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 confirmXbjs(JSONObject json) {
		String data="";
		String returnMsg="";
		String returnCode="400";
		String returnData="";
		String errorMes="";
		CommonDao commonDao = (CommonDao) ac.getBean("commonDao");
		InterfaceManager app = (InterfaceManager) ac.getBean("interfaceManager");
	    PickKamsManager ptManager = (PickKamsManager) ac.getBean("pickKamsManager");
		JSONObject obj= new JSONObject();
		try {
			Long pt_id=json.getLong("pt_id");
	    	String tph=json.getString("tph");
	    	String user_name=json.getString("user_name");
	    	if(tph==null||tph.equals("")){
	    		errorMes = "发货单号／托盘号必填";
	    	}else{
	    		List<Long> ids=commonDao.findByQuery("select id from TaskLog l where "
	    				+ " l.task.pickTicketDetail.pickTicket.id="+pt_id+" and (l.task.pickTicketDetail.pickTicket.code='"+tph+"' or l.srcLPCode='"+tph+"' or "
	    						+ "l.task.pickTicketDetail.pickTicket.relatedBill2='"+tph+"') and l.shipQuantity>0 and l.xbQuantity<=0");
	    		if(ids.size()<=0){
	    			errorMes = "无待接收数据";
	    		}else{
	    			try{
	    				ptManager.xbjs(pt_id,tph,ids,user_name);
	    				returnMsg="线边接收成功";
	    				returnCode="200";
	    				InterfaceLog log=app.storeInterfaceLog(null,"Android", "WMS", "线边接收确认", json.toString(), null);
	    			}catch(Exception e){
	    				returnMsg=e.getMessage();
	    			}
	    		}
	    	}
		} 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 moveZztl(JSONObject json,String type) {
		String data="";
		String returnMsg="";
		String returnCode="400";
		String returnData="";
		String errorMes="";
		CommonDao commonDao = (CommonDao) ac.getBean("commonDao");
		InterfaceManager app = (InterfaceManager) ac.getBean("interfaceManager");
		InventoryManager inventoryManager = (InventoryManager) ac.getBean("inventoryManager");
		JSONObject obj= new JSONObject();
		try {
			Long task_log_id=json.getLong("task_log_id");
	    	Long xpp_id=json.getLong("xpp_id");
	    	String user_name=json.getString("user_name");
	    	String zzkw=json.getString("zzkw");
	    	double qty=json.getDouble("qty");
			try{
				obj=inventoryManager.moveInvtl(null, zzkw, qty, user_name, xpp_id, task_log_id, LocationType.PROCESS, "制造库位投料");
				returnMsg="制造库位投料成功";
				returnCode="200";
				InterfaceLog log=app.storeInterfaceLog(null,"Android", "WMS", "制造库位投料", json.toString(), null);
			}catch(Exception e){
				returnMsg=e.getMessage();
			}
		} 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 moveHctl(JSONObject json,String type) {
		String data="";
		String returnMsg="";
		String returnCode="400";
		String returnData="";
		String errorMes="";
		CommonDao commonDao = (CommonDao) ac.getBean("commonDao");
		InterfaceManager app = (InterfaceManager) ac.getBean("interfaceManager");
		InventoryManager inventoryManager = (InventoryManager) ac.getBean("inventoryManager");
		JSONObject obj= new JSONObject();
		try {
			Long task_log_id=json.getLong("task_log_id");
	    	Long xpp_id=json.getLong("xpp_id");
	    	String user_name=json.getString("user_name");
	    	String hckw=json.getString("hckw");
	    	double qty=json.getDouble("qty");
			try{
				obj=inventoryManager.moveInvtl(null, hckw, qty, user_name, xpp_id, task_log_id, LocationType.HCKW, "缓存库位投料");
				returnMsg="缓存库位投料成功";
				returnCode="200";
				InterfaceLog log=app.storeInterfaceLog(null,"Android", "WMS", "缓存库位投料", json.toString(), null);
			}catch(Exception e){
				returnMsg=e.getMessage();
			}
		} 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 updatePwd(JSONObject json,String type) {
		String data="";
		String returnMsg="";
		String returnCode="400";
		String returnData="";
		String errorMes="";
		CommonDao commonDao = (CommonDao) ac.getBean("commonDao");
		InterfaceManager app = (InterfaceManager) ac.getBean("interfaceManager");
		JSONObject obj= new JSONObject();
		try {
			String user_name=json.getString("user_name");
	    	String old_pwd=json.getString("old_pwd");
	    	String new_pwd=json.getString("new_pwd");
			try{
				String hql="FROM Worker d WHERE (d.code=:code ) AND d.passWord = :passWord";
				List<Worker> ws =commonDao.findByQuery(hql,
						new String[] { "code","passWord" }, new Object[] { user_name,old_pwd });
				if(ws.size()>0){
					Worker w=ws.get(0);
					returnMsg="修改密码成功";
					returnCode="200";
					w.setPassWord(new_pwd);
					commonDao.store(w);
				}else{
					returnMsg="账号或密码不正确";
				}
				
				InterfaceLog log=app.storeInterfaceLog(null,"Android", "WMS", "修改密码", json.toString(), null);
			}catch(Exception e){
				returnMsg=e.getMessage();
			}
		} 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;
	}
	
	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;
	}


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	
}
