/**
 * Company Name : 中贸促信息技术有限责任公司
 * Project Name:memberManageSys
 * File Name:EmailController.java
 * Package Name:ccpit.business.emailManage
 * Date:2015年11月25日上午10:23:18
 * Copyright (c) 2015, dingwei@ccpit.org All Rights Reserved.
 *
 */

package org.ccpit.base.emailSendManage;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.ccpit.base.controller.BaseController;
import org.ccpit.base.controller.Page;
import org.ccpit.base.controller.PageRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * ClassName:EmailController <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason: TODO ADD REASON. <br/>
 * Date: 2015年11月25日 上午10:23:18 <br/>
 * 
 * @author jinlong
 * @version
 * @since JDK 1.6
 * @see
 */
@Controller
@RequestMapping("/business/emailManage")
public class EmailController extends BaseController {
	private static final Logger log = LoggerFactory.getLogger(EmailController.class);
	@Autowired
	private EmailService emailService;
	private static int dirNum = 0;
	private SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM");
	private SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
	@RequestMapping("/goinEmailListPage_yf")
	public Object goinEmailListPage_yf() {
		ModelAndView mv = new ModelAndView("business/emailListPage");
		mv.addObject("emailStatus", "yf");
		return mv;
	}
	@RequestMapping("/goinEmailListPage_cg")
	public Object goinEmailListPage_cg() {
		ModelAndView mv = new ModelAndView("business/emailListPage");
		mv.addObject("emailStatus", "cg");
		return mv;
	}
	@RequestMapping("/getAllEmailInfos")
	@ResponseBody
	public Object getAllEmailInfos(HttpServletRequest request) {
		PageRequest pageRequest = getPage(request);
		String createTime = request.getParameter("createTime");
		String emailStatus = request.getParameter("emailStatus");
		if(!emailStatus.equals("cg")&&!emailStatus.equals("yf")){
			log.info("选择的既不是草稿也不是已发送！！");
			return null;
		}
		String title = request.getParameter("title");
		StringBuffer hql = new StringBuffer("from EmailInfo where 1=1 and emailWhether = true");
		hql.append(" and status = '" + emailStatus +"'");
		if (null == createTime && null == title) {
			hql.append(" order by createTime desc");
		} else {
			if (null != createTime && !"".equals(createTime)) {
				hql.append(" and createTime like '%" + createTime + "%'");
			}
			if (null != title && !"".equals(title)) {
				hql.append(" and title like '%" + title + "%'");
			}
			hql.append(" order by createTime desc");
		}
		Page<EmailInfo> pageEmail = emailService.queryLinkInfos(pageRequest,
				hql.toString());
		return emailService.convert(pageEmail);
	}
	@RequestMapping("/upload/uploadFile")
	@ResponseBody
	public Object uploadFile(HttpServletRequest request) {
		String emailStore = request.getParameter("emailStore");
		String fileName = "";
		String fileName1 = "";
		String realPath = "";
		String monthStr = sdf1.format(new Date());
		String dayStr = sdf2.format(new Date());
		String fileDir = "";
		if (emailStore == null || "".equals(emailStore)) {
			emailStore = String.valueOf(new Date().getTime());
		}
		fileDir =  request.getSession().getServletContext().getRealPath("/")
				+ "emailUploadFile" + "/" + monthStr + "/";
		fileDir = fileDir.replace("\\",  "/");
		// 需要返回的fileName
		realPath = request.getSession().getServletContext().getRealPath("/")
				+ "emailUploadFile" + "/" + monthStr + "/" + emailStore + "/";
		realPath = realPath.replace('\\', '/');
		Map<String, Object> data = new HashMap<String, Object>();
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// Configure a repository (to ensure a secure temp location is used)
		ServletContext servletContext = request.getSession()
				.getServletContext();
		File repository = (File) servletContext
				.getAttribute("javax.servlet.context.tempdir");
		factory.setRepository(repository);
		ServletFileUpload upload = new ServletFileUpload(factory);
		// 设置单个文件的大小20m
		// upload.setFileSizeMax(1024 * 1024 *
		// 20);//设置完后如果上传的文件大于20兆则会出现报异常，但是捕捉不到还
		// 设置总共文件的大小
		upload.setProgressListener(new UploadListener(request));
		try {
			List<FileItem> items = upload.parseRequest(request);
			for (FileItem item : items) {
				String type = item.getContentType();
				if (type == null) {
					continue;
				}
				// 文件名带后缀
				fileName = item.getName();
				File dir = null;// 创建文件夹引用
				// 文件大小多少m
				long fileSize = (item.getSize() / (1024 * 1024));
				if (fileSize > 20) {
					data.put("realPath", realPath);//保存附件上传所在文件夹的绝对地址
					data.put("emailStore", emailStore);
					data.put("fileName", fileName);
					data.put("updateResult", false);
					data.put("msg", "文件上传失败，该文件大于20M");
					return data;
				}
				Double dirSize = null;
				File tempFile =new File(realPath);
				if(!tempFile.exists()){
					tempFile.mkdirs();
				}
				if(emailStore!=null){
					dirSize = getUploadFileSize(new File(realPath));
				}
				if (dirSize!=null&&dirSize > 20) {
					data.put("realPath", realPath);//保存附件上传所在文件夹的绝对地址
					data.put("emailStore", emailStore);
					data.put("fileName",fileName);
					data.put("updateResult", false);
					data.put("msg", "文件上传失败，该文件大于20M");
					return data;
				}
				fileName1 = fileName;
				dir = new File(realPath);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				double dirLong = getUploadFileSize(new File(fileDir));
				// 存放文件夹大小超过200M 将重新创建新的存放文件夹
				if (dirLong >= 200) {
					dir = new File(fileDir + "/" + (dirNum++) + "/"+emailStore);
					dir.mkdirs();
				}
				File f = null;
				f = setUpdateFileName(dir, fileName1);// 如果该文件已经存在，在把其变成副本，并上传到服务器。
				f.createNewFile();
				// 保存
				item.write(f);
				data.put("realPath", realPath);//保存附件上传所在文件夹的绝对地址
				data.put("emailStore", emailStore);//用来区别不同的邮件
				data.put("fileName",f.getName() );
				data.put("updateResult", true);
				data.put("msg", "上传成功");
				return data;

			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@RequestMapping("/deleteAffixByAffixName")
	@ResponseBody
	public Object deleteAffixByAffixName(HttpServletRequest request) {
		return emailService.deleteAffixByAffixName(request);
	}
	private File setUpdateFileName(File dir, String fileName) {
		String fileName1 = fileName;
		String[] fileNameSplit = new String[2];
		for (int i = fileName.length() - 1; i >= 0; i--) {
			if (fileName.charAt(i) == '.') {
				fileNameSplit[0] = fileName.substring(0, i);
				fileNameSplit[1] = fileName.substring(i);
			}
		}
		File f = new File(dir, fileName);
		for (int i = 1;; i++) {
			if (f.exists()) {
				fileName1 = fileNameSplit[0] + "_copy_" + i
						+ fileNameSplit[1];
				f = new File(dir, fileName1);
			} else {
				break;
			}
		}
		return f;
	}

	// 读取上传文件目录大小
	private static double getUploadFileSize(File dir) {
		// 判断文件是否存在
		if (dir.exists()) {
			// 如果是目录则递归计算其内容的总大小
			if (dir.isDirectory()) {
				File[] files = dir.listFiles();
				double size = 0;
				for (File f : files) {
					size += getUploadFileSize(f);
				}
				return size;
			} else {
				// 如果是文件则直接返回其大小,以“兆”为单位
				double size = (double) dir.length() / 1024 / 1024;
				return size;
			}
		} else {
			log.info("文件或者文件夹不存在，请检查路径是否正确！");
			return 0.0;
		}
	}

	private class UploadListener implements ProgressListener {
		private HttpServletRequest request;
		private DecimalFormat df = new DecimalFormat("#00.0");

		UploadListener(HttpServletRequest request) {
			this.request = request;
		}

		@Override
		public void update(long bytesRead, long bytesTotal, int items) {
			double percent = (double) bytesRead * 100 / (double) bytesTotal;
			request.getSession().setAttribute("UPLOAD_PERCENTAGE",
					df.format(percent));
		}

	}

	@RequestMapping("/getEmailInfoById")
	@ResponseBody 
	public Object getEmailInfoById(HttpServletRequest request) {
		return emailService.getEmailInfoById(request);
	}

	@RequestMapping("/modifyEmailInfo")
	@ResponseBody
	public Object modifyEmailInfo(HttpServletRequest request) {
		return emailService.modifyEmailInfo(request);
	}

	@RequestMapping("/addEmailInfo")
	@ResponseBody
	public Object addEmailInfo(HttpServletRequest request) {
		
		return emailService.addEmailInfo(request);
	}

	@RequestMapping("/deleteEmailInfosByIds")
	@ResponseBody
	public Object deleteEmailInfosByIds(HttpServletRequest request) {
		Map<String, Boolean> result = null;
		try {
			String ids = request.getParameter("ids");
			JSONArray jsonArray = JSONArray.fromObject(ids);
			Object[] oids = jsonArray.toArray();
			StringBuffer idss = new StringBuffer();
			int i = 0;
			for (; i < oids.length - 1; i++) {// 把id号拼成需要的字符串
				idss.append(oids[i]);
				idss.append(",");
			}
			idss.append(oids[i]);
			emailService.deleteEmailInfosByIds( request,idss.toString());
			result = new HashMap<String, Boolean>();
			result.put("flag", true);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("flag", false);
		}
		return result;
	}
	@RequestMapping("/sendEmailInfoById")
	@ResponseBody     
	public Object sendEmailInfoById(HttpServletRequest request) {//发送单封邮件
		return emailService.sendEmailInfoById(request);
	}
	
	@RequestMapping("/emailReecipientsCombox")
	@ResponseBody     
	public Object emailReecipientsCombox(HttpServletRequest request) {//发送多封邮件
		return emailService.emailReecipientsCombox(request);
	}
}
