package com.zhiwei.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
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.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.zhiwei.chendong.ExcelReadAndWrite;
import com.zhiwei.readWechat.ReadExcel;
import com.zhiwei.readWechat.WechatReadAndWrite;
import com.zhiwei.util.Config;
import com.zw.entity.Excels;
import com.zw.entity.ReadWechat;

/**
 * 点赞阅读
 * 
 * @author admin
 *
 */
@Controller
public class RwController {
	private final static Log log = LogFactory.getLog(RwController.class);

	public static Vector<Excels> weChatList = new Vector<Excels>();

	/**
	 * 点赞阅读下载文件接口
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/rwdownLode")
	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();
			out.println(JSON.toJSONString(WechatReadAndWrite.findEf()));//
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 点赞阅读文件下载
	 * 
	 * @param request
	 * @param response
	 * @param id
	 */
	@RequestMapping(value = "/rwdownLodeFile")
	public void downFile(HttpServletRequest request, HttpServletResponse response, String id) {
		try {
			response.setContentType("application/msexcel;");
			response.setHeader("Content-Disposition",
					new String(("attachment;filename=" + "downLode.xls").getBytes("GB2312"), "UTF-8"));
			File f = new File(WechatReadAndWrite.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();
		}
	}

	/**
	 * 点赞阅读文件上传
	 * 
	 * @param req
	 * @param res
	 * @param file
	 * @param mail
	 * @param mail2
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/weChatup")
	public String weChatup(HttpServletRequest req, HttpServletResponse res, MultipartFile file, String mail,
			String mail2) throws Exception {
		if (!mail.equals(mail2)) {
			return "error";
		}
		log.info(mail);
		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<ReadWechat> list = ReadExcel.getExcel(path);
			if (list.size() == 0 || list.size() > 35000) {
				return "error2";
			}
			excel.setId((int) (Math.random() * 5000) + "wechat");
			excel.setNeed((list.size() * 50 + 40) / 60);
			excel.setMail(mail);
			excel.setUrl(path);
			excel.setSite(0);
			excel.setSurplusCount(list.size());
			excel.setStartDate("未开始");
			log.info("数据量" + list.size());
			weChatList.add(excel);
			if (!WechatReadAndWrite.runStrat) {
				Thread t = new Thread() {
					@Override
					public void run() {
						try {
							WechatReadAndWrite.work();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				};
				t.start();
			}
			return "redirect:rwsh";
		}
		return "error3";
	}

	/**
	 * 点赞阅读上传后的显示页面
	 * 
	 * @return
	 */
	@RequestMapping("/rwsh")
	public String readshowPage() {
		return "readShow";
	}

	/**
	 * 点赞阅读的下载页面
	 * 
	 * @return
	 */
	@RequestMapping("/rwdown")
	public String rwdown() {
		return "readWechatDown";
	}

	/**
	 * 点赞阅读的上传文件页面
	 * 
	 * @return
	 */
	@RequestMapping("/rwExcel")
	public String rwExcel() {
		return "readWechat";
	}

	/**
	 * 点赞阅读数据显示接口
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/rwShow")
	public void readShows(HttpServletRequest request, HttpServletResponse response) throws IOException {
		System.out.println(weChatList.size());
		try {
			for (int i = 0; i < weChatList.size(); i++) {
				Excels e = weChatList.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();
			out.println(JSON.toJSONString(weChatList));// 返回jsonp格式数据
			out.flush();
			out.close();
			System.out.println(weChatList.size());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
