package com.zhiwei.chendong;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.zhiwei.servlet.MainController;
import com.zhiwei.util.Config;
import com.zw.entity.ExcelFile;
import com.zw.entity.Excels;
import com.zw.entity.Weixin;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import sendmail.SendMailUtil;

public class ExcelReadAndWrite {

	private final static Log log = LogFactory.getLog(ExcelReadAndWrite.class);
	public static Excels e;
	public static boolean cut = false;
	public static String url = Config.getVal("basefile");
	public static boolean runStrat = false;
	public static int cutCount = 0;
	public static String host = Config.getVal("socketIp");
	public static int port = Integer.valueOf(Config.getVal("socketPort"));
	private static MongoForChenDong m = new MongoForChenDong();

	public static List<Weixin> readExcels(String url) {
		InputStream stream = null;
		String str = null;
		List<Weixin> list = new ArrayList<>();
		try {
			stream = new FileInputStream(url);
			Workbook rwb = Workbook.getWorkbook(stream);
			Sheet sheet = rwb.getSheet(0);
			for (int i = 1; i < sheet.getRows(); i++) {
				Cell cell = null;
				Weixin w = new Weixin();
				for (int j = 0; j < sheet.getColumns(); j++) {
					cell = sheet.getCell(j, i);
					str = cell.getContents();
					if (sheet.getCell(j, 0).getContents().equals("来源")) {
						w.setSource(str);
					}
					if (sheet.getCell(j, 0).getContents().equals("时间")) {
						w.setTime(str == null ? "null" : str);
					}
					if (sheet.getCell(j, 0).getContents().equals("标题")) {
						w.setTitle(str);
					}
					if (sheet.getCell(j, 0).getContents().equals("地址")) {
						w.setUrl(str == null ? "null" : str);
					}
					if (sheet.getCell(j, 0).getContents().equals("内容")) {
						w.setConetent(str);
						;
					}
					if (sheet.getCell(j, 0).getContents().equals("关键词")) {
						w.setKeyValue(str);
					}
					if (sheet.getCell(j, 0).getContents().equals("阅读数")) {
						w.setRead(str == null ? "null" : str);
					}
					if (sheet.getCell(j, 0).getContents().equals("点赞数")) {
						w.setZan(str == null ? "null" : str);
					}
					if (sheet.getCell(j, 0).getContents().equals("用户昵称")) {
						w.setNickname(str == null ? "null" : str);
					}
					if (sheet.getCell(j, 0).getContents().equals("简介")) {
						w.setJianjie(str == null ? "null" : str);
					}
					if (sheet.getCell(j, 0).getContents().equals("历史标注情况")) {
						w.setHistory(str == null ? "null" : str);
					}
					if (sheet.getCell(j, 0).getContents().equals("长地址")) {
						w.setLongUrl(str == null ? "null" : str);
					}
					if (sheet.getCell(j, 0).getContents().equals("mark")) {
						w.setMark(str == null ? "null" : str);
					}
					if (sheet.getCell(j, 0).getContents().equals("mark_time")) {
						w.setMark_time(str == null ? "null" : str);
					}
					if (sheet.getCell(j, 0).getContents().equals("markname")) {
						w.setMarkname(str == null ? "null" : str);
					}
					if (sheet.getCell(j, 0).getContents().equals("真实阅读数")) {
						w.setTrueRead(str == null ? "null" : str);
					}
				}
				if (w != null) {
					list.add(w);
				}
			}
			stream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	public static void write(List<Weixin> list, String mail) throws Exception {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String inurl = url + (int) (Math.random() * 99) + sdf.format(cal.getTime()) + ".xls";
		File tempFile = new File(inurl);
		// 若是文件不存在就创建新文件
		if (!tempFile.exists()) {
			tempFile.createNewFile();
		}
		WritableWorkbook workbook = Workbook.createWorkbook(tempFile);
		WritableSheet sheet = workbook.createSheet("table1", 0);
		// 一些临时变量，用于写到excel中
		Label l = null;
		// 标题格式
		WritableFont titleFont = new WritableFont(WritableFont.ARIAL, 14, WritableFont.NO_BOLD, false,
				UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK);
		WritableCellFormat titleFormat = new WritableCellFormat(titleFont);
		titleFormat.setAlignment(Alignment.CENTRE);
		// 正文字体
		WritableFont detFont = new WritableFont(WritableFont.ARIAL, 13, WritableFont.NO_BOLD, false,
				UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK);
		WritableCellFormat detFormat = new WritableCellFormat(detFont);
		detFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
		// 财新小字
		WritableFont detFont2 = new WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD, false,
				UnderlineStyle.NO_UNDERLINE, Colour.WHITE);
		WritableCellFormat detFormat2 = new WritableCellFormat(detFont2);
		detFormat2.setBackground(Colour.BLUE_GREY);
		WritableCellFormat detFormat3 = new WritableCellFormat(detFont2);
		detFormat3.setBackground(Colour.BLUE_GREY);
		detFormat3.setAlignment(Alignment.CENTRE);
		WritableFont urlf = new WritableFont(WritableFont.ARIAL, 11, WritableFont.NO_BOLD, false,
				UnderlineStyle.NO_UNDERLINE, Colour.BLUE);
		WritableCellFormat urlFormat = new WritableCellFormat(urlf);
		urlFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
		int seq = 0;
		l = new Label(0, seq, "来源");
		sheet.addCell(l);
		l = new Label(1, seq, "时间");
		sheet.addCell(l);
		l = new Label(2, seq, "内容");
		sheet.addCell(l);
		l = new Label(3, seq, "关键词");
		sheet.addCell(l);
		l = new Label(4, seq, "标题");
		sheet.addCell(l);
		l = new Label(5, seq, "地址");
		sheet.addCell(l);
		l = new Label(6, seq, "获取的地址");
		sheet.addCell(l);
		for (Weixin w : list) {
			seq++;
			l = new Label(0, seq, w.getSource());
			sheet.addCell(l);
			l = new Label(1, seq, w.getTime());
			sheet.addCell(l);
			l = new Label(2, seq, w.getConetent());
			sheet.addCell(l);
			l = new Label(3, seq, w.getKeyValue());
			sheet.addCell(l);
			l = new Label(4, seq, w.getTitle());
			sheet.addCell(l);
			l = new Label(5, seq, w.getUrl());
			sheet.addCell(l);
			l = new Label(6, seq, w.getGetUrl());
			sheet.addCell(l);
		}
		int column = 0;
		sheet.setColumnView(column++, 20);
		sheet.setColumnView(column++, 25);
		sheet.setColumnView(column++, 25);
		sheet.setColumnView(column++, 25);
		sheet.setColumnView(column++, 30);
		sheet.setColumnView(column++, 80);
		sheet.setColumnView(column++, 90);
		workbook.write();
		workbook.close();
		log.info("内容写入成功");
		SendMailUtil.sendMessage(mail, inurl, "ccxe");
		ExcelFile ef = new ExcelFile();
		ef.setMail(mail);
		ef.setUrl(inurl);
		insert(ef);
		System.out.println("发送完成");
	}

	public static void write2222(List<Weixin> list) throws IOException, RowsExceededException, WriteException {
		File tempFile = new File(url);
		// 若是文件不存在就创建新文件
		if (!tempFile.exists()) {
			tempFile.createNewFile();
		}
		WritableWorkbook workbook = Workbook.createWorkbook(tempFile);
		WritableSheet sheet = workbook.createSheet("table1", 0);
		// 一些临时变量，用于写到excel中
		Label l = null;
		int seq = 0;
		l = new Label(0, seq, "标题");
		sheet.addCell(l);
		l = new Label(1, seq, "阅读数");
		sheet.addCell(l);
		l = new Label(2, seq, "点赞数");
		sheet.addCell(l);
		l = new Label(3, seq, "时间");
		sheet.addCell(l);
		l = new Label(4, seq, "用户昵称");
		sheet.addCell(l);
		l = new Label(5, seq, "地址");
		sheet.addCell(l);
		l = new Label(6, seq, "简介");
		sheet.addCell(l);
		l = new Label(7, seq, "历史标注");
		sheet.addCell(l);
		l = new Label(8, seq, "长地址");
		sheet.addCell(l);
		l = new Label(9, seq, "mark");
		sheet.addCell(l);
		l = new Label(10, seq, "mark_time");
		sheet.addCell(l);
		l = new Label(11, seq, "markname");
		sheet.addCell(l);
		l = new Label(12, seq, "真实阅读数");
		for (Weixin w : list) {
			seq++;
			l = new Label(0, seq, w.getTitle());
			sheet.addCell(l);
			l = new Label(1, seq, w.getRead());
			sheet.addCell(l);
			l = new Label(2, seq, w.getZan());
			sheet.addCell(l);
			l = new Label(3, seq, w.getTime());
			sheet.addCell(l);
			l = new Label(4, seq, w.getNickname());
			sheet.addCell(l);
			l = new Label(5, seq, w.getGetUrl());
			sheet.addCell(l);
			l = new Label(6, seq, w.getJianjie());
			sheet.addCell(l);
			l = new Label(7, seq, w.getHistory());
			sheet.addCell(l);
			l = new Label(8, seq, w.getLongUrl());
			sheet.addCell(l);
			l = new Label(9, seq, w.getMark());
			sheet.addCell(l);
			l = new Label(10, seq, w.getMark_time());
			sheet.addCell(l);
			l = new Label(11, seq, w.getMarkname());
			sheet.addCell(l);
			l = new Label(12, seq, w.getTrueRead());
		}

		int column = 0;
		sheet.setColumnView(column++, 20);
		sheet.setColumnView(column++, 25);
		sheet.setColumnView(column++, 25);
		sheet.setColumnView(column++, 25);
		sheet.setColumnView(column++, 30);
		sheet.setColumnView(column++, 80);
		sheet.setColumnView(column++, 25);
		sheet.setColumnView(column++, 30);
		sheet.setColumnView(column++, 90);
		sheet.setColumnView(column++, 25);
		sheet.setColumnView(column++, 25);
		sheet.setColumnView(column++, 25);
		sheet.setColumnView(column++, 30);
		workbook.write();
		workbook.close();
		log.info("内容写入成功");

	}

	public static byte[] readStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = -1;
		while ((len = inStream.read(buffer)) != -1) {
			outSteam.write(buffer, 0, len);
		}
		outSteam.close();
		inStream.close();
		return outSteam.toByteArray();
	}

	public static boolean so() {
		boolean b = true;
		int tip = 0;
		int now = 999;
		int before = 0;
		try {
			Thread.sleep(1000 * 5);
			while (cut) {// cut=true,插队中
				if (tip == 0) {
					MainController.lists.get(0).setState("暂停中···");
				}
				tip++;
				Thread.sleep(1000);
			}
			if (tip > 0) {
				MainController.lists.get(0).setState("运行中···");
				tip = 0;
			}
			try (Socket s = new Socket(host, port);
					PrintWriter pw = new PrintWriter(s.getOutputStream());
					BufferedReader bufferedReader = new BufferedReader(
							new InputStreamReader(s.getInputStream(), "utf-8"));) {
				pw.println("getnum");
				pw.flush();
				String str = bufferedReader.readLine();
				System.out.println("正常运行" + str);
				Matcher macher = Pattern.compile("num:([0-9]+)\\}").matcher(str);
				if (macher.find()) {
					now = Integer.valueOf(macher.group(1));
					MainController.lists.get(0).setSurplusCount(now);
				}
				if (now == 0) {
					b = false;
				}
			} catch (Exception e) {
				log.error("错误信息{}", e);
			}
		} catch (Exception e) {
			b = false;
			log.error("错误信息{}", e);
		}
		return b;
	}

	public static boolean cutso() {
		boolean b = true;
		try (Socket s = new Socket(host, port);
				PrintWriter pw = new PrintWriter(s.getOutputStream());
				BufferedReader bufferedReader = new BufferedReader(
						new InputStreamReader(s.getInputStream(), "utf-8"));) {
			pw.println("getnum");
			pw.flush();
			String str = bufferedReader.readLine();
			System.out.println("插队运行" + str);
			if (str.contains("0")) {
				b = false;
			}
		} catch (Exception e) {
			log.error("错误信息{}", e);
		}
		return b;
	}

	/**
	 * 开始插队，socket通信告知
	 * 
	 * @return
	 */
	public static String cutQ() {
		try (Socket s = new Socket(host, port);
				PrintWriter pw = new PrintWriter(s.getOutputStream());
				BufferedReader bufferedReader = new BufferedReader(
						new InputStreamReader(s.getInputStream(), "utf-8"));) {
			pw.println("change");
			pw.flush();
			return bufferedReader.readLine();
		} catch (Exception e) {
			log.error("错误信息{}", e);
		}
		return null;
	}

	/**
	 * 执行插队操作
	 * 
	 * @param id
	 * @return
	 */
	public static String startCut(String id) {
		String msg = cutQ();
		if (msg != null & msg.contains("ok")) {
			for (Excels ex : MainController.lists) {
				System.out.println(id);
				if (ex.getId().equals(id)) {
					cut = true;
					System.out.println("开始插队了");
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					ex.setState("插队中···");
					ex.setStartDate(sdf.format(new Date()));
					MainController.excel = ex;
					Thread t = new Thread() {
						public void run() {
							try {
								save();
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					};
					t.start();
				}
			}
		}
		return msg;
	}

	/**
	 * 运行结束，sokcet告知
	 * 
	 * @return
	 */
	public static String back() {
		try (Socket s = new Socket(host, port);
				PrintWriter pw = new PrintWriter(s.getOutputStream());
				BufferedReader bufferedReader = new BufferedReader(
						new InputStreamReader(s.getInputStream(), "utf-8"));) {
			pw.println("back");
			pw.flush();
			return bufferedReader.readLine();
		} catch (Exception e) {
			log.error("错误信息{}", e);
		}
		return null;
	}

	/**
	 * 插队进行转链接
	 * 
	 * @throws Exception
	 */
	public static void save() throws Exception {
		System.out.println("插队开始处理");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Excels excel = MainController.excel;
		excel.setStartDate(sdf.format(new Date()));
		List<Weixin> list = ReaderExcel.getExcel(excel.getUrl());
		List<String> urls = new ArrayList<String>();// 写入url
		for (Weixin l : list) {
			if (null != l.getUrl()) {
				if (l.getUrl().startsWith("https://mp.weixin.qq.com/s")
						|| l.getUrl().startsWith("http://mp.weixin.qq.com/s")) {
					urls.add(l.getUrl());
					log.info(l);
				}
			} else {
				continue;
			}
		}
		m.insert(urls);// 存储
		Thread.sleep(1000 * 60);
		while (cutso()) {
			Thread.sleep(1000 * 10);
		}
		Map<String, String> map = new HashMap<>();
		for (Map<String, Object> ma : m.find()) {
			if (ma != null && ma.get("url") != null)
				map.put(ma.get("_id").toString(), ma.get("url").toString());
		}
		for (Weixin w : list) {
			if (null != w.getUrl() && w.getUrl().startsWith("https://mp.weixin.qq.com/s")
					|| w.getUrl().startsWith("http://mp.weixin.qq.com/s")) {
				if (map.get(w.getUrl()) != null) {
					w.setGetUrl(map.get(w.getUrl()));
				}
			} else {
				w.setGetUrl(w.getUrl() == null ? "" : w.getUrl());
			}
		}
		write(list, excel.getMail());
		delete(excel.getUrl());
		MainController.lists.remove(excel);
		cut = false;
		back();
		log.info("cut处理完成");
	}

	/**
	 * 转链接主要内容
	 * 
	 * @throws Exception
	 */
	public synchronized static void save2() throws Exception {
		runStrat = true;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		while (true) {
			if (MainController.lists.size() > 0) {
				try {
					e = MainController.lists.get(0);
					if (e != null) {
						e.setStartDate(sdf.format(new Date()));
						e.setState("运行中···");
						List<Weixin> list = ReaderExcel.getExcel(e.getUrl());
						List<String> urls = new ArrayList<String>();// 写入url
						for (Weixin l : list) {
							if (null != l.getUrl()) {
								if (l.getUrl().startsWith("https://mp.weixin.qq.com/s")
										|| l.getUrl().startsWith("http://mp.weixin.qq.com/s")) {
									urls.add(l.getUrl());
									log.info(l);
								}
							} else {
								continue;
							}
						}
						m.insert(urls);// 存储
						Thread.sleep(1000 * 80);
						while (so()) {
							Thread.sleep(1000 * 10);
						}
						Map<String, String> map = new HashMap<>();
						for (Map<String, Object> ma : m.find()) {
							try {
								if (ma != null && ma.get("url") != null)
									map.put(ma.get("_id").toString(), ma.get("url").toString());
							} catch (Exception e) {
								log.info("错误信息+560{}" + e.getMessage());
							}
						}
						for (Weixin w : list) {
							try {
								if (null != w.getUrl() && w.getUrl().startsWith("https://mp.weixin.qq.com/s")
										|| w.getUrl().startsWith("http://mp.weixin.qq.com/s")) {
									if (map.get(w.getUrl()) != null) {
										w.setGetUrl(map.get(w.getUrl()));
									}
								} else {
									w.setGetUrl(w.getUrl() == null ? "" : w.getUrl());
								}
							} catch (Exception e) {
								log.info("错误信息+574{}" + e.getMessage());
							}
						}
						write(list, e.getMail());
						m.remove();
						MainController.lists.remove(MainController.lists.get(0));
						e = null;
					}
				} catch (NullPointerException e) {
					e.printStackTrace();
					MainController.lists.remove(MainController.lists.get(0));
				} catch (Exception e1) {
					e1.printStackTrace();
					MainController.lists.remove(MainController.lists.get(0));
				}
			} else {
				Thread.sleep(1000 * 60);
			}

		}
	}

	/**
	 * 删除文件
	 * 
	 * @param url
	 *            文件的路径
	 */
	public static void delete(String url) {
		File file = new File(url);
		if (file.isFile()) {
			file.delete();
		}
		log.info("删除完成");
	}

	public static void insert(ExcelFile ef) {
		m.insertFile(ef);
	}

	public static List<ExcelFile> findEf() {
		List<ExcelFile> list = m.findFile();
		return list;
	}

	public static String findById(String id) {
		return m.findByid(id);
	}

}
