package com.letousky.lottery.action;

import com.fivestars.interfaces.bbs.client.Client;
import com.letousky.connector.MessageTool;
import com.letousky.exception.LotteryException;
import com.letousky.lottery.delegate.LoginManage;
import com.letousky.lottery.delegate.SelectMyAccountManage;
import com.letousky.lottery.delegate.WinsFlat;
import com.letousky.lottery.util.OperaterCode;
import com.letousky.lottery.util.TimeUtil;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URLEncoder;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.utils.AddrUtil;

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

public class LoginAction extends BaseAction
{
  public void doLogin(String username, String password, HttpServletResponse response)
  {
    username = URLEncoder.encode(username);
    password = URLEncoder.encode(password);
    Cookie cookie = new Cookie("cpsUserName", username + "|" + password);
    cookie.setMaxAge(-1);
    cookie.setPath("/");
    response.addCookie(cookie);
  }
  
  /**  
    *  根据名称读取cookie  
    */  
  public String getCookie(String name,HttpServletRequest request){   
    Cookie[] cookie = request.getCookies();   
    String object = null;   
    for(int i=0;i<cookie.length;i++)   
    {   
     if(cookie[i].getName().equals(name)==true)   
    {   
      object = cookie[i].getValue();
      break;   
     }   
   }   
    return object;   
   }  
  
  public ActionForward registerMain(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
		    throws Exception
	{
		response.setContentType("text/html;charset=UTF-8");
		String username = request.getParameter("reg_username");
		String password = request.getParameter("reg_password");
		String[] params = new String[23];
		for(int i =0;i < params.length; i++)
		{
			params[i] = "";
		}
		params[0] = username;
		params[1] = password;
		params[2] = username;
		Cookie[] cookies = request.getCookies();
		String useridSX = "";
		for(int i=0;i<cookies.length;i++){
			if(cookies[i].getName().equals("onLineId")){
				useridSX = cookies[i].getValue();
			}
		}
		params[20] = useridSX;
		try{
			
			
			
			
			String unionId = "";
			//多麦链接接入存入cooke
			boolean isDuomai = false;
			String euid="";
			Cookie Cookies[]=request.getCookies();
			if(Cookies!=null){
				for (int i = 0; i < Cookies.length; i++) {
					System.out.println("---------"+Cookies[i].getName());
					if("sid".equals(Cookies[i].getName())&& "duomai".equals(Cookies[i].getValue())){
						unionId = Cookies[i].getValue();
						isDuomai = true;
//						break;
					}
					if("euid".equals(Cookies[i].getName())){
						euid = Cookies[i].getValue();
						params[20]=euid;
						break;
					}else if("sid".equals(Cookies[i].getName())){
						unionId = Cookies[i].getValue();
						break;
					}
				}
			}
			params[3] = unionId;
			
			if (isDuomai){
				new LoginManage().register3(params,"1009");
			}
			else{
				new LoginManage().register3(params,null);
			}
			String[] loginPar = new String[]{username,password,"sl","0000"}; 
			
			new WinsFlat().newLogin(request,response,loginPar);
		}catch(LotteryException ee)
		{
			request.setAttribute("errorMsg", ee.getMessage());
			return mapping.findForward("errormsg");
		}
		String u=request.getParameter("u");
		request.setAttribute("u", u);
		
		return mapping.findForward("regsuccess");
	}
  
  
  public ActionForward registerInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
		    throws Exception
	{
	  response.setContentType("text/html;charset=UTF-8");
	  
	  String u=request.getParameter("u");
	  if(u==null || "null".equals(u) || "".equals("")){
		  String myLink=(String) request.getSession().getAttribute("myLink");
		  if( myLink!=null && !"".equals(myLink)&&!"null".equals(myLink)){
			  u=myLink;
		  }else{
			  u="111111";
		  }
	  }
	  String idcard = request.getParameter("idcar");
	  String truename = request.getParameter("truename");
	  String tlePhone = request.getParameter("tlePhone");
	  try{
		  String[] userArr = (String[])request.getSession().getAttribute("userAry");
		  String userid = userArr[1];
		  String[] params = new String[]{userid,idcard,truename,tlePhone,u};
		  new LoginManage().rstinfo(params);
	  }catch(LotteryException ee)
	  {
			request.setAttribute("errorMsg", ee.getMessage());
			return mapping.findForward("errormsg");
	  }
	  
	
	  //左国斌给销售人员统计注册人数
	  String sellUserId=u;
	  String []params2=new String[1];
	  String []params3=new String[5];
	  params2[0]=sellUserId;
	  try {
		  String []sellCOuntArray=new LoginManage().findSellCountNum(params2, "C0200");//从数据中查询一条记录
		  sellUserId=sellCOuntArray[0];
		  String sellUserName=sellCOuntArray[1];
		  String postUrl=sellCOuntArray[2];
		  String argument=sellCOuntArray[3];
		  String canyuNum=sellCOuntArray[4];
		  long canyuNumLongType =Long.valueOf(canyuNum);//转换成long数据类型
		  canyuNumLongType=canyuNumLongType+1;//将人数加1;
		  params3[0]=sellUserId;
		  params3[1]=sellUserName;
		  params3[2]=postUrl;
		  params3[3]=argument;
		  params3[4]=String.valueOf(canyuNumLongType);
		  new LoginManage().addSellCountNum(params3, "C0201");//持久化到数据库中去
		  
	  } catch (Exception e) {
			request.setAttribute("errorMsg", "您的链接可能被修改过,请注意!");
			return mapping.findForward("errormsg");
	  }
	  
	  return mapping.findForward("forwordindex");
	}
  public ActionForward login(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
    throws Exception
  {
	response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = null;
    String code = request.getParameter("code");
    try {
      out = response.getWriter(); } catch (IOException localIOException) {
    }
    if (("sy".equals(code)) && 
      (!request.getParameter("validateCode").trim().equals(request.getSession().getAttribute("validateCode").toString().trim()))) {
      out.print("{result:'dfsqw',errorMessage:'验证码输入有误！'}");
      return mapping.findForward("noforward");
    }

    String[] results = (String[])null;
    String[] params = (String[])null;
    String[] result = (String[])null;
    
    String[] userAry = new String[19];
    try {
      __logger.debug("鐢ㄦ埛鐧诲綍!");
      params = initialize(request);
      results = new LoginManage().login(params);

      doLogin(params[0], params[1], response);

      __logger.debug("鐧诲綍缁撴潫!");
    } catch (LotteryException e) {
      out.print("{result:'wrong',errorMessage:'用户名或密码错误！请重新输入！'}");
      return mapping.findForward("noforward");
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    try {
      __logger.debug("鐢ㄦ埛鐧诲綍!");

      result = new SelectMyAccountManage().selectMyAccount(new String[] { params[0], params[1] }, "C0012");
      doLogin(params[0], params[1], response);

      __logger.debug("鐧诲綍缁撴潫!");
    } catch (LotteryException e) {
      userAry[8] = "0.0";
      userAry[9] = "0.0";
      userAry[10] = "0.0";
      userAry[13] = "0.0";
      userAry[14] = "0.0";
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    if (result != null)
    {
      userAry[8] = result[1];
      userAry[9] = result[2];
      userAry[10] = result[3];
      userAry[13] = result[4];
      userAry[14] = result[5];
    }

    for (int i = 0; i < 8; i++) {
      userAry[i] = results[i];
    }

    BigDecimal bd = new BigDecimal(userAry[8]);
    userAry[11] = bd.setScale(2, 1).toString();

    if (results != null) {
      userAry[15] = results[8];
      userAry[16] = results[9];
      userAry[17] = results[10];
    }
    userAry[5] = TimeUtil.string2timeH(userAry[5]);
    userAry[12] = params[1];
    userAry[18] = results[(results.length - 1)];
    HttpSession session = request.getSession();
    session.setAttribute("password", params[1]);
    session.setAttribute("userAry", userAry);
    

    
    session.setMaxInactiveInterval(-1);
    returnAjax(response, userAry);
    
   String  worldCup=request.getParameter("worldCup");
   if(worldCup!=null && "worldCup".equals(worldCup)){
	   return mapping.findForward("worldCup");
   }
    return mapping.findForward("noforward");
  }

  public ActionForward goLogin(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
    throws Exception
  {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = null;
    try {
      out = response.getWriter();
    } catch (IOException localIOException) {
    }
    String whichJsp = request.getParameter("whichJsp").trim();
    if (!request.getParameter("validateCode").trim().equals(request.getSession().getAttribute("validateCode").toString().trim())) {
      request.setAttribute("errorMsg", "楠岃瘉鐮佹湁璇�!");
      return mapping.findForward("fail");
    }
    String[] results = (String[])null;
    String[] params = (String[])null;
    String[] result = (String[])null;
    String[] userAry = new String[18];
    try {
      __logger.debug("鐢ㄦ埛鐧诲綍!");
      params = initialize(request);

      results = new LoginManage().login(params);
      doLogin(params[0], params[1], response);

      __logger.debug("鐧诲綍缁撴潫!");
    } catch (LotteryException e) {
      request.setAttribute("errorMsg", "鐢ㄦ埛鍚嶆垨瀵嗙爜閿欒!");
      return mapping.findForward("fail");
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    try {
      __logger.debug("鐢ㄦ埛鐧诲綍!");

      result = new SelectMyAccountManage().selectMyAccount(new String[] { params[0], params[1] }, "C0012");

      __logger.debug("鐧诲綍缁撴潫!");
    } catch (LotteryException e) {
      userAry[8] = "0";
      userAry[9] = "0";
      userAry[10] = "0";
      userAry[13] = "0";
      userAry[14] = "0";
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    if (result != null) {
      userAry[8] = result[1];
      userAry[9] = result[2];
      userAry[10] = result[3];
      userAry[13] = result[4];
      userAry[14] = result[5];
    }
    double a = Double.valueOf(userAry[8]).doubleValue() + 
      Double.valueOf(userAry[9]).doubleValue() + Double.valueOf(userAry[
      13]).doubleValue() - Double.valueOf(userAry[10]).doubleValue();
    BigDecimal bd = new BigDecimal(a);
    userAry[11] = bd.setScale(2,3).toString();
    
    for (int i = 0; i < 8; i++) {
      userAry[i] = results[i];
    }
    if (results != null) {
      userAry[15] = results[8];
      userAry[16] = results[9];
      userAry[17] = results[10];
    }
    userAry[5] = TimeUtil.string2timeH(userAry[5]);
    userAry[12] = params[1];

    request.getSession().setAttribute("userAry", userAry);
    String jForum = request.getParameter("u");
    if (jForum.equals("jforum")) {
      response.sendRedirect("http://www.letoula.com/jforum/index.htm");
      return null;
    }
    return mapping.findForward(whichJsp);
  }

  public ActionForward unLogin(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
    throws Exception
  {
	  //***********************左国斌消除cookies************************//
	    Cookie useridCookies = new Cookie("userId", "");
	    Cookie passwordCookies = new Cookie("password", "");
	    useridCookies.setPath("/");
	    passwordCookies.setPath("/");
	    response.addCookie(useridCookies);
	    response.addCookie(passwordCookies);
	  //***********************左国斌消除cookies************************//
	  PrintWriter out = null;
		
	    //System.out.println("session has be removed!====================");

    try {
    	out = response.getWriter();
		request.getSession().invalidate();
		request.getSession().removeAttribute("userAry");
		
		/*UC退出*/
		/*Client uc = new Client();  
        String $ucsynlogout = uc.uc_user_synlogout();
    	HttpSession session = request.getSession();
    	session.setAttribute("uc_userout", $ucsynlogout);
    	session.setAttribute("uc_user",null);*/
        /*UC退出完*/
    } catch (IOException localIOException) {
    }
//    out.print("{relust:'0000'}");
//    String close = request.getParameter("b");
//    if ((close != null) && (!"".equals(close))) {
//      return mapping.findForward("jFrmaSuccess");
//    }
    
    //左国斌删除Memcached功能2014-6-24
 /*   MemcachedClientBuilder mClientBuilder =new XMemcachedClientBuilder(
            AddrUtil.getAddresses("127.0.0.1:11211"));
    try {
        MemcachedClient memcachedClient =mClientBuilder.build();
            memcachedClient.delete("userId");   
    } catch (IOException e) {
        e.printStackTrace();
    }*/
    //左国斌删除Memcached功能2014-6-24
    
    
    String worldCup=request.getParameter("worldCup");
    if(worldCup!=null && "worldCup".equals(worldCup)){
    	   return mapping.findForward("worldCup");
    }
    return mapping.findForward("success");
  }
  
  public int uc_layout(HttpServletRequest request, HttpServletResponse response){
	  
	  	request.getSession().invalidate();
		request.getSession().removeAttribute("userAry");
		
		/*UC退出*/
		Client uc = new Client();  
		String $ucsynlogout = uc.uc_user_synlogout();
		HttpSession session = request.getSession();
		session.setAttribute("uc_userout", $ucsynlogout);
		session.setAttribute("uc_user",null);
		return 0;
  }
  public ActionForward isLogin(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
    throws Exception
  {
    Object obj = request.getSession().getAttribute(
      "userAry");

    PrintWriter out = null;
    try {
      out = response.getWriter(); } catch (IOException localIOException) {
    }
    if (obj != null)
      out.print("{result:'yes'}");
    else {
      out.print("{result:'no'}");
    }
    return mapping.findForward("noforward");
  }

  public ActionForward noLogin(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
    throws Exception
  {
    request.getSession().removeAttribute("userAry");

    return mapping.findForward("outSuccess");
  }

  private void returnAjax(HttpServletResponse response, String[] strAry)
  {
    PrintWriter out = null;
    try {
      out = response.getWriter();
    }
    catch (IOException localIOException)
    {
    }
    out.print("{result:'0000");

    out.print("',loginName:'" + strAry[2]);

    out.print("',loginTimes:'" + strAry[4]);
    out.print("',loginLastTime:'" + strAry[5]);

    out.print("',status:'" + strAry[16]);
    out.print("',money:'" + strAry[11]);

    out.print("'}");
  }

  public void upLogin(HttpServletRequest request, HttpServletResponse response)
    throws IOException
  {
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();
    String[] results = (String[])null;
    String[] result = (String[])null;
    String[] userAry = (String[])request.getSession().getAttribute("userAry");
    String[] params = new String[]{super.getUserName(request),super.getPassword(request)};
    try {
      //results = new LoginManage().login(params);
    }
    catch (LotteryException e) {
      e.printStackTrace();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    try {
      result = new SelectMyAccountManage().selectMyAccount(new String[] { params[0], params[1] }, "C0012");
    } catch (LotteryException e) {
      userAry[8] = "0.0";
      userAry[9] = "0.0";
      userAry[10] = "0.0";
      userAry[13] = "0.0";
      userAry[14] = "0.0";
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    if (result != null)
    {
      BigDecimal bg = new BigDecimal(String.valueOf(Double.parseDouble(result[1]) + Double.parseDouble(result[2]) - Double.parseDouble(result[3])));
      userAry[8] = String.valueOf(bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
      userAry[9] = result[2];
      userAry[10] = result[3];
      userAry[13] = result[4];
      userAry[14] = result[5];
    }
    double a = Double.valueOf(userAry[8]).doubleValue() + 
      Double.valueOf(userAry[9]).doubleValue() + Double.valueOf(userAry[
      13]).doubleValue() - Double.valueOf(userAry[10]).doubleValue();
    BigDecimal bd = new BigDecimal(a);
    userAry[11] = bd.setScale(2,3).toString();
    request.getSession().setAttribute("userAry", userAry);
  }

  private String[] initialize(HttpServletRequest request)
    throws Exception
  {
	 // String loginName = new String(request.getParameter("loginName").getBytes("ISO8859-1"),"UTF-8");
	  String loginName = request.getParameter("loginName");
	  String password = request.getParameter("password");

	  String[] logins = new String[2];
	  logins[0] = loginName;
	  logins[1] = password;
	  return logins;
  }
  

}