package com.palmnest.webapp.controller.notice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.*;
import com.palmnest.application.dto.AuditResultVo;
import com.palmnest.application.dto.DeptGroupDto;
import com.palmnest.application.dto.DeptGroupVo;
import com.palmnest.application.dto.DeptUserVo;
import com.palmnest.application.dto.OrgDto;
import com.palmnest.application.dto.output.AuditDto;
import com.palmnest.application.dto.output.AuditInfoDto;
import com.palmnest.application.dto.output.PushSendDto;
import com.palmnest.application.dto.output.PushUserDto;
import com.palmnest.model.User;
import com.palmnest.model.notice.ApprovalModel;
import com.palmnest.model.notice.EmailConfigModel;
import com.palmnest.model.notice.EmailSendModel;
import com.palmnest.model.notice.NoticeApprovalTypeModel;
import com.palmnest.model.notice.PhoneMessageModel;
import com.palmnest.service.AppUserService;
import com.palmnest.service.UserManager;
import com.palmnest.service.notice.AppNoticeManager;
import com.palmnest.service.notice.EmailConfigManager;
import com.palmnest.service.notice.EmailSendManager;
import com.palmnest.service.notice.NoticeApprovalsetManager;
import com.palmnest.service.notice.NoticeSubGroupManager;
import com.palmnest.service.notice.PhoneMessageManager;
import com.palmnest.service.notice.service.NoticePublicnoService;
import com.palmnest.service.notice.service.PushSendService;
import com.palmnest.webapp.controller.BaseFormController;
import com.sun.mail.util.MailSSLSocketFactory;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
@RequestMapping("notice/emailSend*")
public class EmailSendController extends BaseFormController {

	@Autowired
	private EmailSendManager   emailSendManager;
	@Autowired
	private EmailConfigManager emailConfigManager;
	@Autowired
	private AppNoticeManager   appNoticeManager;
	@Autowired
	private UserManager        userManager;
	@Autowired
	private PushSendService    pushSendService;
	@Autowired
	private AppUserService     appUserService;
	
	@Autowired
	private NoticeApprovalsetManager noticeApprovalsetManager;
	
	@Autowired
	private NoticePublicnoService noticePublicnoService;
	
	@Autowired
	private PhoneMessageManager phoneMessageManager;
	@Autowired
	private NoticeSubGroupManager noticeSubGroupManager;

	private final static String HOME_PATH          = EmailSendController.class.getResource("/").getPath();
	private final static String DOWNLOAD_TEMP_FILE = HOME_PATH.subSequence(0, HOME_PATH.indexOf("WEB-INF")) + "file/";

	private String hostUrl         = PropertiesKit.readPropertiesValue("hostUrl", "wechat.properties");
	private String wxEmailUrl      = PropertiesKit.readPropertiesValue("wxEmailUrl", "wechat.properties");
	private String wxEmailAuditUrl = PropertiesKit.readPropertiesValue("wxEmailAuditUrl", "wechat.properties");
	private String wxMsgUrl      = PropertiesKit.readPropertiesValue("wxMsgUrl", "wechat.properties");
	private String wxMsgAuditUrl = PropertiesKit.readPropertiesValue("wxMsgAuditUrl", "wechat.properties");

	/**
	 * 获取邮件消息列表
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getList")
	public void getList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject json = new JSONObject();
		//获取当前登录用户所管辖项目
		User   user        = (User) request.getSession().getAttribute("UserCache");
		String orgIds      = getUserManageOrgIds(user);//例如:1,25,2
		String c_beginTime = request.getParameter("c_beginTime");
		String c_endTime   = request.getParameter("c_endTime");
		String a_beginTime = request.getParameter("a_beginTime");
		String a_endTime   = request.getParameter("a_endTime");
		String state       = request.getParameter("state");
		String pageNo      = request.getParameter("page");
		String orgId       = request.getParameter("orgId");

		if (StringUtils.isNotBlank(orgId)) {
			orgIds = orgId;
		}
		if (StringUtils.isEmpty(pageNo)) {
			pageNo = "1";
		}
		String pageSize = request.getParameter("limit");
		if (StringUtils.isEmpty(pageSize)) {
			pageSize = "10";
		}
		HashMap<String, Object> map = new HashMap<String, Object>();
		if (!StringUtils.isEmpty(c_beginTime)) {
			map.put("c_beginTime", c_beginTime);
		}
		if (!StringUtils.isEmpty(c_endTime)) {
			map.put("c_endTime", c_endTime);
		}
		if (!StringUtils.isEmpty(a_beginTime)) {
			map.put("a_beginTime", a_beginTime);
		}
		if (!StringUtils.isEmpty(a_endTime)) {
			map.put("a_endTime", a_endTime);
		}
		if (!StringUtils.isEmpty(state)) {
			map.put("state", state);
		}
		if(StringUtils.isNotEmpty(orgIds)){
			map.put("orgIds", orgIds);
		}
		
		if (!StringUtils.isEmpty(orgId)) {
			map.put("orgId", orgId);
		}
		//当前登录的人的角色id
		String roleIds       = request.getParameter("roleIds");
		if(StringUtils.isNotBlank(roleIds)){
			map.put("roleIds", roleIds);
		}else{
			roleIds=getRoleIds(user);
			map.put("roleIds", roleIds);
		}
		String approvalType       = request.getParameter("approvalType");
		if (!StringUtils.isEmpty(approvalType)) {
			map.put("approvalType", approvalType);
		}

		try {
			Page page = emailSendManager.getDataList(map, Integer.parseInt(pageNo), Integer.parseInt(pageSize));
			json.put("code", "200");
			json.put("data", page.getItems());
			json.put("msg", "");
			json.put("count", page.getTotalCount());
			StringUtil.charSet(json, request, response);
		} catch (Exception e) {
			json.put("code", "1");
			json.put("data", "");
			json.put("msg", e.getMessage());
			StringUtil.charSet(json, request, response);
			log.error(e.getMessage());
			throw new Exception(e);
		}

	}

	/**
	 * 获取邮件消息详情
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getDetail")
	public void getDetail(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject json = new JSONObject();
		String     id   = request.getParameter("id");
		List<AuditDto> auditList=new ArrayList<AuditDto>();
		try {
			EmailSendModel model = emailSendManager.get(Integer.parseInt(id));
			if(null != model && null != model.getApprovalType() && 0 != model.getApprovalType().intValue()){
				auditList=noticeApprovalsetManager.getAuditList(model.getOrgId(), CodeConstants.ORDER_TYPE_EMAIL, model.getId());
			}
			
			String approvalTypeName="";
			if(null != model.getApprovalType() && 0 != model.getApprovalType().intValue()){
				NoticeApprovalTypeModel typeModel=noticeApprovalsetManager.findById(model.getApprovalType());
				if(null != typeModel){
					approvalTypeName=typeModel.getName();
				}
			}
			
			json.put("approvalTypeName", approvalTypeName);
			json.put("auditList", auditList);
			json.put("code", "200");
			json.put("data", model);
			json.put("msg", "");
			StringUtil.charSet(json, request, response);
		} catch (Exception e) {
			json.put("code", "1");
			json.put("data", "");
			json.put("auditList", auditList);
			json.put("msg", e.getMessage());
			StringUtil.charSet(json, request, response);
			log.error(e.getMessage());
			throw new Exception(e);
		}

	}

	/**
	 * 最新版获取邮箱公告详情
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/getDetailInfo")
	@ResponseBody
	public AppResultDto getDetailInfo(String id, Integer type) {
		if (!StringUtil.isNotEmpty(id)) {
			return AppResultUtil.createErrorDto("100", "id不允许为空");
		}
		try {
			PushSendDto dto = pushSendService.getDetailInfo(Integer.parseInt(id), type);
			return AppResultUtil.createSuccesDto(dto);
		} catch (Exception e) {
			log.error("获取详情失败(getDetailInfo):" + e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "获取详情失败");
		}
	}

	/**
	 * 新增修改邮件消息
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/saveOrUpdate")
	@ResponseBody
	public AppResultDto saveOrUpdate(@ModelAttribute("emailSendModel") EmailSendModel emailSend, HttpServletRequest request,
							 HttpServletResponse response) throws Exception {
		try {
			User user = (User) request.getSession().getAttribute("UserCache");

			Integer createBy=null;
			if(null != user){
				createBy=Integer.parseInt(user.getId().toString());
			}
			// 参数
			String email_theme     = request.getParameter("email_theme");// 主题
			String recipient_email = request.getParameter("recipient_email");// 收件箱
			String email_centent   = request.getParameter("email_centent");// 内容
			String contentTxt      = request.getParameter("contentTxt");// 内容
			String attach_ment     = request.getParameter("attach_ment");// 附件
			String emailaccount_id = request.getParameter("emailaccount_id");// 发件箱ID
			String orgId           = request.getParameter("orgId");
			String           approvalType   = request.getParameter("approvalType");
			String           receiveType   = request.getParameter("receiveType");
			String           deptGroupJson   = request.getParameter("deptGroupJson");//部门或分组

			int recType=Integer.parseInt(receiveType);
			String id = request.getParameter("id");
			if (StringUtils.isNotEmpty(id)) {// 修改
				emailSend = emailSendManager.get(Integer.parseInt(id));
				emailSend.setModifier(createBy.toString());
				emailSend.setModifyTime((new Date()));
				emailSend.setOrgId(Integer.parseInt(orgId));

			} else {
				emailSend.setCreator(createBy.toString());
				emailSend.setState(0);
				emailSend.setCreateTime(new Date());
				emailSend.setIsEnabled("1");
				emailSend.setOrgId(Integer.parseInt(orgId));
				if(StringUtils.isBlank(approvalType)){
					emailSend.setApprovalType(0);
				}else{
					emailSend.setApprovalType(Integer.parseInt(approvalType));
				}
			}
			String ssender_email = "";
			if (StringUtils.isNotEmpty(emailaccount_id)) {
				EmailConfigModel emailConfig = emailConfigManager.get(Integer.parseInt(emailaccount_id));
				ssender_email = emailConfig.getEmail_address();
			}
			emailSend.setSsender_email(ssender_email);
			emailSend.setEmail_theme(email_theme);
			if(StringUtils.isNotEmpty(recipient_email)){
				String[] emails = recipient_email.split(";");
				StringBuilder sb=new StringBuilder();
				for (String email : emails) {
					if (!RegularPattern.checkEmail(email)) {
						sb.append("有不合法邮箱：" + email+";");
						
					}
				}
				if(StringUtils.isNotEmpty(sb.toString())){
					return AppResultUtil.createErrorDto("1", "保存邮件消息失败:"+sb.toString());
				}
			}
			
			emailSend.setReceiveType(recType);
			emailSend.setRecipient_email(recipient_email);
			emailSend.setEmail_centent(email_centent);
			emailSend.setAttach_ment(attach_ment);
			emailSend.setEmailaccount_id(Integer.parseInt(emailaccount_id));
			// test 暂时使用配置邮箱
			//emailSend.setEmailaccount_id(1);
			emailSend.setContentTxt(contentTxt);

			emailSend = emailSendManager.saveOrUpdate(emailSend);
			if(2 == recType && null != emailSend && null != emailSend.getId() && StringUtils.isNotEmpty(deptGroupJson)){
				//发送方式:1-按邮箱发送；2-按部门/分组发送
				List<DeptGroupDto> dtoList=JSONObject.parseArray(deptGroupJson,DeptGroupDto.class);
				if(!CollectionUtils.isEmpty(dtoList)){
					//类型：1-公告;2-微信模板;3-短信;4-邮件;
					noticeSubGroupManager.saveByDeptGroup(4, emailSend.getId(), dtoList, createBy);
					//保存完了之后把用户信息查出来，然后保存到相应的数据里面去
					AppResultDto dto=appNoticeManager.setUserInfo(orgId, dtoList, 1);
					if("200".equals(dto.getCode())){
						emailSend.setRecipient_email(dto.getMsg());
						emailSendManager.saveOrUpdate(emailSend);
					}
				}else{
					return AppResultUtil.createErrorDto("1", "保存邮件消息失败:未选择部门或分组");
				}
			}
			
			String     pathUrl = hostUrl + wxEmailAuditUrl.replace("@id", emailSend.getId().toString())+ "&isApproval=1&approvalType="+emailSend.getApprovalType();
			//新增的时候才推送
			if(StringUtils.isBlank(id)){
				if(null != emailSend.getApprovalType() && 0 != emailSend.getApprovalType().intValue()){
					//推送消息
					List<User> users=noticePublicnoService.getPushMsgUserById(emailSend.getApprovalType(), emailSend.getOrgId(), CodeConstants.ORDER_TYPE_EMAIL, emailSend.getId());
					if(!CollectionUtils.isEmpty(users)){
						appNoticeManager.pushMessage(Long.parseLong(emailSend.getId().toString()), CodeConstants.EMAIL_PUSH_CODE, pathUrl, "您有新的待审核邮件消息，请及时审核！", "有新邮件消息待审核", users);
					}
				}else{
					//推送消息
					List<User> users   = userManager.findByFunction(emailSend.getOrgId(), CodeConstants.AUDIT_NOTICE_PERMISSION);
					appNoticeManager.pushMessage(Long.parseLong(emailSend.getId().toString()), CodeConstants.EMAIL_PUSH_CODE, pathUrl, "有新公告通知待审核", "有新邮件消息待审核", users);
				}
			}
			return AppResultUtil.createCommonDto("200", "success", "success");
		} catch (Exception e) {
			log.error("保存邮件消息失败:"+e.getMessage());
			return AppResultUtil.createErrorDto("1", "保存邮件消息失败:"+e.getMessage());
		}

	}
	


	/**
	 * 接收用户上传附件
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/uploadFile")
	@ResponseBody
	public void uploadFile(@RequestParam(value = "uploadfile", required = false) CommonsMultipartFile uploadFy,
						   HttpServletRequest request, HttpServletResponse response) {
		JSONObject          json = new JSONObject();
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			InputStream stream  = null;
			String      fileExt = null;
			if (uploadFy != null) {
				stream = uploadFy.getInputStream();
				String fileName = uploadFy.getOriginalFilename();
				fileName = new String(fileName.getBytes(), "utf-8");
				fileExt = StringUtils.isNotEmpty(fileName) ? fileName
						.substring(fileName.lastIndexOf("."))
						: StringUtils.EMPTY;

				FileUploadUtils fileUploadUtils = new FileUploadUtils();
				fileUploadUtils.init();
				String url = fileUploadUtils.uploadFile(stream, fileExt);
//				String saveName= fileUploadUtils.fullVisitPath(url);
				String fileOrgName = uploadFy.getFileItem().getName();
				json.put("code", "200");
				json.put("msg", "上传成功！");
				json.put("data", url + ";" + fileOrgName);
				StringUtil.charSet(json, request, response);
			} else {
				json.put("code", "1");
				json.put("msg", "fail");
				json.put("data", "上传文件为空");
				StringUtil.charSet(json, request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", "1");
			json.put("msg", "fail");
			json.put("data", "文件上传失败！");
			StringUtil.charSet(json, request, response);
			log.error(e.getMessage());
		}
	}
	
	/**
	 * 审核-----多级审核
	 *
	 * @param request
	 * @param dto
	 * @return
	 */
	@RequestMapping(value = "/approvalSendNew")
	@ResponseBody
	public AppResultDto approvalSendNew(HttpServletRequest request, PushSendDto dto) {
		User   user    = (User) request.getSession().getAttribute("UserCache");
		String auditor = "0";
		String userName = "";
		if (user != null) {
			auditor = user.getId().toString();
			userName = StringUtils.isNotBlank(user.getFullName()) ? user.getFullName() : user.getUsername();
		}
		
		int approvalResult=2;
		if(null != dto.getIsPass() && 1 == dto.getIsPass().intValue()){
			approvalResult=1;
		}
		int haveNext = 0;//是否有下一级审核人 0-没有；1-有
		String pathUrl = "";//跳转地址
		Integer codeType = 0;//单据类型
		Integer orgId = 0;//项目id
		Integer approvalType = 0;//审核类型id
		Integer orderId = 0;//订单id
		if(null != dto.getType() && 1 == dto.getType().intValue()){ //短信
			PhoneMessageModel model = phoneMessageManager.get(dto.getId());
			if(null == model){
				return AppResultUtil.createErrorDto("100", "审核失败:未获取到单据信息");
			}
			//部门分组发送时，目标用户不能为空
			if(null != model.getReceiveType() && 2 == model.getReceiveType().intValue() && StringUtils.isEmpty(model.getPhones())){
				return AppResultUtil.createErrorDto("100", "发送的用户不能为空，无法审核");
			}
			codeType = CodeConstants.ORDER_TYPE_MESSAGE;
			pathUrl = hostUrl + wxMsgAuditUrl.replace("@id", model.getId().toString());
			orgId = model.getOrgId();
			approvalType = model.getApprovalType();
			orderId = model.getId();
		}else if(null != dto.getType() && 2 == dto.getType().intValue()){ //邮件
			EmailSendModel model = emailSendManager.get(dto.getId());
			if(null == model){
				return AppResultUtil.createErrorDto("100", "审核失败:未获取到单据信息");
			}
			//部门分组发送时，目标用户不能为空
			if(null != model.getReceiveType() && 2 == model.getReceiveType().intValue() && StringUtils.isEmpty(model.getRecipient_email())){
				return AppResultUtil.createErrorDto("100", "发送的用户不能为空，无法审核");
			}
			codeType=CodeConstants.ORDER_TYPE_EMAIL;
			
			pathUrl = hostUrl + wxEmailAuditUrl.replace("@id", model.getId().toString());
			orgId = model.getOrgId();
			approvalType = model.getApprovalType();
			orderId = model.getId();
		}
		AuditResultVo auditResultVo = new AuditResultVo();
		if(null != approvalType && 0 != approvalType.intValue()){
			AuditInfoDto auditDto=new AuditInfoDto(orgId,codeType,orderId, approvalType,Integer.parseInt(auditor), userName, approvalResult,dto.getAuditOpinion());
			auditResultVo=noticeApprovalsetManager.saveAuditInfo(auditDto);
			haveNext=auditResultVo.getHaveNext();
		}
		
		if(0 == haveNext || 2 == approvalResult){
			List<PushUserDto> carDto     = new ArrayList<PushUserDto>();
			String            carDtoJson = request.getParameter("usersList");
			if (StringUtils.isNotEmpty(carDtoJson)) {
				carDto = JSON.parseArray(carDtoJson, PushUserDto.class);
			}
			if (carDto != null && carDto.size() > 0) {
				AppResultDto appResultDto=pushSendService.approvalSend(dto, auditor, carDto, "");
				if(null != auditResultVo && null != auditResultVo.getApprovalModel() && !"200".equals(appResultDto.getCode())){
					ApprovalModel approvalModel=auditResultVo.getApprovalModel();
					approvalModel.setEnabled(0);
					approvalModel.setModifier(Integer.parseInt(user.getId().toString()));
					approvalModel.setModifTime(new Date());
					noticeApprovalsetManager.updateApproval(approvalModel);
				}
				return appResultDto;
			}
			return AppResultUtil.createErrorDto("100", "终审失败");
		}else{
			pathUrl = pathUrl+"&isApproval=1&approvalType="+approvalType;
			//推送消息给下一级审核人
			List<User> users=noticePublicnoService.getPushMsgUserById(approvalType, orgId, codeType, orderId);
			if(!CollectionUtils.isEmpty(users)){
				try {
					if(codeType == CodeConstants.ORDER_TYPE_EMAIL){
						appNoticeManager.pushMessage(Long.parseLong(orderId.toString()), CodeConstants.EMAIL_PUSH_CODE, pathUrl, "您有新的待审核邮件消息，请及时审核！", "有新邮件消息待审核", users);
					}else if(codeType == CodeConstants.ORDER_TYPE_MESSAGE){
						appNoticeManager.pushMessage(Long.parseLong(orderId.toString()), CodeConstants.MESSAGE_PUSH_CODE, pathUrl, "您有新的待审核短信消息，请及时审核！", "有新短信消息待审核", users);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return AppResultUtil.createErrorDto("100", "审核失败");
				}
			}
		}
		return AppResultUtil.createSuccesDto();
	}

	/**
	 * 审核
	 *
	 * @param request
	 * @param dto
	 * @return
	 */
	@RequestMapping(value = "/approvalSend")
	@ResponseBody
	public AppResultDto approvalSend(HttpServletRequest request, PushSendDto dto) {
		User   user    = (User) request.getSession().getAttribute("UserCache");
		String auditor = "";
		if (user != null) {
			auditor = user.getId().toString();
		}
		List<PushUserDto> carDto     = new ArrayList<PushUserDto>();
		String            carDtoJson = request.getParameter("usersList");
		if (StringUtils.isNotEmpty(carDtoJson)) {
			carDto = JSON.parseArray(carDtoJson, PushUserDto.class);
		}
		if (carDto != null && carDto.size() > 0) {
			return pushSendService.approvalSend(dto, auditor, carDto, "");
		}
		return AppResultUtil.createErrorDto("100", "发布失败");
	}


	/**
	 * 审核邮件信息
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/approval")
	public void approval(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject json = new JSONObject();
		try {
			User user = (User) request.getSession().getAttribute("UserCache");

			String id      = request.getParameter("id");
			String state   = request.getParameter("state");
			String pathUrl = hostUrl + wxEmailUrl.replace("@id", id);

			if (StringUtils.isNotEmpty(id)) {// 修改
				EmailSendModel emailSend = emailSendManager.get(Integer.parseInt(id));

				emailSend.setApproval_user(user.getFullName());
				emailSend.setApproval_time((new Date()));
				emailSend.setState(Integer.parseInt(state));//0待审核1已发布2已驳回
				emailSend.setSend_time(new Date());

				emailSend.setTotal(emailSend.getRecipient_email().split(";").length);
				String     userId = emailSend.getCreator();
				List<User> users  = new ArrayList<User>();
				User       user1  = userManager.get(Long.parseLong(userId));
				users.add(user1);
//				emailSendManager.updateModel(emailSend);
				if (emailSend.getState() == 1) {
					EmailConfigModel   emailConfigModel = emailConfigManager.get(emailSend.getEmailaccount_id());
					JavaMailSenderImpl senderImpl       = new JavaMailSenderImpl();
					senderImpl.setHost(emailConfigModel.getSmtp_server());
					senderImpl.setPort(emailConfigModel.getStmp_port());
					senderImpl.setUsername(emailConfigModel.getEmail_address());
					senderImpl.setPassword(emailConfigModel.getPassword());
					senderImpl.setDefaultEncoding("UTF-8");
					Properties           prop = new Properties();
					MailSSLSocketFactory sf   = new MailSSLSocketFactory();
					sf.setTrustAllHosts(true);
					prop.put("mail.smtp.ssl.enable", "true");
					prop.put("mail.smtp.ssl.socketFactory", sf);
					prop.put("mail.smtp.auth", "true");
					prop.put("mail.smtp.timeout", "20000");
					senderImpl.setJavaMailProperties(prop);
					MimeMessage       mail   = senderImpl.createMimeMessage();
					MimeMessageHelper helper = new MimeMessageHelper(mail, true, "UTF-8");
					if (StringUtils.isNotEmpty(emailConfigModel.getSend_email_name())) {
						helper.setFrom(emailConfigModel.getEmail_address(), emailConfigModel.getSend_email_name()); // 发件人_发信名称
					} else {
						helper.setFrom(emailConfigModel.getEmail_address()); // 发件人
					}
					if (emailSend.getRecipient_email().indexOf(";") != -1) {
						helper.setTo(emailSend.getRecipient_email().split(";")); // 收件人
					} else {
						helper.setTo(emailSend.getRecipient_email()); // 收件人
					}
					// helper.setSubject("逾期账单"); //邮件主题

//					helper.setText(text, false); // 邮件内容
					StringBuilder html = new StringBuilder();
					html.append("<html>");
					html.append("<body>");
					html.append(emailSend.getEmail_centent()); // 邮件内容
					html.append("</body>");
					html.append("</html>");
					// 保存至收件箱start
					helper.setSubject(emailSend.getEmail_theme());
					helper.setText(html.toString(), true);

					String folderLocalPathString = request.getSession().getServletContext().getRealPath("/upload");
					String attachMentstr         = emailSend.getAttach_ment();
					String rootPath              = FileUploadUtils.getATTACHMENT_ROOT();
//					if (attachMentstr.split(",").length > 0) {
					if (StringUtils.isNotEmpty(attachMentstr)) {
						for (int i = 0; i < attachMentstr.split(",").length; i++) {
							String array_element = attachMentstr.split(",")[i];
							if (!array_element.equals("")) {
//								helper.addAttachment(
//										array_element.replace(array_element.substring(array_element.lastIndexOf('_'),
//												array_element.lastIndexOf('.')), ""),
//										new File(folderLocalPathString + "/" + array_element));
//								helper.addAttachment(array_element, new File(folderLocalPathString + "/" + array_element));
//								System.out.println(rootPath+"/"+array_element.split(";")[1]);
								String addr     = array_element.split(";")[0];
								String fileName = array_element.split(";")[1];
//								System.out.println(fileName);
								helper.addAttachment(fileName, new File(rootPath + "/" + addr));
							}
						}
					}

					senderImpl.send(mail);

					emailSendManager.updateModel(emailSend);
					json.put("code", "200");
					json.put("msg", "success");
					json.put("data", "发送");
					StringUtil.charSet(json, request, response);
//					emailSendManager.sendMesseg(id, userId, "4", "审核通过");
					appNoticeManager.pushMessage(Long.parseLong(id), CodeConstants.EMAIL_PUSH_CODE, pathUrl, "您发起的邮箱消息已审核通过", "已审核通过", users);
				} else if (emailSend.getState() == 0) {
					emailSendManager.updateModel(emailSend);
					json.put("code", "200");
					json.put("msg", "success");
					json.put("data", "未通过审核");
					StringUtil.charSet(json, request, response);
				} else if (emailSend.getState() == 2) {
					emailSendManager.updateModel(emailSend);
					json.put("code", "200");
					json.put("msg", "success");
					json.put("data", "已驳回");
					StringUtil.charSet(json, request, response);
//					emailSendManager.sendMesseg(id, userId, "4", "被驳回");
					appNoticeManager.pushMessage(Long.parseLong(id), CodeConstants.EMAIL_PUSH_CODE, pathUrl, "您发起的邮箱消息已被驳回", "未通过审核", users);
				} else {
					emailSend.setState(0);
					emailSendManager.updateModel(emailSend);
					json.put("code", "1");
					json.put("msg", "fail");
					json.put("data", "参数错误");
					StringUtil.charSet(json, request, response);
				}
			} else {
				json.put("code", "1");
				json.put("msg", "fail");
				json.put("data", "参数错误");
				StringUtil.charSet(json, request, response);
			}

		} catch (Exception e) {
			json.put("code", "1");
			json.put("msg", "fail");
			json.put("data", e.getMessage());
			StringUtil.charSet(json, request, response);
			log.error(e.getMessage());
			e.printStackTrace();
			throw new Exception(e);
		}

	}

	/**
	 * 公告部分文本编辑器文件异步上传
	 *
	 * @param multipartFile
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/ueAction")
	@ResponseBody
	public String ueAction(@RequestParam(value = "uploadfile", required = false) CommonsMultipartFile multipartFile,
						   HttpServletRequest request, HttpServletResponse response) {
		Map<String, String> map    = new HashMap<String, String>();
		String              picUrl = "";
		try {
			//获得文件原始名称
			InputStream stream   = null;
			String      fileExt  = null;
			String      fileName = "";
			if (multipartFile != null) {
				stream = multipartFile.getInputStream();
				fileName = multipartFile.getOriginalFilename();
				fileName = new String(fileName.getBytes(), "utf-8");
				fileExt = StringUtils.isNotEmpty(fileName) ? fileName
						.substring(fileName.lastIndexOf("."))
						: StringUtils.EMPTY;
			}

			FileUploadUtils fileUploadUtils = new FileUploadUtils();
			fileUploadUtils.init();
			String url = fileUploadUtils.uploadFile(stream, fileExt);
			picUrl = fileUploadUtils.fullVisitPath(url);
		} catch (Exception e) {
			// message= "文件上传失败！";
			e.printStackTrace();

		}
		map.put("title", picUrl);
		map.put("url", picUrl);
		map.put("original", picUrl);
		map.put("state", "SUCCESS");
		return JSONObject.toJSONString(map);

	}

	/**
	 * 新增时 获取发送人邮箱的接口
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getUserEmail")
	public void getUserEmail(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject json   = new JSONObject();
		String     orgIds = request.getParameter("orgIds");
		try {
			// emailSendManager
			User         user = (User) request.getSession().getAttribute("UserCache");
			List<OrgDto> dtos = appUserService.getUserOrgs(user.getId());
			if (StringUtils.isEmpty(orgIds) || "0".equals(orgIds)) {
				if (dtos != null && dtos.size() > 0) {
					orgIds = "";
					for (int i = 0; i < dtos.size(); i++) {
						OrgDto dto = dtos.get(i);
						orgIds = orgIds + dto.getId() + ";";
					}
				}
			}
			Page page = emailSendManager.getEmailUser(orgIds);
			json.put("code", "200");
			json.put("msg", "success");
			json.put("data", page);
			StringUtil.charSet(json, request, response);

		} catch (Exception e) {
			json.put("code", "1");
			json.put("msg", "fail");
			StringUtil.charSet(json, request, response);
			log.error(e.getMessage());
			throw new Exception(e);
		}

	}

	/**
	 * 新增时导入的接口
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/txtToEmail")
	@ResponseBody
	public void txtToEmail(@RequestParam(value = "uploadfile", required = false) CommonsMultipartFile uploadFy,
						   HttpServletRequest request, HttpServletResponse response) {
		JSONObject  json = new JSONObject();
		InputStream in   = null;
		if (uploadFy == null) {
			json.put("code", "1");
			json.put("msg", "fail");
			json.put("data", "上传文件为空");

			StringUtil.charSet(json, request, response);
		}
		try {
			// 使用Apache文件上传组件处理文件上传步骤：
			// 1、创建一个DiskFileItemFactory工厂
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 2、创建一个文件上传解析器
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 解决上传文件名的中文乱码
			upload.setHeaderEncoding("UTF-8");
			// 3、判断提交上来的数据是否是上传表单的数据
			if (!ServletFileUpload.isMultipartContent(request)) {
				// 按照传统方式获取数据
				json.put("code", "1");
				json.put("msg", "fail");
				json.put("data", "没有文件上传");
				StringUtil.charSet(json, request, response);
			}
			in = uploadFy.getInputStream();
			InputStreamReader  inputStreamReader = new InputStreamReader(in);
			BufferedReader     br                = new BufferedReader(inputStreamReader);
			String             expr              = "^([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})$";
			Pattern            pattern           = Pattern.compile(expr);
			ArrayList<String>  emailList         = new ArrayList<String>();
			String             temp              = null;
			ArrayList<Integer> errorLine         = new ArrayList<Integer>();
			for (int i = 1; (temp = br.readLine()) != null; i++) {
				temp.trim();
				Matcher matcher = pattern.matcher(temp);
				if (matcher.matches()) {
					emailList.add(temp);
				} else {
					errorLine.add(i);
				}
			}
			StringBuffer errorLineBuffer = new StringBuffer();
			errorLineBuffer.append("上传成功,第");
			for (Integer integer : errorLine) {
				errorLineBuffer.append(integer + ",");
			}
			if (errorLineBuffer.toString().equals("上传成功,第") && !emailList.isEmpty()) {
				json.put("code", "200");
				json.put("msg", "success");
				json.put("data", emailList);
			} else if (errorLineBuffer.toString().equals("上传成功,第") && emailList.isEmpty()) {
				json.put("code", "1");
				json.put("msg", "导入失败,文件为空!");
			} else {
				errorLineBuffer.append("行数据格式有错误");
				json.put("code", "1");
				json.put("msg", errorLineBuffer.toString());
				json.put("data", emailList);
			}

			StringUtil.charSet(json, request, response);
		} catch (Exception e) {
			// message= "文件上传失败！";
			json.put("code", "1");
			json.put("msg", "fail");
			json.put("data", "文件上传失败！");

			StringUtil.charSet(json, request, response);
			log.error(e.getMessage());
			e.printStackTrace();
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

//	/**
//	 * 发送邮件
//	 * 
//	 * @param request
//	 * @param response
//	 * @return
//	 * @throws Exception
//	 */
//	@RequestMapping(value = "/sendEmail")
//	public void sendEmail(HttpServletRequest request, HttpServletResponse response) throws Exception {
//		JSONObject json = new JSONObject();
//		String user = request.getParameter("user");
//		String userEmail = request.getParameter("userEmail");
//		String text = request.getParameter("text");
//
//		if (StringUtils.isNotBlank(user) && StringUtils.isNotBlank(userEmail)) {
//			try {
//				JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
//				senderImpl.setHost("smtp.163.com");
//				senderImpl.setPort(465);
//				senderImpl.setUsername(EMAIL_ADDRESS);
//				senderImpl.setPassword(EMAIL_NAME);
//				senderImpl.setDefaultEncoding("UTF-8");
//				Properties prop = new Properties();
//				MailSSLSocketFactory sf = new MailSSLSocketFactory();
//				sf.setTrustAllHosts(true);
//				prop.put("mail.smtp.ssl.enable", "true");
//				prop.put("mail.smtp.ssl.socketFactory", sf);
//				prop.put("mail.smtp.auth", "true");
//				prop.put("mail.smtp.timeout", "20000");
//				senderImpl.setJavaMailProperties(prop);
//				MimeMessage mail = senderImpl.createMimeMessage();
//				MimeMessageHelper helper = new MimeMessageHelper(mail, true, "UTF-8");
//				if (StringUtils.isNotEmpty(EMAIL_NAME)) {
//					helper.setFrom(EMAIL_ADDRESS, EMAIL_NAME); // 发件人_发信名称
//				} else {
//					helper.setFrom(EMAIL_ADDRESS); // 发件人
//				}
//				helper.setTo(userEmail); // 收件人
//
//				// helper.setSubject("逾期账单"); //邮件主题
//
//				helper.setText(text, false); // 邮件内容
//				// 保存至收件箱start
//				senderImpl.send(mail);
//
//				json.put("code", "200");
//				json.put("msg", "success");
//				json.put("data", "发送");
//				StringUtil.charSet(json, request, response);
//			} catch (Exception e) {
//				json.put("code", "1");
//				json.put("msg", "fail");
//				json.put("data", "发送失败");
//				StringUtil.charSet(json, request, response);
//				e.printStackTrace();
//			}
//		}
//	}
//


	/**
	 * 下载用户上传附件
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/downloadFile")
	@ResponseBody
	public void uploadFile(HttpServletRequest request, HttpServletResponse response) {
		JSONObject json     = new JSONObject();
		String     filename = request.getParameter("filename");
		try {
			response.reset();// 清空输出流

//	            String resultFileName = filename.substring(filename.lastIndexOf(".")+1);
			String resultFileName = filename;
			resultFileName = URLEncoder.encode(resultFileName, "UTF-8");
			response.setCharacterEncoding("UTF-8");
			response.setHeader("Content-disposition", "attachment; filename=" + resultFileName);// 设定输出文件头
			// response.setContentType("application/msexcel");// 定义输出类型
			//输入流：本地文件路径
			DataInputStream in = new DataInputStream(new FileInputStream(new File(filename)));
			//输出流
			OutputStream out = response.getOutputStream();
			//输出文件
			int    bytes     = 0;
			byte[] bufferOut = new byte[1024];
			while ((bytes = in.read(bufferOut)) != -1) {
				out.write(bufferOut, 0, bytes);
			}
			out.close();
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
			response.reset();
			try {
				OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
				String             data   = "<script language='javascript'>alert(\"\\u64cd\\u4f5c\\u5f02\\u5e38\\uff01\");</script>";
				writer.write(data);
				writer.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}

	/**
	 * 删除邮件公告
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/deleteNotice")
	@ResponseBody
	public void deleteNotice(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		emailSendManager.remove(Integer.parseInt(id));
		JSONObject json = new JSONObject();
		json.put("code", "200");
		json.put("msg", "success");
		StringUtil.charSet(json, request, response);
	}


//	/**
//	 * 跳转到界面
//	 * 
//	 * @param request
//	 * @param response
//	 */
//	@RequestMapping(value = "/noticeEmailSend*")
//	public ModelAndView noticeEmailSend(HttpServletRequest request, HttpServletResponse response) {
//		return new ModelAndView("admin/notice/noticeEmailSend");
//	}
//
//	/**
//	 * 跳转到界面-发布
//	 * 
//	 * @param request
//	 * @param response
//	 */
//	@RequestMapping(value = "/noticeEmailPublish*")
//	public ModelAndView noticeEmailPublish(HttpServletRequest request, HttpServletResponse response) {
//		return new ModelAndView("admin/notice/noticeEmailPublish");
//	}
//
//	/**
//	 * 跳转到界面-审核
//	 * 
//	 * @param request
//	 * @param response
//	 */
//	@RequestMapping(value = "/noticeEmailVerify*")
//	public ModelAndView noticeEmailVerify(HttpServletRequest request, HttpServletResponse response) {
//		return new ModelAndView("admin/notice/noticeEmailVerify");
//	}
//	
}


//// 发布邮件
//EmailConfigModel emailConfigModel = emailConfigManager.get(emailSend.getEmailaccount_id());
//
//JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
//senderImpl.setHost(emailConfigModel.getSmtp_server());
//senderImpl.setPort(emailConfigModel.getStmp_port());
//senderImpl.setUsername(emailConfigModel.getEmail_address());
//senderImpl.setPassword(emailConfigModel.getPassword());
//senderImpl.setDefaultEncoding("UTF-8");
//Properties prop = new Properties();
//MailSSLSocketFactory sf = new MailSSLSocketFactory();
//sf.setTrustAllHosts(true);
//prop.put("mail.smtp.ssl.enable", "true");
//prop.put("mail.smtp.ssl.socketFactory", sf);
//prop.put("mail.smtp.auth", "true");
//prop.put("mail.smtp.timeout", "20000");
//senderImpl.setJavaMailProperties(prop);
//MimeMessage mail = senderImpl.createMimeMessage();
//MimeMessageHelper helper = new MimeMessageHelper(mail, true, "UTF-8");
//if (StringUtils.isNotEmpty(emailConfigModel.getSend_email_name())) {
//	helper.setFrom(emailConfigModel.getEmail_address(), emailConfigModel.getSend_email_name()); // 发件人_发信名称
//} else {
//	helper.setFrom(emailConfigModel.getEmail_address()); // 发件人
//}
//
//if (emailSend.getRecipient_email().indexOf(";") != -1) {
//	helper.setTo(emailSend.getRecipient_email().split(";")); // 收件人
//} else {
//	helper.setTo(emailSend.getRecipient_email()); // 收件人
//}
//
//helper.setSubject(emailSend.getEmail_theme()); // 邮件主题
//StringBuilder html = new StringBuilder();
////html.append("<html>");
////html.append("<body>");
//
//html.append(emailSend.getEmail_centent()); // 邮件内容
//
////html.append("</body>");
////html.append("</html>");
//
//helper.setText(html.toString(), true); // 邮件发送
//
//String folderLocalPathString = request.getSession().getServletContext().getRealPath("/upload");
//String attachMentstr = emailSend.getAttach_ment();
////if (attachMentstr.split(",").length > 0) {
////	for (int i = 0; i < attachMentstr.split(",").length; i++) {
////		String array_element = attachMentstr.split(",")[i];
////		if (!array_element.equals("")) {
////			helper.addAttachment(array_element,new File(folderLocalPathString + "/" + array_element));
////		}
////	}
////}
//senderImpl.send(mail);

