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.receiving.ASNDetail;
import com.dev.swms.server.service.interfaceLog.InterfaceManager;
import com.dev.swms.server.service.receiving.ASNManager;

import net.sf.json.JSONObject;

/**
 * Servlet implementation class LoginAppServlet
 */
public class ASNReceiveServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected static ApplicationContext ac;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ASNReceiveServlet() {
        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("scanRkDstLoc")){//扫描库位上架
        		  result=scanRkDstLoc(json);
        	 }else{
        		  InterfaceManager app = (InterfaceManager) ac.getBean("interfaceManager");
      	          result=app.readJsonKams(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 xpp =json.has("xpp")?json.getString("xpp"):"";
		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 jzfp =json.has("jzfp")?json.getString("jzfp"):"";
		String tph =json.has("tph")?json.getString("tph"):"";
		if(tph.substring(0, 2).equals("98")){
    		tph=tph.replaceFirst("98", "");
    	}else if(tph.substring(0, 2).equals("90")){
    		tph=tph.replaceFirst("90", "");
    	}
		String oper=json.has("user_name")?json.getString("user_name"):"";
	    JSONObject obj= new JSONObject();
	    InterfaceManager app = (InterfaceManager) ac.getBean("interfaceManager");
			if(xpp!=null&&!xpp.equals("")&&xpp.length()==82){
				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.confirmReceivingKamsApp(new Long(d_id), dst_loc, new Long(pf_id), Double.parseDouble(qty), xpp, 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 lotInfo.propC2='"+tph+"'");
						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]);
						obj.put("put_xs",app.getPutXs(tph));
						InterfaceLog log=app.storeInterfaceLog(d_id,"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;
	}
	
	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)
	 */
	
}
