package com.jingCaiBack.action;

import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

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

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.jingCaiBack.dao.CoreDAO;
import com.jingCaiBack.model.UserLogin;
import com.jingCaiBack.util.MD5;
import com.jingCaiBack.util.SqlUtil;

public class GirlAction extends AbstractAction
{
		private static final int NOLOGIN=1;//未登陆状态
		private static final int ISEXITS=2;//已经投票
		private static final int LOGINOK=3;//登陆成功
		private static final int LOGINFAIL=4;//登陆失败
		private static final int OK=5;	 	//投票成功
		private static final int big4=6;	 	//超过4次投票
		private static final int OTHERS=0;	//未知错误
		
	   CoreDAO coreDAO=new CoreDAO();
	   public ActionForward findAllGirl(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
	     throws Exception
	   {
		   String sqlStr="select * from gril order by support desc";
		   Map map=new HashMap();
		   map.put("sql", sqlStr);
		   List list=coreDAO.getList("Core.generalSelect", map);
		   System.out.println(list);
		   Object Object=request.getSession().getAttribute("userAry");
		   System.out.println("Object----------------"+Object);
			Cookie Cookies[]=request.getCookies();
			if(Cookies==null)
			{
				
			}
			else
			{
			for(int i=0;i < Cookies.length;i++)
			  {
				if("userId".equals(Cookies[i].getName())){
					String userId=Cookies[i].getValue();
			     System.out.println("============Cookies============"+Cookies[i].getName()+"="+userId+"============Cookies============");
				}
				if("password".equals(Cookies[i].getName())){
					String passWord=Cookies[i].getValue();
				     System.out.println("============Cookies============"+Cookies[i].getName()+"="+Cookies[i].getValue()+"============Cookies===============");
					}
			  }
			}
	       request.setAttribute("list", list);
	     return mapping.findForward("success");
	   }
	   
	   public ActionForward updateSupport(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
			     throws Exception
			   {
			     request.setCharacterEncoding("UTF-8");
			     String userId=validLogin(request,response);
			     response.setContentType("text/html;charset=UTF-8");
			     PrintWriter out = response.getWriter();
			     if(userId!=null)
			     {
			    	
			     String gid = request.getParameter("gid");
			     
			    boolean flag= isExitsGrilAndUser(gid,userId);
			    if(flag)
			    {
			    	  out.print("{\"result\":"+ISEXITS+"}");
			    	  return null;
			    }
			     
			    int times = isTimes(userId);
			    if(times >= 4)
			    {
			    	  out.print("{\"result\":"+ big4 + ", \"times\":" + times + "}");
			    	  return null;
			    }
			     String sql="update gril set support=support+1 where grilid="+gid;
			     Map map=new HashMap();
			     map.put("sql", sql);
			     coreDAO.update("Core.generalUpdate", map);
			     
			     String insertSql="insert into GrilAndUser values("+gid+","+userId+")";
			     Map map2=new HashMap();
			     map2.put("sql", insertSql);
			     coreDAO.insert("Core.generalInsert", map2);
			     
			     
			     out.print("{\"result\":"+OK+", \"times\": "+ times + "}");
			     }
			     else
			     {
			    	 out.print("{\"result\":"+NOLOGIN+"}");
			     } 
			     out.flush();
			     return null;
			   }
	   
	   
	   public boolean isExitsGrilAndUser(String grilId,String userId) throws SQLException
	   {
		   String sql="select count(*) num from GRILANDUSER where grilId="+grilId+" and userId="+userId;
		   Map map=new HashMap();
		   map.put("sql", sql);
		   Map resultMap= coreDAO.getMap("Core.generalSelect", map);
		   String num=resultMap.get("NUM").toString();
		     
		     if("1".equals(num)){
		      return true;
		     }
		   return false;
	   }
	   
	   
	   public int isTimes(String userId) throws SQLException
	   {
		   String sql="select count(*) num from GRILANDUSER where  userId="+userId;
		   Map map=new HashMap();
		   map.put("sql", sql);
		   Map resultMap= coreDAO.getMap("Core.generalSelect", map);
		   String num=resultMap.get("NUM").toString();
		   return Integer.valueOf(num);

	   }
	   /***
	    * 验证是否登陆
	    * @param request
	    * @param response
	    * @return
	    * @throws Exception
	    */
	   public String validLogin(HttpServletRequest request, HttpServletResponse response)
			     throws Exception
			   {
			     request.setCharacterEncoding("UTF-8");
			     
			     
			    String userId=""; 
			    String passWord="";
			     
			 	Cookie Cookies[]=request.getCookies();
				if(Cookies==null)
				{
					
				}
				else
				{
				for(int i=0;i < Cookies.length;i++)
				  {
					if("userId".equals(Cookies[i].getName())){
						 userId=Cookies[i].getValue();
				     System.out.println("============Cookies============"+Cookies[i].getName()+"="+userId+"============Cookies============");
					}
					if("password".equals(Cookies[i].getName())){
						 passWord=Cookies[i].getValue();
					     System.out.println("============Cookies============"+Cookies[i].getName()+"="+Cookies[i].getValue()+"============Cookies===============");
						}
				  }
				}
			     MD5 md5=new MD5();
			     String pwd= md5.md5GB2312(passWord);
			     SqlUtil sqlUti=new SqlUtil();
			     String loginName=(String) sqlUti.getColumnNameById("user_login", "userid", userId, "loginName");
			     
			     String sql="select count(1) num from  user_login where loginName='"+loginName+"' and userpassword='"+pwd+"'";
			     Map map=new HashMap();
			     map.put("sql", sql);
			    Map resultMap= coreDAO.getMap("Core.generalSelect", map);
			     String num=resultMap.get("NUM").toString();
			     
			     if("1".equals(num)){
			      return userId;
			     }
			    return null;
			   }
	   /***
	    * 验证登陆是否成功
	    * @param mapping
	    * @param form
	    * @param request
	    * @param response
	    * @return
	    * @throws Exception
	    */
	   public ActionForward login(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
			     throws Exception
			   {
			     request.setCharacterEncoding("UTF-8");
			     
					
			    String loginName = request.getParameter("username");
			    String password= request.getParameter("password");
			    
			    MD5 md5=new MD5();
			     String pwd= md5.md5GB2312(password);
			    
			    String sql="select count(1) num from  user_login where loginName='"+loginName+"' and userpassword='"+pwd+"'";
			     Map map=new HashMap();
			     map.put("sql", sql);
			     Map resultMap= coreDAO.getMap("Core.generalSelect", map);
			     String num=resultMap.get("NUM").toString();
			     response.setContentType("text/html;charset=UTF-8");
			     PrintWriter out = response.getWriter();
			     if("1".equals(num)){
			    	 SqlUtil sqlUti=new SqlUtil();
			    	 String userId=sqlUti.getColumnNameById("user_login", "loginName", loginName, "userId").toString();
			    	 
			    	 Cookie useridCookies = new Cookie("userId", userId);
			    	 Cookie passwordCookies = new Cookie("password", password);
			    	 useridCookies.setMaxAge(3600);
			    	 passwordCookies.setMaxAge(3600);
			    	 useridCookies.setPath("/");
			    	 passwordCookies.setPath("/");
			    	 response.addCookie(useridCookies);
			    	 response.addCookie(passwordCookies);
				     out.print("{\"result\":" + LOGINOK + "}");
				     
			     }
			     else
			     {
			    	 out.print("{\"result\":" + LOGINFAIL + "}");
			     }
			
			     out.flush();
			    
			     return null;
			   }
}

