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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
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.apache.commons.codec.digest.DigestUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.dev.energy.server.dao.CommonDao;
import com.dev.energy.server.model.EntityFactory;
import com.dev.energy.server.model.security.User;
import com.dev.swms.server.model.base.Item;
import com.dev.swms.server.model.base.ItemRelation;
import com.dev.swms.server.model.base.Warehouse;
import com.dev.swms.server.model.base.Worker;
import com.dev.swms.server.model.shipping.PlanShipDetail;
import com.dev.swms.server.utils.DateUtil;

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

/**
 * Servlet implementation class LoginAppServlet
 */
public class ScanDomesticServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected static ApplicationContext ac;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ScanDomesticServlet() {
        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);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		CommonDao commonDao = (CommonDao) ac.getBean("commonDao");
		request.setCharacterEncoding("utf-8");
		BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));//post方式传递读取字符流
		String jsonStr = null;
		StringBuilder result = new StringBuilder();
		 PrintWriter out = null;
		try {
			while ((jsonStr = reader.readLine()) != null) {
				result.append(jsonStr);
			}
			System.out.println("result:"+result.toString());
			JSONObject json= JSONObject.fromObject(result.toString());
			System.out.println("==========KEY采集========"+new Date());
			String key =json.has("key")?json.getString("key"):""; 
			String user_id = json.has("user_id")?json.getString("user_id"):""; 
			String user_name = json.has("user_name")?json.getString("user_name"):""; 
			String w_id = json.has("w_id")?json.getString("w_id"):""; 
			String u_type = json.has("u_type")?json.getString("u_type"):""; 
			String msg = "";
			String status ="0";
			String data="";
			JSONObject rJson = new JSONObject();
			if(key!=null&&!key.equals("")&&key.length()==85){
				List<PlanShipDetail> sds=commonDao.findByQuery("from PlanShipDetail p where p.key='"+key+"'");
				if(sds.size()<=0){
					 JSONObject obj = new JSONObject();
					// gys	mh	pf	cpmc	hz	srs	xs	shsl	djrq	ddbh	bz	nrzsr
					 String gys=key.substring(52,64).trim();
					 String mh="";
					 String pf=key.substring(3, 13);
					 String hz="";
					 int srs=0;
					 int xs=0;
					 int shsl=Integer.parseInt(key.substring(45, 52));
					 String djrq=DateUtil.formatDateYMD01ToStr(new Date());
					 String ddbh=key.substring(29, 37);
					 String nrzsr=key.substring(37, 45);
					 String nrcs=key.substring(64, 70);
					 List<Item> its=commonDao.findByQuery("from Item p where p.code='"+pf+"' and p.warehouse.id=1020 ");
					 if(its.size()<=0){
						 msg = pf+"品番不存在";
					 }else{
						 Item it=its.get(0);
						 List<ItemRelation> irs=commonDao.findByQuery("from ItemRelation p where p.item.id="+it.getId()+" and p.key='"+pf+nrcs+"'");
						 if(irs.size()>0){
							 ItemRelation ir=irs.get(0);
							 mh=ir.getDoor();
							 srs=ir.getQty();
							 xs=1;//(int) Math.ceil(shsl/ir.getQty());
							 hz=ir.getCaseType();
							 obj.put("gys",gys);
							 obj.put("mh", mh);
							 obj.put("pf", pf);
							 obj.put("cpmc", it.getName());
							 obj.put("hz",hz);
							 obj.put("srs", srs);
							 obj.put("xs", xs);
							 obj.put("shsl",shsl);
							 obj.put("djrq", djrq);
							 obj.put("ddbh", ddbh);
							 obj.put("nrzsr", nrzsr);
							 data = obj.toString();
							 status="1";
							 PlanShipDetail psd=EntityFactory.getEntity(PlanShipDetail.class);
							 //序号	供应商	门号	品番	产品名称	何姿	收容数	箱数	送货数量	登记日期	订单编号	备注	纳入指示日
							 psd.setGys(gys);
							 psd.setMh(mh);
							 psd.setItem(it);
							 psd.setHz(hz);
							 psd.setSrs(srs);
							 psd.setXs(xs);
							 psd.setShsl(shsl);
							 psd.setDjrq(new Date());
							 psd.setDdbh(ddbh);
							 psd.setNrzsr(DateUtil.formatDate(nrzsr));
							 psd.setCreateBy(user_name);
							 psd.setCreateDate(new Date());
							 psd.setKey(key);
							 psd.setWarehouse(commonDao.get(Warehouse.class, 1020L));
							 commonDao.store(psd);
						 }else{
							 msg = pf+"纳入场所没维护";
						 }
					 }
				}else{
					msg = "Key不能重复扫描";
				}
			}else{
				msg = "Key不能为空或长度不对";
			}
			rJson.put("status", status);
			rJson.put("msg", msg);
			rJson.put("data", data);
			System.out.println(rJson.toString());
			response.setContentType(rJson.toString());
			response.setCharacterEncoding("UTF-8");
			out = response.getWriter();
			out.print(rJson.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			out.close();
		}	
	}
	private String shaEncodePassword(String painPwd){
		painPwd = painPwd == null ? "" : painPwd;
		if(painPwd.length() == 40){
			return painPwd;
		}
		return DigestUtils.shaHex(painPwd);
	}
    
//    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		// TODO Auto-generated method stub
//		this.doGet(request, response);
//	}
	
//    public void doGet(HttpServletRequest request, HttpServletResponse response)
//            throws ServletException, IOException {
//    		response.setContentType("text/html;charset=utf-8");
//    		request.setCharacterEncoding("utf-8");
//      	response.setCharacterEncoding("utf-8");
//      	Enumeration enu=request.getParameterNames();
//		while(enu.hasMoreElements()){  
//		String paraName=(String)enu.nextElement();  
//		System.out.println(paraName+":"+request.getParameter(paraName));  
//		}
//		BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));//post方式传递读取字符流
//		String jsonStr = null;
//		StringBuilder result = new StringBuilder();
//		try {
//		while ((jsonStr = reader.readLine()) != null) {
//		result.append(jsonStr);
//		}
//		} catch (IOException e) {
//		e.printStackTrace();
//		}
//		System.out.println(result.toString());
//		reader.close();// 关闭输入流
//      	PrintWriter out = response.getWriter();
//      	String content = request.getParameter("content");
//       //String content = new String(request.getParameter("content").getBytes("iso-8859-1"), "utf-8");  
//        String msg = "";
//		String status ="0";
//		String data="";
//		JSONObject resultJson = new JSONObject();
//		JSONObject obj = new JSONObject();
//		 obj.put("workerId","123456");
//		 obj.put("userName", content);
//		 obj.put("wId", "仓库ID");
//		 obj.put("isAdmin", "0");
//		 obj.put("userType", "WORKER");
//		 data = obj.toString();
//		resultJson.put("status", status);
//		resultJson.put("msg", msg);
//		resultJson.put("data", data);
//		System.out.println(resultJson.toString());
////		PrintWriter out = null;
//		try {
//			response.setContentType(resultJson.toString());
//			response.setCharacterEncoding("UTF-8");
//			out = response.getWriter();
//			out.print(resultJson.toString());
//		} catch (IOException e) {
//			e.printStackTrace();
//		} finally {
//			out.close();
//		}	
////        out.close();
//    }


}
