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.Worker;

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

/**
 * Servlet implementation class LoginAppServlet
 */
public class LoginAppServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected static ApplicationContext ac;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginAppServlet() {
        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();
		try {
			while ((jsonStr = reader.readLine()) != null) {
				result.append(jsonStr);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("result:"+result.toString());
		JSONObject json= JSONObject.fromObject(result.toString());
		System.out.println("==========app登录========"+new Date());
		String loginName =json.has("loginName")?json.getString("loginName"):""; 
		String passWord = json.has("passWord")?json.getString("passWord"):""; 
//		String type = json.has("type")?json.getString("type"):"VMI"; 
//		String token = json.has("token")?json.getString("token"):""; 
		String msg = "";
		String status ="0";
		String data="";
		JSONObject resultJson = new JSONObject();
		Long wId=null;
		String hql="FROM Worker d WHERE (d.code=:code ) AND d.passWord = :passWord";
//		if(type.equals("VMI")){
//			hql+=" and d.warehouse.code like '%VMI%'";
//		}
		List<Worker> ws =commonDao.findByQuery(hql,
				new String[] { "code","passWord" }, new Object[] { loginName,passWord });
		Worker w=null;
		if(ws.size()>0){
			w=ws.get(0);
			if(w.isDisabled()){
				msg = "用户已失效";
			}else{
				wId=w.getWarehouse().getId();
				status="1";
				//维护消息推送token
//				w.setAndroid_token(token);
				commonDao.store(w);
				JSONObject obj = new JSONObject();
		 		 obj.put("user_id",w.getId());
				 obj.put("user_name", w.getName());
				 obj.put("w_id", wId);
				 obj.put("user_type", w.getType()==null?"":w.getType());
				 data = obj.toString();
			}
		}else{
			msg = "用户不存在或密码错误";
		}
		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();
		}	
	}
	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();
//    }


}
