package com.wxpn.tutorial.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

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

import com.wxpn.tutorial.db.ConnectionPool;
import com.wxpn.tutorial.db.DB;

/**
 * Servlet implementation class for Servlet: RegisterServlet
 */
public class RegisterServlet extends javax.servlet.http.HttpServlet implements
		javax.servlet.Servlet {
	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public RegisterServlet() {
		super();
	}

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request,
	 *      HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String result = "";

		// 获取提交的用户名：
		String strUserName = request.getParameter("txtUserName");
		strUserName = new String(strUserName.getBytes("ISO8859_1"), "UTF-8");
		// 获取提交的密码：
		String strPassword = request.getParameter("txtPassword");
		strPassword = new String(strPassword.getBytes("ISO8859_1"), "UTF-8");
		String strConfPassword = request.getParameter("txtConfPassword");
		if ((strUserName == null) || (strUserName.equals(""))
				|| (strUserName.length() > 20)) {
			result = "请输入用户名(不超过20字符)";
			request.setAttribute("result", result);
			try {
				request.getRequestDispatcher("/register.jsp").forward(request,
						response);
			} catch (Throwable t) {
				getServletContext().log(t.getMessage());
			}
		}
		if ((strPassword == null) || (strPassword.equals(""))
				|| (strPassword.length() > 20)) {
			result = "请输入密码(不超过20字符)";
			request.setAttribute("result", result);
			try {
				request.getRequestDispatcher("/register.jsp").forward(request,
						response);
			} catch (Throwable t) {
				getServletContext().log(t.getMessage());
			}
		}
		if ((strConfPassword == null) || (strConfPassword.equals(""))
				|| (strConfPassword.length() > 20)) {
			result = "请输入确认密码(不超过20字符)";
			request.setAttribute("result", result);
			try {
				request.getRequestDispatcher("/register.jsp").forward(request,
						response);
			} catch (Throwable t) {
				getServletContext().log(t.getMessage());
			}
		}
		if (!strPassword.endsWith(strConfPassword)) {
			result = "密码与确认密码不匹配，请重新输入密码(不超过20字符)";
			request.setAttribute("result", result);
			try {
				request.getRequestDispatcher("/register.jsp").forward(request,
						response);
			} catch (Throwable t) {
				getServletContext().log(t.getMessage());
			}
		}
		// 获取其他数据：
		String strRealName = request.getParameter("txtRealName");

		if ((strRealName == null) || (strRealName.equals(""))
				|| (strRealName.length() > 20)) {
			result = "请输入真实姓名(不超过50字符)";
			request.setAttribute("result", result);
			try {
				request.getRequestDispatcher("/register.jsp").forward(request,
						response);
			} catch (Throwable t) {
				getServletContext().log(t.getMessage());
			}
		}
		strRealName = new String(strRealName.getBytes("ISO8859_1"), "UTF-8");
		String strGender = request.getParameter("sltGender");
		if ((strGender == null) || (strGender.equals(""))
				|| (strGender.length() > 20)) {
			result = "请选择性别";
			request.setAttribute("result", result);
			try {
				request.getRequestDispatcher("/register.jsp").forward(request,
						response);
			} catch (Throwable t) {
				getServletContext().log(t.getMessage());
			}
		}
		String strTel = request.getParameter("txtTel");
		if ((strTel == null) || (strTel.equals("")) || (strTel.length() > 20)) {
			result = "请输入正确的电话(不超过20字符)";
			request.setAttribute("result", result);
			try {
				request.getRequestDispatcher("/register.jsp").forward(request,
						response);
			} catch (Throwable t) {
				getServletContext().log(t.getMessage());
			}
		}
		strTel = new String(strTel.getBytes("ISO8859_1"), "UTF-8");
		String strEmail = request.getParameter("txtEmail");
		if ((strEmail == null) || (strEmail.equals(""))
				|| (strEmail.length() > 20)) {
			result = "请输入正确的Email(不超过30字符)";
			request.setAttribute("result", result);
			try {
				request.getRequestDispatcher("/register.jsp").forward(request,
						response);
			} catch (Throwable t) {
				getServletContext().log(t.getMessage());
			}
		}
		strEmail = new String(strEmail.getBytes("ISO8859_1"), "UTF-8");
		String strHomePage = request.getParameter("txtHomePage");
		strHomePage = new String(strHomePage.getBytes("ISO8859_1"), "UTF-8");
		int intGender = -1;
		// 转化变量：
		if ((strGender != null) && (strGender.equals("1"))) {
			intGender = 1;
		} else if ((strGender != null) && (strGender.equals("0"))) {
			intGender = 0;
		}

		// 创建数据库连接对象：
		ConnectionPool connPool = DB.getConnPool();
		Connection conn = connPool.getConnection();
		Statement stmt = null;
		ResultSet rs = null;

		try {
			User user = new User();
			user.setUserName(strUserName);
			user.setUserPwd(strPassword);
			user.setRealName(strRealName);
			user.setGender(intGender);
			user.setTelNumber(strTel);
			user.setEmail(strEmail);
			user.setHomepage(strHomePage);

			// 在UserInfo表中查找是否有同名的记录
			String sql = "select * from userinfo where username='"
					+ strUserName + "'";

			// 创建数据记录集对象：
			stmt = conn.createStatement();
			// 执行sql语句，返回一个记录集到rs：
			rs = stmt.executeQuery(sql);

			if (rs.next()) {
				// 如果记录集为非空，表明有相匹配的用户名，注册失败：
				result = "已经存在相同的用户名，请更换一个新用户名";

				request.setAttribute("result", result);
				request.setAttribute("user", user);
				try {
					request.getRequestDispatcher("/register.jsp").forward(
							request, response);
				} catch (Throwable t) {
					getServletContext().log(t.getMessage());
				}
			} else {
				// 否则（记录集为空），表明不存在该用户：
				// sql语句：
				sql = "insert into userinfo(UserName,UserPwd,RealName,"
						+ "gender,telnumber,email,homepage) values('"
						+ strUserName + "','" + strPassword + "','"
						+ strRealName + "','" + intGender + "','" + strTel
						+ "','" + strEmail + "','" + strHomePage + "')";
				// 执行sql语句：
				int i = stmt.executeUpdate(sql);
				if (i == 1) {
					// 注册成功
					request.setAttribute("user", user);
					try {
						request.getRequestDispatcher("/registerSuccess.jsp")
								.forward(request, response);
					} catch (Throwable t) {
						getServletContext().log(t.getMessage());
					}
				} else {
					// 否则，表明注册失败：
					System.out.println("<h1>注册用户" + strUserName + "失败!</h1>");
				}
			}
		} catch (SQLException sqlExc) {
			sqlExc.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 关闭连接，释放数据库资源：
			try {
				if (stmt != null) {
					stmt.close();
				}
				connPool.freeConnection(conn);
			} catch (SQLException sqlExc) {
				sqlExc.printStackTrace();
			}
		}
	}
}