package com.letousky.lottery.action;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

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 org.apache.struts.actions.DispatchAction;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;

import com.letousky.connector.MessageTool;
import com.letousky.exception.LotteryException;
import com.letousky.lottery.delegate.LoginManage;
import com.letousky.lottery.delegate.WinsFlat;
import com.letousky.lottery.util.Base64DecoderEncoder;
import com.letousky.lottery.util.ConvertUtil;
import com.letousky.lottery.util.InsiderCenterFormat;
import com.letousky.lottery.util.LotteryExceptionUtil;
import com.letousky.lottery.util.OperaterCode;
import com.letousky.lottery.util.TimeUtil;

public class PutForwordAction extends BaseAction{
	
	 /**
	  * 
	  * @Title: putforword
	  * @Description: 竞彩投注接口
	  * @param @param mapping
	  * @param @param form
	  * @param @param request
	  * @param @param response
	  * @param @return
	  * @return ActionForward
	  * @throws
	  * @param mapping
	  * @param form
	  * @param request
	  * @param response
	  * @return
	  */
	public ActionForward putforword(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){
		
		
		response.setContentType("text/html;charset=UTF-8");
		
		 this.saveToken(request);//防止重复提交的问题
		 
		HashMap betMap = new HashMap();
		String info = request.getParameter("inf");
		String[] infoArr = info.split("\\$");
		String muliptile=request.getParameter("muliptile");
		String tzNumber=request.getParameter("tzNumber");
		String gameCode=request.getParameter("gameCode");
		if("513".equals(gameCode) || "514".equals(gameCode)){
			gameCode = "509";
		}
		String spzValue=request.getParameter("spzValue");
		String mcn=request.getParameter("McN");
		String zqmcn=request.getParameter("ZQMcN");
		String zhushu=request.getParameter("zhushu");
		String price=request.getParameter("price");
		String gType=request.getParameter("gType");
		String issue=request.getParameter("issue");
		String moneyFw=request.getParameter("moneyFw");
		//int chop=Integer.parseInt(zhushu.trim())*Integer.parseInt(muliptile.trim())*2;
		
		StringBuffer strssid = new StringBuffer(); 
		if(info.indexOf(",")!=-1){
			for(int i=0;i<infoArr.length;i++){
				String[] ssid = infoArr[i].split(",");
				strssid.append(ssid[6]).append(",");
			}
			strssid.deleteCharAt(strssid.lastIndexOf(","));
		}
		//HashMap marketMap = new WinsFlat().betting_sel(new String[]{strssid.toString()});
		int countCopies = (int)Double.parseDouble(price);
		betMap.put("Muliptile", muliptile); //描述
		betMap.put("money", price);
		betMap.put("zs", zhushu);//注数
		betMap.put("mcn", mcn);//过关方式
		betMap.put("manner", zqmcn);
		betMap.put("title", "过关投注");
		betMap.put("description", "过关投注");
		betMap.put("isopen", "1");
		betMap.put("openusers", "all");
		betMap.put("isUpload", "1");
		betMap.put("payofftc", "0");
		betMap.put("copies", countCopies);//份数
		betMap.put("betcopies", countCopies);//每份价格
		betMap.put("eachPrice", "1.00");
		betMap.put("ensures", "0");
		betMap.put("chipinNums",tzNumber);//投注号码
		betMap.put("hmfaType", "1");
		betMap.put("spvalue", spzValue);//赔率
		betMap.put("moneyFw", moneyFw);//
		betMap.put("issue", issue);
		betMap.put("info", info);
		betMap.put("gameCode", gameCode);//彩种
		betMap.put("strssid", strssid);//未知
		String betjson = Json.toJson(betMap,JsonFormat.compact());
		request.setAttribute("betjson", betjson);
		String forward = new InsiderCenterFormat().getLotteryForwrd(gameCode);
		return mapping.findForward(forward);
	}
	
	public ActionForward BettingEntrance(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){
		
		if(isTokenValid(request,true)){ 
		response.setContentType("text/html;charset=UTF-8");
		String gameCode = request.getParameter("gameCode");//玩法类型
		String manner	= request.getParameter("manner");//投注方式
		String title    = request.getParameter("title");//标题
		String description    = request.getParameter("description");//描述
		String isopen    = request.getParameter("isopen");//是否公开
		String openusers    = request.getParameter("openusers");//面向全部网友
		String isUpload    = request.getParameter("isUpload");//是否上传
		String payofftc    = request.getParameter("payofftc");//提成比例
		String money    = request.getParameter("money");//投注总金额
		String multiple    = request.getParameter("Muliptile");//倍数
		String copies    = request.getParameter("copies");//总份数
		String betcopies    = request.getParameter("betcopies");//认购份数
		String eachPrice    = request.getParameter("eachPrice");//每份单价
		String ensures    = request.getParameter("ensures");//保底份数
		String chipinNums    = request.getParameter("chipinNums");//投注号码
		String hmfaType    = request.getParameter("hmfaType");//代购1,合买2
		String spValue    = request.getParameter("spvalue");//SP值
		String moneyFw    = request.getParameter("moneyFw");//奖金范围
		String issue    = request.getParameter("issue");//期号，竞彩没有期号unkonw
		
		//判断账户金额是否足以购买
		String[] userAry = (String[]) request.getSession().getAttribute("userAry");
		String touzhuMoney=userAry[8];
		String hongbaoMoney=userAry[13];
		double totalMoney=Double.valueOf(touzhuMoney)+Double.valueOf(hongbaoMoney);
		//购买金额
		double goumai=Double.valueOf(betcopies)*Double.valueOf(eachPrice);
		if(goumai>totalMoney){//如果金额不足就弹出一个对话框,告诉用户去充值
			request.setAttribute("totalMoney", totalMoney);
			request.setAttribute("money", goumai);
			return mapping.findForward("forward_chongzhi");
		}
      	   
		
		
		if("102".equals(gameCode) || "103".equals(gameCode) || "106".equals(gameCode) || "107".equals(gameCode)){
			String[] strA=new WinsFlat().findStatusBylotNameAndIssue(new String[]{gameCode,issue});
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			Date date=new Date();
			String fdate=sdf.format(date);
			if(Long.valueOf(strA[2])!=0 || Long.valueOf(strA[3])>Long.valueOf(fdate)){
				request.setAttribute("errorMsg", "该销售期未开始或已暂停!");
				  return mapping.findForward("errormsg");
			}
		}
		
		
		if("103".equals(gameCode) && chipinNums.indexOf(".txt") == -1){chipinNums = chipinNums.replaceAll("\\*","9");}   //任选9格式化
		else if("511".equals(gameCode) && chipinNums.indexOf(".txt") == -1){chipinNums=chipinNums.replaceAll("R", "");} //让球胜平负格式化
		else if("503".equals(gameCode) && chipinNums.indexOf(".txt") == -1){chipinNums=chipinNums.replaceAll("B", "");} //总进球格式化
		else if("601".equals(gameCode) && "602".equals(gameCode) && "603".equals(gameCode) && "604".equals(gameCode) && "605".equals(gameCode) && "606".equals(gameCode) && "607".equals(gameCode)){
			if("0".equals(manner)){manner = "1";}
		}
		String forward = "betSuccess";
		try{
			String username = super.getUserName(request);
			String password = super.getPassword(request);
			String[] params = new String[]{username,password,gameCode,issue,manner,title,description,isopen,openusers,isUpload,payofftc,money,multiple,copies,betcopies,eachPrice,ensures,chipinNums,hmfaType,spValue,moneyFw,"",""};
			List list=new WinsFlat().betting(request,response,params);
			Object[] obj=list.toArray();
			String[] bts = (String[])obj[0];
			request.setAttribute("id", bts[0]);
			response.sendRedirect(request.getContextPath()+"/member/serNoScheme_details.jsp?id="+bts[0]);
			return null;
		}catch(LotteryException e)
		{
			//request.setAttribute("errNo",e.getErrNo());
			request.setAttribute("errorMsg", e.getMessage());
			forward = "betfail";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			request.setAttribute("errorMsg", e.getMessage());
			forward = "betfail";
			e.printStackTrace();
		}
		return mapping.findForward(forward);
		}else{
			  this.saveToken(request); 
			  System.out.println("=================重复提交=========================");
			  return mapping.findForward("duplicateBetfail");
		}
	}
	
	public ActionForward BettingEntranceCup(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){
		
		response.setContentType("text/html;charset=UTF-8");
		String gameCode = request.getParameter("gameCode");//玩法类型
		String manner	= request.getParameter("manner");//投注方式
		String title    = request.getParameter("title");//标题
		String description    = request.getParameter("description");//描述
		String isopen    = request.getParameter("isopen");//是否公开
		String openusers    = request.getParameter("openusers");//面向全部网友
		String isUpload    = request.getParameter("isUpload");//是否上传
		String payofftc    = request.getParameter("payofftc");//提成比例
		String money    = request.getParameter("money");//投注总金额
		String multiple    = request.getParameter("Muliptile");//倍数
		String copies    = request.getParameter("copies");//总份数
		String betcopies    = request.getParameter("betcopies");//认购份数
		String eachPrice    = request.getParameter("eachPrice");//每份单价
		String ensures    = request.getParameter("ensures");//保底份数
		String chipinNums    = request.getParameter("chipinNums");//投注号码
		String hmfaType    = request.getParameter("hmfaType");//代购1,合买2
		String spValue    = request.getParameter("spvalue");//SP值
		String moneyFw    = request.getParameter("moneyFw");//奖金范围
		String issue    = request.getParameter("issue");//期号，竞彩没有期号unkonw
		
		
		if("103".equals(gameCode) && chipinNums.indexOf(".txt") == -1){chipinNums = chipinNums.replaceAll("\\*","9");}   //任选9格式化
		else if("511".equals(gameCode) && chipinNums.indexOf(".txt") == -1){chipinNums=chipinNums.replaceAll("R", "");} //让球胜平负格式化
		else if("601".equals(gameCode) && "602".equals(gameCode) && "603".equals(gameCode) && "604".equals(gameCode) && "605".equals(gameCode) && "606".equals(gameCode) && "607".equals(gameCode)){
			if("0".equals(manner)){manner = "1";}
		}
		String forward = "betSuccess";
		try{
			String username = super.getUserName(request);
			String password = super.getPassword(request);
			String[] params = new String[]{username,password,gameCode,issue,manner,title,description,isopen,openusers,isUpload,payofftc,money,multiple,copies,betcopies,eachPrice,ensures,chipinNums,hmfaType,spValue,moneyFw,"",""};
			List list=new WinsFlat().betting(request,response,params);
			Object[] obj=list.toArray();
			String[] bts = (String[])obj[0];
			request.setAttribute("id", bts[0]);
			//response.sendRedirect(request.getContextPath()+"/member/serNoScheme_details.jsp?id="+bts[0]);
			//return null;
		}catch(LotteryException e)
		{
			//request.setAttribute("errNo",e.getErrNo());
			request.setAttribute("errorMsg", e.getMessage());
			forward = "betfail";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			request.setAttribute("errorMsg", e.getMessage());
			forward = "betfail";
			e.printStackTrace();
		}
			try {
				if("betSuccess".equals(forward)){
				    response.setContentType("text/html;charset=UTF-8");
					PrintWriter out = response.getWriter();
					
					out.print("{\"items\":[");
					out.print("{\"strs\":\""+forward+"\"}");
					out.print("]}");
					out.flush();
					out.close();
					
				}else{
				    response.setContentType("text/html;charset=UTF-8");
					PrintWriter out = response.getWriter();
					out.print("{\"items\":[");
					out.print("{\"strs\":\""+forward+"\"}");
					out.print("]}");
					out.flush();
					out.close();
				}
				
			} catch (Exception e) {
			}
			return null;
	
	}
	/***
	 * CPS购买Action,如果购买成功则输出betSuccess失败则输出betfail,此接口要我们推送最新的消息到CPS网站
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException 
	 */
	public ActionForward BettingEntranceCPS(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException{
		
		response.setContentType("text/html;charset=UTF-8");
		String forward = "betSuccess";
		//url说明:必须传入的参数用户编号和密码,手机号码或邮箱至少传入一个,两个都传入的话优先选择手机号
		String testUrl="putForwordAction.do?action=BettingEntranceCPS&userid=zuoguobin&pwd=654321"+
        "&phone=18357002811" +//传入
        "&email=243517277@qq.com"+//传入
        "type=0" +//可以不传入,目前是传入,如果是不传入,则选择易中奖或高回报的给CPS联盟
        "&gameCode=501" +//目前只测试2串1暂时可以不传入
        "&manner=2" +//可以不传入
        "&title=过关投注" +//可以不传入
        "&description=此单太绝,跟单必赢" +//可以不传入
        "&isopen=0" +//可以不传入
        "&openusers=all" +//可以不传入
        "&isUpload=1" +//可以不传入
        "&payofftc=0" +//可以不传入
        "&money=2.00" +//可以不传入
        "&multiple=1" +//可以不传入
        "&copies=2" +//可以不传入
        "&betcopies=2" +//可以不传入
        "&eachPrice=1.00" +//可以不传入
        "&ensures=0" +//保底份数设计到合买,可以不传入
        "&chipinNums=61603,3,0//61605,3,0" +//做处理此处可以只传入期号(此处要校验期号是否过时,不是最新要跟新最新)
        "&hmfaType=1" +//可以不传入
        "&spValue=61603,1.32,0//61605,1.22,0" +//做处理可以只传入期号(此处要校验期号是否过时,如果传入的是赔率则还要检验赔率是否最新,不是最新要跟新最新)
        "&moneyFw=0-0" +//可以不传入
        "&issue=unknow" +//可以不传入
        "&buyType=0" +//此处自动判断可以不传入
        "&buyInfo=18357002811";//此处自动判断可以不传入
		System.out.println(testUrl);
		String phone = request.getParameter("phone");//玩法类型
		if(phone==null)phone="";
		String email = request.getParameter("email");//玩法类型
		if(email==null)email="";
		String gameCode = request.getParameter("gameCode");//玩法类型
		String manner	= request.getParameter("manner");//投注方式
		String title    = request.getParameter("title");//标题
		String description    = request.getParameter("description");//描述
		String isopen    = request.getParameter("isopen");//是否公开
		String openusers    = request.getParameter("openusers");//面向全部网友
		String isUpload    = request.getParameter("isUpload");//是否上传
		String payofftc    = request.getParameter("payofftc");//提成比例
		String money    = request.getParameter("money");//投注总金额
		String multiple    = request.getParameter("multiple");//倍数
		String copies    = request.getParameter("copies");//总份数
		String betcopies    = request.getParameter("betcopies");//认购份数
		String eachPrice    = request.getParameter("eachPrice");//每份单价
		String ensures    = request.getParameter("ensures");//保底份数
		String chipinNums    = request.getParameter("chipinNums");//投注号码
		String hmfaType    = request.getParameter("hmfaType");//代购1,合买2
		String spValue    = request.getParameter("spValue");//SP值
		String moneyFw    = request.getParameter("moneyFw");//奖金范围
		String issue    = request.getParameter("issue");//期号，竞彩没有期号unkonw
		String buyType=null;//购买类型
		String buyInfo=null;//购买信息
		
		//关于buy.do?useid=任君行代码&md=校验码&phone=手机号码&lottid=彩种id &timestamp=时间戳的修改
	    String md=request.getParameter("md");
		String testUrl2="putForwordAction.do?action=BettingEntranceCPS" +
	    "&userid=zuoguobin" +//合作码
		"&md=BCDERTWWFERWQXWFF"+//校验码，md5(合作方代码+md5(密码)+手机号码+时间戳)
        "&phone=18357002811" +//传入
        "&email=243517277@qq.com"+//传入
        "lottid=0" +//lottid表示彩票类型,这里指的的是高频彩11选5,大乐透,双色球等
        "&timestamp=2014070212053559-2014070212055050"+//时间戳,这段时间内购买才有效
        "&gameCode=501" +//目前只测试2串1暂时可以不传入
        "&manner=2" +//可以不传入
        "&title=过关投注" +//可以不传入
        "&description=此单太绝,跟单必赢" +//可以不传入
        "&isopen=0" +//可以不传入
        "&openusers=all" +//可以不传入
        "&isUpload=1" +//可以不传入
        "&payofftc=0" +//可以不传入
        "&money=2.00" +//可以不传入
        "&multiple=1" +//可以不传入
        "&copies=2" +//可以不传入
        "&betcopies=2" +//可以不传入
        "&eachPrice=1.00" +//可以不传入
        "&ensures=0" +//保底份数设计到合买,可以不传入
        "&chipinNums=61603,3,0//61605,3,0" +//做处理此处可以只传入期号(此处要校验期号是否过时,不是最新要跟新最新)
        "&hmfaType=1" +//可以不传入
        "&spValue=61603,1.32,0//61605,1.22,0" +//做处理可以只传入期号(此处要校验期号是否过时,如果传入的是赔率则还要检验赔率是否最新,不是最新要跟新最新)
        "&moneyFw=0-0" +//可以不传入
        "&issue=unknow" +//可以不传入
        "&buyType=0" +//此处自动判断可以不传入
        "&buyInfo=18357002811";//此处自动判断可以不传入
		//关于购买成功后返回的json格式
		 String returnJson="{"+
            "“phone”:”18788888888”"+
            "“orders”:["+
            "{“lottid”:”107”, ”lottname”:”山东11选5”, “orderNO”:””, ”type”:””, ”lottinfo”:””, ”count”:””, “money”:””“status”:””, “reward”:””},"+
             "]"+
             "}";
		 //描叙type:指的是彩种名称的类型值fourPoly(任选四复式)lottinfo是购买的信息,例如(01,02,03,04,05|01,02,08,09,10)
		 //count购买注数,status状态,分购买成功,出票和派奖这几种情况
	    
		
		try{
		if(!"".equals(phone)||!"".equals(email)){//如果手机或号码至少有一个不为空
			if(!"".equals(phone)){
				buyType="0";//如果手机不为空则设置为0
				buyInfo=phone;
			}else{
				buyType="1";//反之则是邮箱不为空设置为1
				buyInfo=email;
			}
		}
		
		String userid    = request.getParameter("userid");//用户编号
		String loginName="";
		if(userid!=null && !"".equals(userid)){
			loginName=new WinsFlat().findLoginNameByUserId(request, response, userid);
		}
		String pwd    = request.getParameter("pwd");//加密传过来的密码经过密钥解密需要和CPS厂商商量
	
		
		
		if("103".equals(gameCode) && chipinNums.indexOf(".txt") == -1){chipinNums = chipinNums.replaceAll("\\*","9");}   //任选9格式化
		else if("511".equals(gameCode) && chipinNums.indexOf(".txt") == -1){chipinNums=chipinNums.replaceAll("R", "");} //让球胜平负格式化
		else if("601".equals(gameCode) && "602".equals(gameCode) && "603".equals(gameCode) && "604".equals(gameCode) && "605".equals(gameCode) && "606".equals(gameCode) && "607".equals(gameCode)){
			if("0".equals(manner)){manner = "1";}
		}
		
	
			String username=loginName;
			String password=pwd;
			String[] params = new String[]{username,password,gameCode,issue,manner,title,description,isopen,openusers,isUpload,payofftc,money,multiple,copies,betcopies,eachPrice,ensures,chipinNums,hmfaType,spValue,moneyFw,buyType,buyInfo};
			List list=new WinsFlat().bettingCPS(request,response,params);
			Object[] obj=list.toArray();
			String[] bts = (String[])obj[0];
			request.setAttribute("id", bts[0]);
		}catch(Exception e)
		{
			
			forward = "betfail";
		}
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(forward);
		return null;
	}
	/***
	 * 处理数字彩的投注信息
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward BettingEntranceLotteryNumber(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){
		response.setContentType("text/html;charset=UTF-8");
		String fore=request.getParameter("fore");
		String back=request.getParameter("back");
		String ratio=request.getParameter("ratio");//注数
		
		
		String gameCode = request.getParameter("gameCode");//玩法类型,双色球201
		String manner	= request.getParameter("manner");//投注方式,1单关(双色球)
		String title    = request.getParameter("title");//标题
		String description    = request.getParameter("description");//描述
		String isopen    = request.getParameter("isopen");//是否公开
		String openusers    = request.getParameter("openusers");//面向全部网友默认all
		String isUpload    = request.getParameter("isUpload");//是否上传,默认为1,不上传
		String payofftc    = request.getParameter("payofftc");//提成比例
		String money    = request.getParameter("money");//投注总金额
		String multiple    = request.getParameter("Muliptile");//倍数
		String copies    = request.getParameter("copies");//总份数
		String betcopies    = request.getParameter("betcopies");//认购份数
		String eachPrice    = request.getParameter("eachPrice");//每份单价
		String ensures    = request.getParameter("ensures");//保底份数
		String chipinNums    = request.getParameter("chipinNums");//投注号码
		String hmfaType    = request.getParameter("hmfaType");//代购1,合买2
		String spValue    = request.getParameter("spvalue");//SP值,数字彩票没有赔率,赔率默认为0
		String moneyFw    = request.getParameter("moneyFw");//奖金范围,数字彩票没有奖金返回
		String issue    = request.getParameter("issue");//期号，竞彩没有期号unkonw,数字彩票有期号
		
		/**
		 * 暂时处理单买双色球
		 */
		Long moneyTemp=Long.valueOf(ratio)*2;
		money=moneyTemp.toString();//投注总金额处理
		Long copyiesTemp =Long.valueOf(ratio)*2;//总份数为倍数*2
		copies=copyiesTemp.toString();//处理总分数
		betcopies=copies;//处理认购份数,单买暂时是总份数
		multiple=ratio;//处理倍数,单买暂时是倍数
		
		gameCode="201";
		manner="1";
		title="双色球购买";
		description="双色球购买";
		isopen="0";//暂时公开
		openusers="all";//面向所有人
		isUpload="1";//不上传
		payofftc="0";//提成暂时为0
		//money="2";//投注总金额
		//multiple="1";//倍数
		//copies="2";//总分数
		//betcopies="2";//认购份数暂时等于总分数
		eachPrice="1";//每一份单价
		ensures="0";//保底份数,暂时为0
		
		//将force格式化
		fore=fore.replaceAll(",", "/")+"//"+back;//投注的号码
		chipinNums=fore;
		hmfaType="1";
		spValue="0";
		moneyFw="0";
		//issue="2014088";
		
		
		
		
		
		
		
		
		
		
		PrintWriter out=null;
		try {
			String username = super.getUserName(request);
			String password = super.getPassword(request);
			String buyType="";
			String buyInfo="";
			String[] params = new String[]{username,password,gameCode,issue,manner,title,description,isopen,openusers,isUpload,payofftc,money,multiple,copies,betcopies,eachPrice,ensures,chipinNums,hmfaType,spValue,moneyFw,buyType,buyInfo};
			List list=new WinsFlat().betting(request,response,params);
			 out = response.getWriter();
		} catch (IOException e) {
			out.print("error");
			e.printStackTrace();
		}
		out.print("success");
		return null;
	}
	
	public ActionForward BettingUpload(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){
		
		
		response.setContentType("text/html;charset=UTF-8");
		String time = TimeUtil.getDatetoString("yyyyMMddHHmmssSSSSSS", new Date());
		String dirPath=servlet.getServletContext().getRealPath("/");
		String filePath ="/upload/"+ time + ".txt";
		File file = new File(dirPath+"/"+filePath);
		String chipinNums    = request.getParameter("chipinNums");//投注号码
		String forward = "betSuccess";
		if(isTokenValid(request,true)){ 
		try {
			OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(file),"GBK");
			BufferedWriter osw=new BufferedWriter(write);
			String[] betNumArr = chipinNums.split("\\|");
			for(int i=0;i<betNumArr.length;i++)
			{
				String[] betnum = betNumArr[i].split("\\s");
				if(!betnum[1].equals("0")){
					osw.write(betnum[0]+"\t"+betnum[1]+"\t"+betnum[2]+"\t"+betnum[3].replaceAll("串", "_")+"\n");
				}
			}
			osw.close();
			write.close();
			String gameCode = request.getParameter("gameCode");//玩法类型
			String manner	= request.getParameter("manner");//投注方式
			String title    = request.getParameter("title");//标题
			String description    = request.getParameter("description");//描述
			String isopen    = request.getParameter("isopen");//是否公开
			String openusers    = request.getParameter("openusers");//面向全部网友
			String isUpload    = request.getParameter("isUpload");//是否上传
			String payofftc    = request.getParameter("payofftc");//提成比例
			String money    = request.getParameter("money");//投注总金额
			String multiple    = request.getParameter("Muliptile");//倍数
			String copies    = request.getParameter("copies");//总份数
			String betcopies    = request.getParameter("betcopies");//认购份数
			String eachPrice    = request.getParameter("eachPrice");//每份单价
			String ensures    = request.getParameter("ensures");//保底份数
			String chipinNumsPath    = dirPath+filePath;//投注号码
			String hmfaType    = request.getParameter("hmfaType");//代购1,合买2
			String spValue    = request.getParameter("spvalue");//SP值
			String moneyFw    = request.getParameter("moneyFw");//奖金范围
			String issue    = request.getParameter("issue");//期号，竞彩没有期号unkonw

			
	
			String username = super.getUserName(request);
			String password = super.getPassword(request);
			String[] params = new String[]{username,password,gameCode,issue,manner,title,description,isopen,openusers,isUpload,payofftc,money,multiple,copies,betcopies,eachPrice,ensures,chipinNumsPath,hmfaType,spValue,moneyFw};
			List list=new WinsFlat().betting(request,response,params);
			Object[] obj=list.toArray();
			String[] bts = (String[])obj[0];
			request.setAttribute("id", bts[0]);
			forward = "betSuccess";
			return mapping.findForward(forward);
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			request.setAttribute("errorMsg", e1.getMessage());
			forward = "betfail";
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			request.setAttribute("errorMsg", e1.getMessage());
			forward = "betfail";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			request.setAttribute("errorMsg", e.getMessage());
			forward = "betfail";
		}catch(LotteryException e)
		{
			//request.setAttribute("errNo",e.getErrNo());
			request.setAttribute("errorMsg", e.getMessage());
			forward = "betfail";
		}
		}else{
			  this.saveToken(request); 
			  System.out.println("=================重复提交=========================");
			  return mapping.findForward("duplicateBetfail");
		}
		return mapping.findForward(forward);
	}
	
	/**
	 * 
	 * @Title: brounsOpt
	 * @Description: 奖金优化提交转发
	 * @param @param mapping
	 * @param @param form
	 * @param @param request
	 * @param @param response
	 * @param @return
	 * @return ActionForward
	 * @throws
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward brounsOpt(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){
		this.saveToken(request);//防止重复提交的问题
		response.setContentType("text/html;charset=UTF-8");
		HashMap betMap = new HashMap();
		String info = request.getParameter("inf");
		String[] infoArr = info.split("\\$");
		String muliptile=request.getParameter("muliptile");
		String tzNumber=request.getParameter("tzNumber");
		String gameCode=request.getParameter("gameCode");
		if("513".equals(gameCode) || "514".equals(gameCode)){
			gameCode = "509";
		}
		String spzValue=request.getParameter("spzValue");
		String mcn=request.getParameter("McN");
		String zqmcn=request.getParameter("ZQMcN");
		String zhushu=request.getParameter("zhushu");
		String price=request.getParameter("price");
		String gType=request.getParameter("gType");
		String issue=request.getParameter("issue");
		String tempstr=request.getParameter("tempstr");
		String danmaid=request.getParameter("danmaid");
		String newhy=request.getParameter("newhy");
		int chop=Integer.parseInt(zhushu.trim())*Integer.parseInt(muliptile.trim())*2;
		
		StringBuffer strssid = new StringBuffer(); 
		for(int i=0;i<infoArr.length;i++){
			String[] ssid = infoArr[i].split(",");
			strssid.append(ssid[6]).append(",");
		}
		strssid.deleteCharAt(strssid.lastIndexOf(","));
		//HashMap marketMap = new WinsFlat().betting_sel(new String[]{strssid.toString()});
		betMap.put("Muliptile", muliptile); 
		betMap.put("money", price);
		betMap.put("zs", zhushu);
		betMap.put("mcn", mcn);
		betMap.put("manner", zqmcn);
		betMap.put("title", "过关投注");
		betMap.put("description", "过关投注");
		betMap.put("isopen", "1");
		betMap.put("openusers", "all");
		betMap.put("isUpload", "1");
		betMap.put("payofftc", "0");
		betMap.put("copies", "1");
		betMap.put("betcopies", "1");
		betMap.put("eachPrice", price);
		betMap.put("ensures", "0");
		betMap.put("chipinNums",tzNumber);
		betMap.put("hmfaType", "1");
		betMap.put("spvalue", spzValue);
		betMap.put("moneyFw", "0-0");
		betMap.put("issue", issue);
		betMap.put("info", info);
		betMap.put("gameCode", gameCode);
		betMap.put("strssid", strssid);
		betMap.put("tempstr", tempstr);
		betMap.put("danmaid", danmaid);
		betMap.put("newhy", newhy);
		String betjson = Json.toJson(betMap,JsonFormat.compact());
		request.setAttribute("betjson", betjson);
		return mapping.findForward("brounsopt");
	}
	/**
	 * 
	 * @Title: checkUserLogin
	 * @Description: 检测用户是否登录
	 * @param @param mapping
	 * @param @param form
	 * @param @param request
	 * @param @param response
	 * @param @return
	 * @return ActionForward
	 * @throws
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward checkUserLogin(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try{
			super.getUserName(request);
			out.println("{\"result\":\"0\"}");
		}catch(LotteryException e){
			out.println("{\"result\":\"1\"}");
		}
		return null;
	}
	
	/**
	 * 
	 * @Title: ChangePassword
	 * @Description: 修改密码
	 * @param @param mapping
	 * @param @param form
	 * @param @param request
	 * @param @param response
	 * @param @return
	 * @return ActionForward
	 * @throws
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException 
	 */
	public ActionForward ChangePassword(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException{
		
		response.setContentType("text/html;charset=UTF-8");
		String oldPassword = request.getParameter("oldPassword");
		String newPassword = request.getParameter("newPassword");
		String gread = request.getParameter("gread");
		String sessionPassword = super.getPassword(request);
		String sessionUserName = super.getUserName(request);
		
		PrintWriter out = response.getWriter();
		if(!oldPassword.equals(sessionPassword)){
			out.println("{\"result\":\"原密码输入错误!\"}");
			return null;
		}
		
		String[] params = new String[]{sessionUserName,newPassword,oldPassword,gread}; 
		try{
			new LoginManage().getPass(params, OperaterCode.PWD_UPDATE);
			String[] loginPar = new String[]{params[0],params[1],"sl","0000"}; 
			new WinsFlat().newLogin(request,response,loginPar);
			out.println("{\"result\":\"修改成功\"}");
		}catch(LotteryException ee)
		{
			out.println("{\"result\":\""+ee.getMessage()+"\"}");
			return null;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			out.println("{\"result\":\""+e.getMessage()+"\"}");
			return null;
		}
		return null;
	}
	
	/**
	 * 
	 * @Title: UserLogin
	 * @Description: 用户登陆
	 * @param @param mapping
	 * @param @param form
	 * @param @param request
	 * @param @param response
	 * @param @return
	 * @param @throws IOException
	 * @return ActionForward
	 * @throws
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception 
	 */
	public ActionForward UserLogin(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException{
		response.setContentType("textml;charset=UTF-8");
		String UserName = request.getParameter("UserName");
		String UserPassword = request.getParameter("UserPassword");
		String Page = java.net.URLDecoder.decode(request.getParameter("Page"));
		String[] loginPar = new String[]{UserName,UserPassword,"sl","0000"}; 
		PrintWriter out = response.getWriter();
		try {
			String loginRtrue = new WinsFlat().newLogin(request,response,loginPar);
			if(loginRtrue.indexOf("-")<=-1)
			{
				response.sendRedirect(request.getContextPath()+"/letoula/loginError.jsp?loginErr="+java.net.URLEncoder.encode(loginRtrue)+"&pages="+Page);
			}else
			{
				if(Page==null || Page.equals("") || Page.equals("null")){
					response.sendRedirect(request.getContextPath());
				}else{
					response.sendRedirect(request.getContextPath()+"/member/"+Page);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			out.println("<script type='text/javascript'>alert('"+e.getMessage()+"');</script>");
			response.sendRedirect(request.getContextPath()+"/member/login.jsp");
		}
		return null;
	}

	
	/**
	 * 
	 * @Title: emailPut
	 * @Description: 找回密码
	 * @param @param mapping
	 * @param @param form
	 * @param @param request
	 * @param @param response
	 * @param @return
	 * @return ActionForward
	 * @throws
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward emailPut(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)throws Exception{
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=UTF-8");
		   String userName = request.getParameter("uName");
		   String qusition = request.getParameter("qusition");
		   String answer = request.getParameter("answer");
		   
		   System.out.println(userName+"============="+qusition+"========="+answer);
		   String[] params = {userName,qusition,answer};
		   try{
			   new WinsFlat().ShowUserPassword(params);
			   request.setAttribute("errorMsg", "成功找回密码，请在邮箱收取新的密码登陆！");
		   }catch(LotteryException e)
		   {
			   request.setAttribute("errorMsg", e.getMessage());
		   }
		   return mapping.findForward("errormsg");
	   }
	
}
