package com.psj.main;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;

import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import sun.audio.AudioPlayer;
import sun.audio.AudioStream;

/**
 * 使用POP3协议接收邮件
 */
public class POP3ReceiveMailTest {

	Timer timer;
	
	ArrayList<String> idHaveProblem = new ArrayList<String>();
	ArrayList<String> idHaveProblemInfo = new ArrayList<String>();
	ArrayList<String> cooperateListInfo = new ArrayList<String>();

	// public ArrayList<String> isPlayed = new ArrayList(); //
	// 记录已经播放的声音的有问题的id列表

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static void main(String[] args) throws Exception {
		Data.isPlayed = new ArrayList<String>();
		new POP3ReceiveMailTest(0);

	}

	@SuppressWarnings("unused")
	public POP3ReceiveMailTest(int seconds) {
		Date time = getTime();
		// System.out.println("指定时间time=" + time);
		System.out.println("");
		System.out.println("稍后继续。。。。。。");
		timer = new Timer();
		timer.schedule(new TimerTaskTest02(), seconds * 1000 * 60);

		// timer.cancel();
	}

	public Date getTime() {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, 16);
		calendar.set(Calendar.MINUTE, 47);
		calendar.set(Calendar.SECOND, 00);
		Date time = calendar.getTime();
		return time;
	}

	class TimerTaskTest02 extends TimerTask {
		@SuppressWarnings({ "unchecked", "rawtypes" })
		public ArrayList<String> list = new ArrayList();

		@Override
		public void run() {
			System.out.println("指定时间执行线程任务...");
			getLocalFile();
			try {
				receive();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		// 获取本地文件,遍历每行的字符串
		public void getLocalFile() {
			File fin, fout;
			BufferedReader bf = null;
			PrintWriter pw = null;

			try {
				fin = new File("test.txt");
				fout = new File("456.txt");
				bf = new BufferedReader(new FileReader(fin));
				pw = new PrintWriter(fout);
				String line = bf.readLine();
				while (line != null) {
					// System.out.println(line);// 遍历每行的字符串
					list.add(line);
					pw.println(line);
					line = bf.readLine();
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (bf != null) {
						bf.close();
						bf = null;
					}
					if (pw != null) {
						pw.close();
						pw = null;
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		}

		public void writeToLocalFile(ArrayList<String> list, String fileName)
				throws IOException {
			// 把有异常的节目ID存到本地文件;
			File fout;
			PrintWriter pw = null;

			try {
				fout = new File(fileName);
				pw = new PrintWriter(fout);
				for (String tmp : list) {
					pw.println(tmp);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (pw != null) {
					pw.close();
					pw = null;
				}
			}
		}

		/**
		 * 接收邮件
		 */
		public void receive() throws Exception {
			// System.out.println("aaaaaaaaaaaaaaaa");
			// 准备连接服务器的会话信息
			Properties props = new Properties();
			props.setProperty("mail.store.protocol", "pop3"); // 协议
			props.setProperty("mail.pop3.port", "110"); // 端口
			props.setProperty("mail.pop3.host", "pop.exmail.qq.com"); // pop3服务器

			// 创建Session实例对象
			Session session = Session.getInstance(props);
			Store store = session.getStore("pop3");
			store.connect("email address", "email password");

			// 获得收件箱
			Folder folder = store.getFolder("INBOX");
			// Folder.READ_ONLY:只读权限
			// Folder.READ_WRITE:可读可写(可以修改邮件的状态)
			System.out.println("打开收件箱");
			folder.open(Folder.READ_WRITE); // 打开收件箱

			// 由于POP3协议无法获知邮件的状态,所以getUnreadMessageCount得到的是收件箱的邮件总数
			System.out.println("未读邮件数: " + folder.getUnreadMessageCount());

			// 由于POP3协议无法获知邮件的状态,所以下面得到的结果始终都是为0
			System.out.println("删除邮件数: " + folder.getDeletedMessageCount());
			System.out.println("新邮件: " + folder.getNewMessageCount());

			// 获得收件箱中的邮件总数
			System.out.println("邮件总数: " + folder.getMessageCount());

			// 得到收件箱中的所有邮件,并解析
			Message[] messages = folder.getMessages();
			parseMessage(messages);

			// 释放资源
			folder.close(true);
			store.close();
			timer.cancel();
			new POP3ReceiveMailTest(5);
		}

		public void nowDate() {
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
			System.out.println("当前时间是:" + df.format(new Date()));// new
																	// Date()为获取当前系统时间
		}

		/**
		 * 解析邮件
		 * 
		 * @param messages
		 *            要解析的邮件列表
		 */
		public void parseMessage(Message... messages)
				throws MessagingException, IOException {
			
			idHaveProblem.removeAll(idHaveProblem);
			idHaveProblemInfo.removeAll(idHaveProblemInfo);
			cooperateListInfo.removeAll(cooperateListInfo);
			Data.isPlayed.removeAll(Data.isPlayed);
			
			if (messages == null || messages.length < 1)
				throw new MessagingException("未找到要解析的邮件!");

			

			// 解析所有邮件
			for (int i = 0, count = messages.length; i < count; i++) {
				MimeMessage msg = (MimeMessage) messages[i];
				if (getCurrentTime().equalsIgnoreCase( // 只输出当天的邮件
						getSentDate(msg, null))) {
					System.out.println("");
//					nowDate();
					System.out.println(getNowDateInfo());
					System.out.println("--" + msg.getMessageNumber() + "--");
					
					// System.out.println("------------------解析第" +
					// msg.getMessageNumber() + "封邮件-------------------- ");
					// System.out.println("主题: " + getSubject(msg));
					// System.out.println("发件人: " + getFrom(msg));
					// System.out.println("收件人:" + getReceiveAddress(msg,
					// null));
					// System.out.println("发送时间:" + getSentDate(msg, null));
					// System.out.println("是否已读:" + isSeen(msg));
					// System.out.println("邮件优先级:" + getPriority(msg));
					// System.out.println("是否需要回执:" + isReplySign(msg));
					// System.out.println("邮件大小:" + msg.getSize() * 1024 +
					// "kb");
					boolean isContainerAttachment = isContainAttachment(msg);
					// System.out.println("是否包含附件:" + isContainerAttachment);
					if (isContainerAttachment) {
						// saveAttachment(msg, "c:\\mailtmp\\"+msg.getSubject()
						// +
						// "_");
						// //保存附件
					}
					StringBuffer content = new StringBuffer(30);
					getMailTextContent(msg, content);
					String co = ((content.length() > 100 ? content.substring(0,
							100) + "..." : content))
							+ "";
					// co是正文的内容,需要获取正文内容的 冒号后面的内容
					if (co.indexOf(":") != -1) {
						String[] strArray = co.split(":");
						co = strArray[1];
						co = co.trim();
					}
					
					idHaveProblem.add(co);
					idHaveProblemInfo.add(co + "------"
							+ getSentDate(msg, null, "1"));// 把有问题的加入到一个列表中,待会保存到本地文件。。
					// System.out.println("第" + msg.getMessageNumber() + "封邮件");
					// 本地的list与邮件里面的正文比较
					// System.out.println("第" + msg.getMessageNumber() + "封邮件");
					// System.out.println("当前时间"+getCurrentTime());
					// System.out.println(getSentDate(msg, null));
					for (int qi = 0; qi < list.size(); qi++) {
						String t = list.get(qi);
						if (t.equalsIgnoreCase(co)) {
							// if (getCurrentTime().equalsIgnoreCase(
							// getSentDate(msg, null))) {
							/*System.out.println("第" + msg.getMessageNumber()
									+ "封邮件");
							System.out.println("发送时间:"
									+ getSentDate(msg, null, "1"));

							System.out.println("节目ID:" + t);*/
							// for (int ii =0;ii<Data.isPlayed.size();ii++){
							// System.out.println(Data.isPlayed.get(ii));
							// }
							// }
							Data.isPlayed.add(t); // 把播放过的节目加入已播放列表
							cooperateListInfo.add(t + "------"
									+ getSentDate(msg, null, "1"));
							if (Data.isPlayed.size() != 0) {
								if (Data.isPlayed.indexOf(t) < 0) { // 这个是判断当前的id号是否在isplayed列表里
									try {
										System.out.println("列表不为零,并且id只出现一次。。。"
												+ Data.isPlayed.size());
										FileInputStream fileau = new FileInputStream(
												"music.au");
										AudioStream as = new AudioStream(fileau);
										AudioPlayer.player.start(as);
//										Data.isPlayed.add(t); // 把播放过的节目加入已播放列表
//										cooperateListInfo.add(t + "------"
//												+ getSentDate(msg, null, "1"));
									} catch (FileNotFoundException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								}
							} else {
								try {
									System.out.println("播放啦。。。");
									FileInputStream fileau = new FileInputStream(
											"music.au");
									AudioStream as = new AudioStream(fileau);
									AudioPlayer.player.start(as);
//									Data.isPlayed.add(t); // 把播放过的节目加入已播放列表
//									cooperateListInfo.add(t + "------"
//											+ getSentDate(msg, null, "1"));
								} catch (FileNotFoundException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}

						}
					}
					// System.out.println("第" + msg.getMessageNumber() + "封邮件" +
					// ":"
					// +
					// co);
					// System.out.println("邮件正文:" + (content.length() > 100 ?
					// content.substring(0,100) + "..." : content));
					// System.out.println("------------------第" +
					// msg.getMessageNumber()
					// + "封邮件解析结束-------------------- ");
					// System.out.println();
				} else {
					System.out.print(".");
				}
			}

			writeToLocalFile(idHaveProblem, getNowDate()
					+ "_id_haveproblem.txt");
			writeToLocalFile(Data.isPlayed, getNowDate()
					+ "_id_haveproblem_cooperate.txt");
			writeToLocalFile(idHaveProblemInfo, getNowDate()
					+ "_id_haveproblem_info.txt");
			writeToLocalFile(cooperateListInfo, getNowDate()
					+ "_id_haveproblem_cooperate_info.txt");
		}

		public String getNowDate() {
			SimpleDateFormat df = new SimpleDateFormat("yyyy_MM_dd");// 设置日期格式
			// System.out.println("当前时间是:"+df.format(new Date()));// new
			// Date()为获取当前系统时间
			return df.format(new Date());
		}
		
		public String getNowDateInfo() {
			SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日 E HH:mm ");// 设置日期格式
			// System.out.println("当前时间是:"+df.format(new Date()));// new
			// Date()为获取当前系统时间
			return df.format(new Date());
		}

		public String getCurrentTime() {
			SimpleDateFormat df = new SimpleDateFormat("MM-dd");// 设置日期格式
			// System.out.println(df.format(new Date()));
			return df.format(new Date());
		}

		/**
		 * 获得邮件发送时间
		 * 
		 * @param msg
		 *            邮件内容
		 * @return yyyy年mm月dd日 星期X HH:mm
		 * @throws MessagingException
		 */
		public String getSentDate(MimeMessage msg, String pattern)
				throws MessagingException {
			Date receivedDate = msg.getSentDate();
			if (receivedDate == null)
				return "";

			if (pattern == null || "".equals(pattern))
				// pattern = "yyyy年MM月dd日 E HH:mm ";
				pattern = "MM-dd";

			return new SimpleDateFormat(pattern).format(receivedDate);
		}

		public String getSentDate(MimeMessage msg, String pattern, String i)
				throws MessagingException {
			Date receivedDate = msg.getSentDate();
			if (receivedDate == null)
				return "";

			if (pattern == null || "".equals(pattern))
				pattern = "yyyy年MM月dd日 E HH:mm ";
			// pattern = "MM-dd";

			return new SimpleDateFormat(pattern).format(receivedDate);
		}

		/**
		 * 判断邮件中是否包含附件
		 * 
		 * @param msg
		 *            邮件内容
		 * @return 邮件中存在附件返回true,不存在返回false
		 * @throws MessagingException
		 * @throws IOException
		 */
		public boolean isContainAttachment(Part part)
				throws MessagingException, IOException {
			boolean flag = false;
			if (part.isMimeType("multipart/*")) {
				MimeMultipart multipart = (MimeMultipart) part.getContent();
				int partCount = multipart.getCount();
				for (int i = 0; i < partCount; i++) {
					BodyPart bodyPart = multipart.getBodyPart(i);
					String disp = bodyPart.getDisposition();
					if (disp != null
							&& (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp
									.equalsIgnoreCase(Part.INLINE))) {
						flag = true;
					} else if (bodyPart.isMimeType("multipart/*")) {
						flag = isContainAttachment(bodyPart);
					} else {
						String contentType = bodyPart.getContentType();
						if (contentType.indexOf("application") != -1) {
							flag = true;
						}

						if (contentType.indexOf("name") != -1) {
							flag = true;
						}
					}

					if (flag)
						break;
				}
			} else if (part.isMimeType("message/rfc822")) {
				flag = isContainAttachment((Part) part.getContent());
			}
			return flag;
		}

		/**
		 * 获得邮件文本内容
		 * 
		 * @param part
		 *            邮件体
		 * @param content
		 *            存储邮件文本内容的字符串
		 * @throws MessagingException
		 * @throws IOException
		 */
		public void getMailTextContent(Part part, StringBuffer content)
				throws MessagingException, IOException {
			// 如果是文本类型的附件,通过getContent方法可以取到文本内容,但这不是我们需要的结果,所以在这里要做判断
			boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;
			if (part.isMimeType("text/*") && !isContainTextAttach) {
				if (part.getContent() == null){
					System.out.print("正文内容为空");
					return;
				} else {
				System.out.println(part.getContent().toString().trim()+"");
					content.append(part.getContent().toString());
//					System.out.println(content.toString().trim()+"");
				}
			} else if (part.isMimeType("message/rfc822")) {
				getMailTextContent((Part) part.getContent(), content);
			} else if (part.isMimeType("multipart/*")) {
				Multipart multipart = (Multipart) part.getContent();
				int partCount = multipart.getCount();
				for (int i = 0; i < partCount; i++) {
					BodyPart bodyPart = multipart.getBodyPart(i);
					getMailTextContent(bodyPart, content);
				}
			}
		}
	}

}