package com.mingsoft.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import com.mingsoft.biz.IUserBiz;
import com.mingsoft.biz.impl.UserBizImpl;
import com.mingsoft.constant.SessionConst;
import com.mingsoft.entity.ResutEntity;
import com.mingsoft.entity.UserEntity;
import com.mingsoft.util.StringUtil;

/**
 * 登录页面 
 * session验证
 * @author 荣繁奎
 * QQ：1096199590
 * 铭飞科技
 * 官网：www.ming-soft.com
 * 
 */
public class LoginServlet extends BaseServlet {

	/**
	 * 版本号
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * 验证码
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		super.doGet(request, response);
		HttpSession sesion = request.getSession(true);
		//判断用户登录则跳转到主页面
		if(sesion.getAttribute(SessionConst.ADMIN_SESSION.toString())!=null){
			response.sendRedirect("admin/index");
		}else{
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
	}

	/**
	 * 请求登录
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		super.doPost(request, response);
		String userName = request.getParameter("name");
		String userPassWord = request.getParameter("password");
		String check = request.getParameter("check");
		//验证码
		HttpSession session = request.getSession();
		Object verify = session.getAttribute("randomCode");
		PrintWriter out = response.getWriter();
		IUserBiz userBiz = new UserBizImpl();
		ResutEntity re = new ResutEntity();
		if (StringUtil.strNull(userName) || StringUtil.strNull(userPassWord)) {
				re.setCode(ResutEntity.LOGIN_EMPTY);
		} else {
			String passWord = userBiz.queryName(userName);
			if (passWord.equals(userPassWord)) {
				if(check.equals("")|| check == null){
					re.setCode(ResutEntity.LOGIN_RANDCODER_EMPTY);
				} else if(!check.equals("") && check != null) {
					if (check.equals(verify)) {
						re.setCode(ResutEntity.LOGIN_SUCCESS);
						//登录成功把用户对象压入session
						UserEntity user = new UserEntity();
						user.setUserName(userName);
						user.setUserPassWord(userPassWord);
						//把用户对象压入session里面
						session.setAttribute(SessionConst.ADMIN_SESSION.toString(), user);
					} else {
						re.setCode(ResutEntity.LOGIN_RANDCODER_ERROR);
					}
				}
			} else {
				re.setCode(ResutEntity.LOGIN_PASSWORD_ERROR);
			}
		}
		out.write(JSONObject.fromObject(re).toString());
		out.close();
	}

}
