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.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.interfaceLog.InterfaceLog;
import com.dev.swms.server.model.inventory.Task;
import com.dev.swms.server.model.receiving.ASNDetail;
import com.dev.swms.server.model.shipping.PickTicket;
import com.dev.swms.server.model.shipping.PickTicketDetail;
import com.dev.swms.server.service.interfaceLog.InterfaceManager;
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 PickingServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected static ApplicationContext ac;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PickingServlet() {
        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("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("pickKamsForApp")){//扫描现品票备货
        		  result=pickKamsForApp(json);
        	 }else if(methodType.equals("confirmShipKams")){//发运确认
       		  	  result=confirmShipKams(json);
        	 }else if(methodType.equals("updateXppPick")){//修改现品票
      		  	  result=updateXppPick(json);
	       	 }else{
        		  InterfaceManager app = (InterfaceManager) ac.getBean("interfaceManager");
      	          result=app.readJsonCk(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 updateXppPick(JSONObject json) {
		String data="";
		String returnMsg="";
		String returnCode="400";
		String returnData="";
		CommonDao commonDao = (CommonDao) ac.getBean("commonDao");
//		String xpp=json.getString("xpp");
		String user_name=json.getString("user_name");
    	Long pt_id=json.getLong("pt_id");
    	Long xpp_id=json.getLong("xpp_id");
    	Long log_id=json.getLong("log_id");
    	Double qty=json.getDouble("qty");
	    JSONObject obj= new JSONObject();
//	    InterfaceManager app = (InterfaceManager) ac.getBean("interfaceManager");
	    PickKamsManager ptManager = (PickKamsManager) ac.getBean("pickKamsManager");
		try{
			
			ptManager.pickedBack(pt_id, log_id, qty, user_name, xpp_id);
			PickTicket pt=commonDao.get(PickTicket.class, pt_id);
			obj.put("ybhs", pt.getPickedQuantity());
			returnMsg="修改成功";
			returnCode="200";
//			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 pickKamsForApp(JSONObject json) {
		String data="";
		String returnMsg="";
		String returnCode="400";
		String returnData="";
		CommonDao commonDao = (CommonDao) ac.getBean("commonDao");
		String xpp=json.getString("xpp");
		String tph=json.getString("tph");
		String bhr=json.getString("bhr");
		String user_name=json.getString("user_name");
    	Long pt_id=json.getLong("pt_id");
//    	Long ptd_id=json.getLong("ptd_id");
//    	Long task_id=json.getLong("task_id");
//    	Long xpp_id=json.getLong("xxp_id");
//    	double qty=json.getDouble("kysl");
	    JSONObject obj= new JSONObject();
//	    InterfaceManager app = (InterfaceManager) ac.getBean("interfaceManager");
	    PickKamsManager ptManager = (PickKamsManager) ac.getBean("pickKamsManager");
		try{
			obj=ptManager.pickKamsForApp(pt_id,xpp,user_name , tph,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 pickConfirm(JSONObject json) {
		String data="";
		String returnMsg="";
		String returnCode="400";
		String returnData="";
		CommonDao commonDao = (CommonDao) ac.getBean("commonDao");
    	Long pt_id=json.getLong("pt_id");
    	String bhr=json.getString("bhr");
	    JSONObject obj= new JSONObject();
//	    InterfaceManager app = (InterfaceManager) ac.getBean("interfaceManager");
	    PickTicketManager ptManager = (PickTicketManager) ac.getBean("pickTicketManager");
		try{
			ptManager.pickConfirm(pt_id,bhr,null);
			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="200";
		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 ship_type=json.getString("ship_type");
	    	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";
	    		if(ship_type.equals("tph")){
	    			hql+= " and l.srcLPCode='"+tph+"' ";
	    		}
	    		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;
	}
	
	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)
	 */
	
}
