package com.skic.servlet;

import java.io.IOException;
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.coding.util.Coding;
import com.skic.DTO.UserDTO;
import com.skic.service.CheckRegisterService;;

public class CheckRegisterServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 8438869886327574209L;
	private CheckRegisterService crs = new CheckRegisterService(); 
		
	public CheckRegisterServlet() {
		super();
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log

	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		request.setCharacterEncoding("utf-8");
		String userName = request.getParameter("userName");
		String realName = request.getParameter("realName");
		String email = request.getParameter("email");
		String passWord = request.getParameter("passWord");
		String passWordBase64 = null;
		try {
			passWordBase64 = new BigInteger(Coding.encryptSHA(passWord.getBytes())).toString();//对密码进行加密处理
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		String tel = request.getParameter("tel");
		RequestDispatcher rd = null;
		String forwardString = null;
		if (userName==null||passWord==null) {
			request.setAttribute("msg", "用户名或密码为空");
			rd = request.getRequestDispatcher("/page/messagePage/error.jsp");
			rd.forward(request, response);
		}else {
			UserDTO user = new UserDTO();
			user.setUserName(userName);
			user.setPassword(passWordBase64);
			user.setRealName(realName);
			user.setEmail(email);;
			user.setPhoneNum(tel);
			boolean bool = crs.AddUser(user);
			System.out.println(bool);
			if (bool) {
				request.setAttribute("msg", "注册成功,请登录");
				request.setAttribute("RedirctURL", "login.jsp");
				request.setAttribute("Redirct", "前往登录");
				//forwardString = "/messagePage/messageShow.jsp";
			}else {
				request.setAttribute("msg", "账号已存在,请重新注册");
				request.setAttribute("RedirctURL", "register.jsp");
				request.setAttribute("Redirct", "重新注册");
			}
			forwardString = "/page/messagePage/messageShow.jsp";
			rd = request.getRequestDispatcher(forwardString);
			rd.forward(request, response);
		}
	}

	public void init() throws ServletException {

	}

}
