package com.letousky.lottery.action;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;

import com.letousky.lottery.util.CheckCodes;
import com.letousky.lottery.util.TimeUtil;

public class JcUpload extends HttpServlet{
	
	private ServletContext sc;
    private String uploadDir = "downloads";
    public static final String localhost = "d:/";
    
	@Override
    public void init(ServletConfig config) {
        sc = config.getServletContext();
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        doPost(request, response);
    }
    
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    	request.setCharacterEncoding("UTF-8"); // 防止中文乱码
        response.setContentType("text/html;charset=UTF-8");
        String lot = request.getParameter("gameid");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        RequestDispatcher dispatcher = request.getRequestDispatcher("/letoula/jingcai/beterror.jsp");
        String time = TimeUtil.getDatetoString("yyyyMMddHHmmssSSSSSS", new Date());
        String filePath ="/upload/"+ time + ".txt";
        String encoding = "UTF-8";
        String[] params=new String[21];
        String issue = "unkonw";
		String match = "" , selectUd = "0";
		String error = "";
		int countLine = 0 , chang = 0 , m = 0;
		try{
			List items = upload.parseRequest(request);
			Iterator itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				 if (item.isFormField()) {
					 if("match".equals(item.getFieldName())){
	                    match = item.getString("UTF-8");
	                 }else if("selectUd".equals(item.getFieldName())){
	                	 selectUd = item.getString("UTF-8");
	                 }
				 }else{
					 if (item.getName() != null && !item.getName().equals("")) {
						 if(item.getSize() > 10485760){
							 error = "您的注数太多，最大不要超过10M";
						 }else if(item.getName().indexOf(".txt") == -1){
	                    	 error = "您上传的文件类型错误，必须为.txt类型的文件！";
	                     }
						 File file = new File(filePath);
						 item.write(file);
						 String temp = "" , str = "";
	                     BufferedReader  br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),"GBK"));
	                     while ((temp = br.readLine()) != null) {
	                    	 str += temp + "/";
	                     }
	                     str = str.substring(0,str.length()-1);
	                     FileOutputStream fouts = new FileOutputStream(file);
	                     Writer fout = new OutputStreamWriter(fouts, "GBK");
	                     String[] lines = str.split("/");
	                     if(error.length() <= 0){
	                    	 for(String betNumLine : lines){
	                    		 String flag = "";
	                    		 if("".equals(betNumLine)) continue;
	                    		 if("502".equals(lot))
		                    	 {
		                    			betNumLine = betNumLine.replaceAll("胜其他", "43");
		                    			betNumLine = betNumLine.replaceAll("平其他", "44");
		                    			betNumLine = betNumLine.replaceAll("负其他", "34");
		                    	 }
	                    		 if("0".equals(selectUd)){
	                    			 if(betNumLine.indexOf("#")!=-1 || betNumLine.indexOf("*")!=-1 || betNumLine.indexOf(" ")!=-1 || betNumLine.indexOf("-")!=-1 || betNumLine.indexOf(",")!=-1){
	                     				StringBuffer getNum = new  StringBuffer();
	                     				String[] matchArr = match.split("\\|");
	                     				String[] numTx = null;
	                     				int l = 0 , t = 1;
	                     				if(betNumLine.indexOf("#")!=-1 || betNumLine.indexOf("*")!=-1) {numTx=betNumLine.split(""); l = 1;}
	                     				else if(betNumLine.indexOf(" ")!=-1) {numTx=betNumLine.split("\\ ");}
	                     				else if(betNumLine.indexOf("-")!=-1) {numTx=betNumLine.split("\\-");}
	                     				else if(betNumLine.indexOf(",")!=-1) {numTx=betNumLine.split("\\,");}
	                     				
	                     				for(;l<numTx.length;l++)
	                     				{
	                     					if(!numTx[l].equals("*") && !numTx[l].equals("#") && numTx[l]!=null && !numTx[l].equals("") && matchArr[t-1]!=null){
	                     						if("502".equals(numTx[l])){
	                     							numTx[l] = numTx[l].charAt(0) + ":" + numTx[l].charAt(1); 
	                     						}else if("504".equals(numTx[l])){
	                     							numTx[l] = numTx[l].charAt(0) + "_" + numTx[l].charAt(1); 
	                     						}
	                     						getNum.append(matchArr[t-1]).append("→").append(numTx[l]).append(";");
	                     					}
	                     					t++;
	                     				}
	                     				getNum.deleteCharAt(getNum.lastIndexOf(";"));
	                     				betNumLine = getNum.toString();
	                     			}else if(betNumLine.matches("\\d{2,8}")){
	                     				String[] matchArr = match.split("\\|");
	                     				StringBuffer getNum = new  StringBuffer();
	                     				for(int i=0;i<betNumLine.length();i++)
	                     				{
	                     					String bnl = String.valueOf(betNumLine.charAt(i));
	                     					if(bnl!=null && !"".equals(bnl) && matchArr[i]!=null){
	                     						if("502".equals(bnl)){
	                     							bnl = bnl.charAt(0) + ":" + bnl.charAt(1); 
	                     						}else if("504".equals(bnl)){
	                     							bnl = bnl.charAt(0) + "_" + bnl.charAt(1); 
	                     						}
	                     						getNum.append(matchArr[i]).append("→").append(bnl).append(";");
	                     					}
	                     				}
	                     				getNum.deleteCharAt(getNum.lastIndexOf(";"));
	                     				betNumLine = getNum.toString();
	                     			}
	                    		 }
	                    		 if(betNumLine.split("\\s")[0].indexOf(",")!=-1){
                    				 chang = betNumLine.split("\\s")[0].split(",").length;
                    			 }else if(betNumLine.split("\\s")[0].indexOf(";")!=-1){
                    				 chang = betNumLine.split("\\s")[0].split(";").length;
                    				 betNumLine = betNumLine.replaceAll("->", "→").replaceAll(";", ",");
                    			 }
	                    		 flag =new CheckCodes().CheckCodesJC(lot,betNumLine);
	                    		 
	                    		fout.write(betNumLine+"\n");
	                    		issue = "-1";
	                    		
	                    		String[] codes = betNumLine.split("\\s");
	                			if(codes.length >= 3){
	                				m += Integer.parseInt(codes[1]);
	                			}else{
	                				m++;
	                			}
	                			countLine++;
	                    		if(!"success".equals(flag)){
	                    			error = "第"+countLine+"行错误,"+flag;
	                    			request.setAttribute("result", "1111");
	                            	request.setAttribute("errorMsg", "第"+countLine+"行错误,"+flag);
	                            	request.setAttribute("lot", lot);
	                            	dispatcher.forward(request, response);
	                            	return;
	                    		}
	                    		
	                    	 }
	                     }else{
	                    	 if(file.exists()) {
	                        	Runtime run = Runtime.getRuntime(); 
	                        	try { 
	                        		/*String cmd = "rm -rf "+ filePath;*/
	                        		//String cmd = "del "+ filePath;
	                        		//Process p = run.exec(cmd); //cmd为String，其内容为对应系统的删除命令，例如：在win下，应该写成：String cmd = "del "+你的文件路径以及文件名; 
	                        		//p.waitFor();
	                        	} catch (Exception e) { 
	                        		e.printStackTrace(); 
	                        	}

	                        }
	                        fout.flush();
	                        fout.close();
	                        br.close();
	                        fouts.close();
	                        request.setAttribute("result", "1111");
	                        request.setAttribute("errorMsg", error);
	                        request.setAttribute("lot", lot);
	                        dispatcher.forward(request, response);
	                        return;
	                     }
	                     fout.flush();
	                     fout.close();
	                     br.close();
	                     fouts.close();
					 }
				 }
			}
			
		}catch(Exception e){
			 request.setAttribute("result", "1111");
	         request.setAttribute("errorMsg", "上传文件失败");
	         request.setAttribute("lot", lot);
	         dispatcher.forward(request, response);
	         return;
		}
		
		String bets = String.valueOf(m * 2);
    	HashMap betMap = new HashMap();
    	betMap.put("Muliptile", "1"); 
		betMap.put("money", bets);
		betMap.put("zs", m);
		betMap.put("mcn", chang);
		betMap.put("manner", "1");
		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", bets);
		betMap.put("ensures", "0");
		betMap.put("chipinNums",filePath);
		betMap.put("hmfaType", "1");
		betMap.put("spvalue", "spzValue");
		betMap.put("moneyFw", "0-0");
		betMap.put("issue", issue);
		betMap.put("info", "info");
		betMap.put("gameCode", lot);
		betMap.put("strssid", "sid");
		String betjson = Json.toJson(betMap,JsonFormat.compact());
		request.setAttribute("betjson", betjson);
    	request.getRequestDispatcher("/letoula/BetUpload.jsp").forward(request, response);
    }
    
    public String getManner(int chang){
    	String manner = "";
    	switch(chang){
    	case 2:manner="2";break;
    	case 3:manner="4";break;
    	case 4:manner="7";break;
    	case 5:manner="11";break;
    	case 6:manner="16";break;
    	case 7:manner="22";break;
    	case 8:manner="23";break;
    	case 9:manner="24";break;
    	case 10:manner="25";break;
    	case 11:manner="26";break;
    	case 12:manner="27";break;
    	case 13:manner="28";break;
    	case 14:manner="29";break;
    	case 15:manner="30";break;
    	}
    	return manner;
    }
}
