package com.letousky.lottery.action;

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

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 com.letousky.lottery.util.CheckCodes;
import com.letousky.lottery.util.TimeUtil;

@SuppressWarnings("serial")
public class Upload 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 {
    	String lot = request.getParameter("lot");
        request.setCharacterEncoding("UTF-8"); // 防止中文乱码
        response.setContentType("text/html;charset=UTF-8");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        int countLine = 0 , chang = 0 , m = 0;
        String error = "";
        String time = TimeUtil.getDatetoString("yyyyMMddHHmmssSSSSSS", new Date());
		String filePath ="/upload/"+ time + ".txt";
		String encoding = "UTF-8";
        try {
        	
            List items = upload.parseRequest(request);
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                if (item.isFormField()) {
                    System.out.println("表单参数名：" + item.getFieldName() + ",表单参数值：" + 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类型的文件！";
                    	}
                        String data = null;
                        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 line : lines){
                        	String s = line;
                    		if("".equals(s)){
                    			
                    			continue;
                    		}
                    		
                    		String flag = "";
                    		if("103".equals(lot) || "102".equals(lot) || "106".equals(lot) || "107".equals(lot)){
                    			if("103".equals(lot)) {
                    				if(s.indexOf("*") != -1) s = s.replace("*", "9").trim();
                    				else if(s.indexOf("#") != -1) s = s.replace("#", "9").trim();
                    			}
                    			if(s.indexOf(",") != -1) s = s.replace(",", "").trim();
                    			flag =new CheckCodes().CheckCodes(lot,s);
                    			fout.write(s+"\n");
                    		}
                    		else if("301".equals(lot) || "302".equals(lot) || "303".equals(lot) || "304".equals(lot) || "305".equals(lot)){
                    			 if(s.split("\\s")[0].indexOf(",")!=-1){
                    				 chang = s.split("\\s")[0].split(",").length;
                    			 }else if(s.split("\\s")[0].indexOf(";")!=-1){
                    				 chang = s.split("\\s")[0].split(";").length;
                    				 s = s.replaceAll("->", "→").replaceAll(";", ",");
                    			 }
                    			flag =new CheckCodes().CheckCodesDc(lot,s);
                    			if("304".equals(lot))
                    			{
                    				s = s.replaceAll("胜其他", "4:3");
                    				s = s.replaceAll("平其他", "4:4");
                    				s = s.replaceAll("负其他", "3:4");
                    			}
                    			fout.write(s+"\n");
                    		}
                    		else if("501".equals(lot) || "502".equals(lot) || "503".equals(lot) || "504".equals(lot) || "505".equals(lot) || "511".equals(lot)){
                    			flag =new CheckCodes().CheckCodesJC(lot,s);
                    			chang = s.split("\\s")[0].split(";").length;
                    			fout.write(s+"\n");
                    		}
                    		String[] codes = s.split("\\s");
                			if(codes.length >= 3){
                				m += Integer.parseInt(codes[1]);
                			}else{
                				m++;
                			}
                    		countLine++;
                    		if(!"success".equals(flag)){
                    			error = "第"+countLine+"行错误,"+flag;
                    			break;
                    		}
                         }
                        }
                        
                        
                        if(error.length() > 0){
                        	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();
                        	response.getWriter().print("{\"result\":\"1111\",\"error\":\""+error+"\"}");
                        	return;
                        }
                        fout.flush();
                        fout.close();
                        br.close();
                        fouts.close();
                    } else {
                    	response.getWriter().print("{\"result\":\"1111\",\"error\":\"没有选择文件\"}");
                        return;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().print("{\"result\":\"1111\",\"error\":\"上传文件失败\"}");
            return;
        }
        response.getWriter().println("{\"result\":\"0000\",\"time\":\""+time+"\",\"chang\":\""+chang+"\",\"countLine\":\""+countLine+"\",\"filePath\":\""+filePath+"\",\"m\":\""+m+"\"}");
    }
}