package com.zhiwei.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.zhiwei.chendong.ExcelReadAndWrite;
import com.zhiwei.chendong.ReaderExcel;
import com.zhiwei.util.Config;
import com.zw.entity.Excels;
import com.zw.entity.Weixin;

@Controller
public class MainController {

	private final static Log log = LogFactory.getLog(MainController.class);
	public static Vector<Excels> lists = new Vector<Excels>();
	public static Map<String, Integer> map = new HashMap<String, Integer>();
	public static Excels excel = null;
	public static int finished = 0;

	@RequestMapping("/scanExcel")
	public String mian() {
		return "test";
	}

	@RequestMapping(value = "/show")
	public void shows(HttpServletRequest request, HttpServletResponse response) throws IOException {
		System.out.println(lists.size());
		try {
			for (int i = 0; i < lists.size(); i++) {
				Excels e = lists.get(i);
				e.setSite(i + 1);
			}
			response.setContentType("text/plain;charset=utf-8");
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			response.setHeader("Access-Control-Allow-Origin", "*");
			PrintWriter out = response.getWriter();
			String jsonpCallback = request.getParameter("callback");// 客户端请求参数
			out.println(JSON.toJSONString(lists));// 返回jsonp格式数据
			out.flush();
			out.close();
			System.out.println(lists.size());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "/downLode")
	public void downLode(HttpServletRequest request, HttpServletResponse response) {
		System.out.println(ExcelReadAndWrite.findEf());
		try {
			response.setContentType("text/plain;charset=utf-8");
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			response.setHeader("Access-Control-Allow-Origin", "*");
			PrintWriter out = response.getWriter();
			// String jsonpCallback = request.getParameter("callback");//
			// 客户端请求参数
			out.println(JSON.toJSONString(ExcelReadAndWrite.findEf()));//
			out.flush();
			out.close();
			System.out.println("当前队列长度：" + lists.size());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "/downLodeFile")
	public void downFile(HttpServletRequest request, HttpServletResponse response, String id) {
		System.out.println(ExcelReadAndWrite.findEf());
		try {
			response.setContentType("application/msexcel;");
			response.setHeader("Content-Disposition",
					new String(("attachment;filename=" + "downLode.xls").getBytes("GB2312"), "UTF-8"));
			File f = new File(ExcelReadAndWrite.findById(id));
			FileInputStream in = new FileInputStream(f);
			byte b[] = new byte[1024];
			int i = 0;
			ServletOutputStream out = response.getOutputStream();
			while ((i = in.read(b)) != -1) {
				out.write(b, 0, i);
			}
			out.flush();
			out.close();
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "/delete")
	public void delete(HttpServletRequest request, HttpServletResponse response, String id) {
		Map<String, Boolean> map = new HashMap<String, Boolean>();
		boolean b = false;
		List<Excels> list = new ArrayList<Excels>();
		if (id != null)
			for (Excels ex : lists) {
				if (ex.getId().equals(id)) {
					list.add(ex);
					b = true;
				}
			}
		for (Excels e : list) {
			lists.remove(e);
		}
		response.setContentType("text/plain;charset=utf-8");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setHeader("Access-Control-Allow-Origin", "*");
		PrintWriter out;
		map.put("result", b);
		try {
			out = response.getWriter();
			out.println(JSON.toJSONString(map));// 返回jsonp格式数据
			out.flush();
			out.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

	@RequestMapping(value = "cutQ")
	public void cutQ(HttpServletRequest request, HttpServletResponse response, String id) {
		Map<String, Boolean> map = new HashMap<String, Boolean>();
		boolean b = false;
		if (ExcelReadAndWrite.cut) {
		} else {
			if (id != null) {
				String msg = ExcelReadAndWrite.startCut(id);
				if (msg.contains("ok"))
					;
				b = true;
			}
		}
		response.setContentType("text/plain;charset=utf-8");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setHeader("Access-Control-Allow-Origin", "*");
		PrintWriter out;
		map.put("result", b);
		try {
			out = response.getWriter();
			out.println(JSON.toJSONString(map));// 返回jsonp格式数据
			out.flush();
			out.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

	@RequestMapping("/sh")
	public String showPage() {
		return "dataTable";
	}

	@RequestMapping("/admin")
	public String showPageAdmin() {
		return "dataTable2";
	}

	@RequestMapping("/down")
	public String down() {
		return "dataTable3";
	}

	@RequestMapping(value = "/up")
	public String up(HttpServletRequest req, HttpServletResponse res, MultipartFile file, String mail, String mail2)
			throws Exception {
		if (!mail.equals(mail2)) {
			return "error";
		}
		System.out.println(mail);
		log.info(mail);
		// 得到上传文件的保存目录，将上传的文件存放于WEB-INF目录下，不允许外界直接访问，保证上传文件的安全
		String fileName = file.getOriginalFilename();
		if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {// 是否是excel结尾的
			String path = Config.getVal("timefileUrl") + "/" + mail + fileName;
			log.info(path);
			File targetFile = new File(path);
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			// 保存
			try {
				file.transferTo(targetFile);
			} catch (Exception e) {
				e.printStackTrace();
			}
			Excels excel = new Excels();
			List<Weixin> list = ReaderExcel.getExcel(path);
			if (list.size() == 0 || list.size() > 35000) {
				return "error2";
			}
			excel.setId((int) (Math.random() * 50000) + "k");
			excel.setNeed((list.size() * 5 + 40) / 60);
			excel.setMail(mail);
			excel.setUrl(path);
			excel.setSite(0);
			excel.setSurplusCount(list.size());
			excel.setStartDate("未开始");
			log.info("数据量" + list.size());
			System.out.println(list.size());
			lists.add(excel);
			if (!ExcelReadAndWrite.runStrat) {
				Thread t = new Thread() {
					@Override
					public void run() {
						try {
							ExcelReadAndWrite.save2();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				};
				t.start();
			}
			return "redirect:sh";
		}
		return "error3";
	}

	@RequestMapping(value = "/zhNum", produces = "application/json;charset=utf-8")
	@ResponseBody
	public String getzhNum() {
		return JSON.toJSONString(map);
	}

	@RequestMapping("/zh")
	public String zh() {
		return "zhihu";
	}
}
