/* 
 * Company Name : 中贸促信息技术有限责任公司
 * Project Name:memberManageSys
 * File Name:EmailService.java
 * Package Name:ccpit.business.linkManage
 * Date:2015年11月30日
 * Copyright (c) 2015, jinlong@ccpit.org All Rights Reserved.
 * 
 */
package ccpit.base.emailSendManage;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import ccpit.base.controller.BaseController;
import ccpit.base.controller.Convert;
import ccpit.base.controller.Page;
import ccpit.base.controller.PageBo;
import ccpit.base.controller.PageRequest;
import ccpit.base.metadataManage.Metadata;
import ccpit.base.metadataManage.MetadataDao;
import ccpit.base.user.User;
import ccpit.base.user.UserDao;
import ccpit.base.user.UserEmail;
import ccpit.base.user.UserEmailDao;
import ccpit.base.utils.mailUtil.Mail;
import ccpit.base.utils.mailUtil.MailUtil;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 * ClassName:EmailService <br/>
 * Function: TODO <br/>
 * Reason: TODO <br/>
 * Date: 2015年11月30日 <br/>
 * 
 * @author jinlong
 * @version
 * @since JDK 1.6
 * @see
 */
@Repository
@Transactional
public class EmailService {
	private static final Logger log = LoggerFactory.getLogger(EmailService.class);
	private final static SimpleDateFormat sdf = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");
	@Autowired
	private EmailDao emailDao;
	@Autowired
	private UserEmailDao userEmailDao;
	@Autowired
	private MetadataDao metadataDao;
	@Autowired
	private UserDao userDao;
	
	public Page<EmailInfo> queryLinkInfos(PageRequest pageRequest, String hql) {
		return emailDao.findPage(pageRequest, hql, null);
	}

	public Map<String, Object> convertToMap(EmailInfo emailInfo) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (emailInfo == null) {
			return map;
		}
		map.put("id", emailInfo.getId());
		map.put("createTime", sdf.format(emailInfo.getCreateTime()));
		// map.put("creator", emailInfo.getCreator());
		map.put("title", emailInfo.getTitle());
		map.put("copyTo", emailInfo.getCopyTo());
		// map.put("addresser", emailInfo.getAddresser());
		map.put("recipients", emailInfo.getRecipients());
		map.put("recipientName", emailInfo.getRecipientName());
		// map.put("content", emailInfo.getContent());
	
		return map;
	}

	public PageBo<EmailInfo> convert(Page<EmailInfo> page) {
		return new PageBo<EmailInfo>(page, new Convert<EmailInfo>() {
			@Override
			public Map<String, Object> convert(EmailInfo obj) {
				return convertToMap(obj);
			}
		});
	}
	//软删除邮件，先把邮件查出来，然后再更新
	public void deleteEmailInfosByIds(HttpServletRequest request,String ids) {

		StringBuffer hql = new StringBuffer(
				"from EmailInfo m where id in(");
		String[] filters = ids.split(",");
		try {
			int i = 0;
			for (; i < filters.length - 1; i++) {
				hql.append(filters[i]);
				hql.append(" , ");
			}
			hql.append(filters[i]);
			hql.append(")");
			User modifyBy = ((User) request.getSession().getAttribute(BaseController.USER_IN_SESSION));
			List<EmailInfo> listE = emailDao.query(hql.toString(), null);
			for(EmailInfo emailInfo:listE){
				emailInfo.setEmailWhether(false);
				emailInfo.setModifyBy(modifyBy);
				emailInfo.setModifyTime(new Date());
				emailDao.update(emailInfo);
			}
		} catch (Exception ex) {
			throw new RuntimeException("orm-entity-006：删除记录失败，hql为："
					+ hql.toString(), ex);
		}

	}

	public Object emailReecipientsCombox(HttpServletRequest request) {// 发送多封邮件
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		
		return list;
//		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
//		List<LinkStaffInfo> linkStaffInfos = linkStaffInfoDao.queryAll();
//		if(linkStaffInfos!=null&&linkStaffInfos.size()>0){
//			StringBuffer hql = new StringBuffer("from Metadata where id = ");
//			int i = 0;
//			for (; i < linkStaffInfos.size() - 1; i++) {
//				hql.append(linkStaffInfos.get(i).getLinkType() + " or  id = ");
//			}
//			hql.append(linkStaffInfos.get(i).getLinkType());
//			List<Metadata> listM = metadataDao.query(hql.toString(), null);
//			Map<String, String> map = null;
//			for (Metadata m : listM) {
//				map = new HashMap<String, String>();
//				map.put("id", String.valueOf(m.getId()));
//				map.put("text", m.getDataName());
//				list.add(map);
//			}
//		}
//		return list;
	}

	public Object addEmailInfo(HttpServletRequest request) {
		Map<String, Object> data = null;
		try {
			data = new HashMap<String, Object>();String info = "";
			// 获取表单信息
			String emailStatus = request.getParameter("emailStatus");
			String recipients = request.getParameter("addRecipientsName");
			Pattern pattern = Pattern.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
			Matcher matcher = pattern.matcher(recipients.trim());
			System.out.println(matcher.matches());
			String recipientName = request.getParameter("addRecipientNameName");
			String title = request.getParameter("addTitleName");
			String affixRealPath = request.getParameter("addEmailRealPathName");
			String content = request.getParameter("emailContent");
			String copyTo = request.getParameter("copyTo");
			
			EmailInfo emailInfo = new EmailInfo();
			emailInfo.setStatus(emailStatus);
			emailInfo.setRecipients(recipients);
			emailInfo.setRecipientName(recipientName);
			emailInfo.setTitle(title);
			emailInfo.setAffix(affixRealPath);
			User user = (User) request.getSession().getAttribute(
					BaseController.USER_IN_SESSION);
//			User user = (User)userDao.queryById((long)1);
			UserEmail userEmail = user.getUserEmail();
			if(userEmail==null){
				throw new RuntimeException("userEmail为空");
			}
			emailInfo.setAddresser(userEmail.getEmailCount());
			emailInfo.setContent(content);
			emailInfo.setEmailWhether(true);
			emailInfo.setCreateTime(new Date());
			emailInfo.setCreator(user);
			emailInfo.setCopyTo(copyTo);
			emailInfo.setId(0);
			emailInfo.setEmailWhether(true);
			emailDao.save(emailInfo);
			data.put("flag", true);
			data.put("info", "添加成功");
			data.put("emailInfo", emailInfo);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			if (data != null) {
				data.put("flag", false);
				data.put("info", "添加失败");
			}
			log.info(e.getMessage());
			e.printStackTrace();
		}
		log.info("添加邮件");
		return data;
	}

	public Object modifyEmailInfo(HttpServletRequest request) {
		Map<String, Object> data = null;
		EmailInfo emailInfo = null;
		try {
			String emailStatus = request.getParameter("emailStatus");
			String id = request.getParameter("emailInfoId");
			emailInfo = emailDao.queryById(Long.valueOf(id));
			String recipients = request.getParameter("addRecipientsName");
			Pattern pattern = Pattern.compile("[0-9]*");
			Matcher isNum = pattern.matcher(recipients);
			if (isNum.matches() && !StringUtils.isEmpty(recipients)) {
				Metadata meta = metadataDao.queryById(Long.valueOf(recipients));
				recipients = meta.getDataName();
			}
			String recipientName = request.getParameter("addRecipientNameName");
			String title = request.getParameter("addTitleName");
			String affixRealPath = request.getParameter("addEmailRealPathName");
			String content = request.getParameter("emailContent");
			String copyTo = request.getParameter("copyTo");
			User user = (User) request.getSession().getAttribute(
					BaseController.USER_IN_SESSION);
			data = null;
			if (emailInfo != null) {
				data = new HashMap<String, Object>();
				emailInfo.setStatus(emailStatus);
				emailInfo.setRecipients(recipients);
				emailInfo.setRecipientName(recipientName);
				emailInfo.setTitle(title);
				emailInfo.setAffix(affixRealPath);
				emailInfo.setContent(content);
				emailInfo.setCopyTo(copyTo);
				emailInfo.setModifyBy(user);
				emailInfo.setModifyTime(new Date());
				data.put("flag", true);
				data.put("info", "修改成功");
				data.put("content", emailInfo.getContent());
			}
			emailDao.update(emailInfo);
		} catch (NumberFormatException e) {
			if (data != null) {
				data.put("flag", false);
				data.put("info", "修改失败");
				data.put("content", emailInfo.getContent());
			}
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return data;
	}

	public Object getEmailInfoById(HttpServletRequest request) {
		String id = request.getParameter("emailInfoId");
		EmailInfo emailInfo = emailDao.queryById(Long.valueOf(id));
		Map<String, Object> data = new HashMap<String, Object>();
		if (emailInfo == null) {
			return data;
		}
		data.put("id", String.valueOf(emailInfo.getId()));
		data.put("createTime", sdf.format(emailInfo.getCreateTime()));
//		data.put("creator", emailInfo.getCreator());
		data.put("title", emailInfo.getTitle());
		data.put("copyTo", emailInfo.getCopyTo());
		data.put("addresser", emailInfo.getAddresser());
		data.put("recipients", emailInfo.getRecipients());
		data.put("content", emailInfo.getContent());
		data.put("recipientName", emailInfo.getRecipientName());
		Metadata meta = metadataDao.findUnique(
				"from Metadata where dataName = '"
						+ emailInfo.getRecipients() + "'", null);
		if(meta!=null){
			data.put("linkType", meta.getId());
		}else{
			data.put("linkType", null);
		}
		
		String affix = emailInfo.getAffix();
		data.put("realPath", affix);
		//获得文件夹下所有文件名
		File file = new File(affix);
		StringBuffer fStr =null;
		if(file.exists()){
			fStr= new StringBuffer();
			File fa[] = file.listFiles();
			for(File f:fa){
				fStr.append(f.getName()+";");
			}
		}
		if(fStr!=null){
			String[] fileNames = fStr.toString().split(";");
			data.put("fileNameArr", fileNames);
		}else{
			data.put("fileNameArr", "");
		}
		//把emailStore保存在data中
		String emailStore = null;
		if(affix!=null){
			String[] filePathParts = affix.split("/");
			emailStore = filePathParts[filePathParts.length-1];
		}
		data.put("emailStore", emailStore);
		return data;
	}

	public Object sendEmailInfoById(HttpServletRequest request) {
		//根据id获得emailinfo
		String id = request.getParameter("id");
		EmailInfo emailInfo = emailDao.queryById(Long.parseLong(id));
		//邮件发送
		Mail mail = null;String linkManType = null;List<String> listEmailAddress = new ArrayList<String>();
		int count = 0;// 记录失败次数
		Map<String, Object> data = new HashMap<String, Object>();
		UserEmail userEmail = ((User) request.getSession().getAttribute(BaseController.USER_IN_SESSION)).getUserEmail();
		if(emailInfo==null){
			data.put("flag", false);
			data.put("info", "邮件不存在！！！");
			return data;
		}else{
			linkManType = emailInfo.getRecipients();
			if(!StringUtils.isEmpty(linkManType)){
				//根据联系人类型，查看下该接受邮件的人到底是不是联系人类型还是邮箱地址
				Metadata meta = metadataDao.findUnique("from Metadata m where m.dataNameId='"+linkManType+"'", null);
				if(meta==null){
					//单发
					sendOneEmail(request,emailInfo.getRecipients(),emailInfo, userEmail);
				}else{
					//群发
					linkManType = meta.getId()+"";
					
					if(listEmailAddress.size()>0){
						for(String emailAddress:listEmailAddress){
							//发送邮件，单封发送
							if(!StringUtils.isEmpty(emailAddress)){
								sendOneEmail(request,emailAddress,emailInfo, userEmail);								
							}
						}
					}
				}
			}
		}
		Session session = userDao.getHibernateTemplate().getSessionFactory().getCurrentSession();session.close();
//		taskExecutor.execute(new Runnable() {
//			@Override
//			public void run() {
//				System.out.println(222222222);
//			}
//		});

		return data;
	}
	
	public void sendOneEmail(HttpServletRequest request,String emailAddress,EmailInfo emailInfo,UserEmail userEmail){
		Mail mail = null;
		if (emailInfo != null && userEmail != null) {
			mail = new Mail();
			mail.setHost(userEmail.getServerHost());
			mail.setProtocol(userEmail.getServerProtocol());
			mail.setSender(userEmail.getEmailCount());
			mail.setName(null);
			mail.setEmailCount(userEmail.getEmailCount());
			mail.setEmailPassword(userEmail.getEmailPassword());
			mail.setReceiver(emailAddress);
//			mail.setCopyTo(emailInfo.getCopyTo());
			mail.setMailTitle(emailInfo.getTitle());
			mail.setMailMessage(emailInfo.getContent());
			String files = getAffixFromDir(emailInfo.getAffix());
			mail.setAffix(files);
				//监测发送过程，如果发送失败，则把发送失败的名单保留下来，并回显到页面
			MailUtil.sendMail(mail);
		}
    }
	
	public String getAffixFromDir(String dir) {
		File file = new File(dir);
		StringBuffer fStr = null;
		if (file.exists()) {
			fStr = new StringBuffer();
			File fa[] = file.listFiles();
			for (int i = 0; i < fa.length; i++) {
				fStr.append(fa[i] + ";");
			}
			return fStr.toString();
		}
		return null;
	}
	//测试数据
				// MailUtil.sendMail(mail);
				// mail = new Mail();
				// mail.setHost("smtp.exmail.qq.com");
				// mail.setProtocol("smtp");
				// mail.setSender("jinlong@ccpit.org");
				// mail.setName("123");
				// mail.setEmailCount("jinlong@ccpit.org");
				// mail.setEmailPassword("Jl13465213");
				// mail.setReceiver("jinlong@ccpit.org");//
				// listEmail.get(index).getAddresser());
				// mail.setCopyTo("xinguohui@ccpit.org");
				// mail.setMailTitle("123");
				// mail.setMailMessage("123123");
				// mail.setAffix("F://body.xls");
				// MailUtil.sendMail(mail);

	public Object deleteAffixByAffixName(HttpServletRequest request) {
		String fileName = request.getParameter("fileName");
		String realPath = request.getParameter("realPath");
		File file = new File(realPath);
		StringBuffer fStr =null;Map<String,Object> data = new HashMap<String,Object>();
		if(file.exists()){
			File fa[] = file.listFiles();
			for(int i =0;i<fa.length;i++){
				String fileN = fa[i].getName();
				if(fileName.trim().equals(fileN)){
					
					if(fa[i].delete()){
						data.put("flag", true);
						data.put("info", "文件删除成功！！！");
					}	
				}
			}
		}else{
			data.put("flag", false);
			data.put("info", "该文件保存路径已经过期！！！");
		}
		return data;
	}
}
