package com.palmnest.webapp.controller.notice;

import cn.superdesk.libs.common.json.JsonUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.palmnest.application.AppConstants;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.Constants;
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.NoticeWxTempVo;
import com.palmnest.application.dto.OrgDto;
import com.palmnest.application.dto.WebPageResultDto;
import com.palmnest.application.dto.output.AuditDto;
import com.palmnest.application.dto.output.AuditInfoDto;
import com.palmnest.application.dto.output.NoticeDto;
import com.palmnest.application.dto.output.PushSendDto;
import com.palmnest.application.dto.output.PushUserDto;
import com.palmnest.model.*;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.estateserve.WxPublicno;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.model.notice.*;
import com.palmnest.service.ElementGroupManager;
import com.palmnest.service.UserManager;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.estateserve.ScWxuserManager;
import com.palmnest.service.estateserve.SmsAuthCodeManager;
import com.palmnest.service.notice.*;
import com.palmnest.service.notice.service.NoticePublicnoService;
import com.palmnest.service.notice.service.PushSendService;
import com.palmnest.service.redis.BaseRedisService;
import com.palmnest.webapp.controller.BaseFormController;
import com.sun.mail.util.MailSSLSocketFactory;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.directwebremoting.util.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
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.util.LinkedCaseInsensitiveMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.text.SimpleDateFormat;
import java.util.*;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
@RequestMapping("wechat/notice*")
public class WxNoticeController extends BaseFormController{

	@Autowired
	private WxtemplateMessageManager wxtemplateMessageManager;
	@Autowired
	private WxtemplateConfigParaManager wxtemplateConfigParaManager;
	@Autowired
	private WxtemplateMessageTypeManager wxTypeManager ;
	@Autowired
	private AppNoticeManager appNoticeManager;
	@Autowired
	private PhoneMessageManager phoneMessageManager;
	@Autowired
	private EmailSendManager emailSendManager;
	@Autowired
	private EmailConfigManager emailConfigManager;
	@Autowired
	private UserManager userManager;
	@Autowired
	private WxPubManager wxPubManager;
	@Autowired
	private BaseRedisService baseRedisService;
	@Autowired
	private SmsAuthCodeManager smsAuthCodeManager;
	@Autowired
	private ElementGroupManager elementGroupManager;
	@Autowired
	private ScWxuserManager scWxuserManager;

	@Autowired
	private PushSendService pushSendService;

	@Autowired
	private NoticePublicnoService noticePublicnoService;
	@Autowired
	private ArticleCensusManager articleCensusManager;
	@Autowired
	private AppUserManager                 appUserManager;
	@Autowired
	private NoticeApprovalsetManager noticeApprovalsetManager;


	@Autowired
	private AppNoticeRecordManager      appNoticeRecordManager;

	private String smsServer=PropertiesKit.readPropertiesValue("sms_server", "wechat.properties");

	private String hostUrl=PropertiesKit.readPropertiesValue("hostUrl", "wechat.properties");
	private String wxWechatUrl=PropertiesKit.readPropertiesValue("wxWechatUrl", "wechat.properties");
	private String wxAppNoticeUrl=PropertiesKit.readPropertiesValue("wxAppNoticeUrl", "wechat.properties");
	private String wxEmailUrl=PropertiesKit.readPropertiesValue("wxEmailUrl", "wechat.properties");
	private String wxMsgUrl=PropertiesKit.readPropertiesValue("wxMsgUrl", "wechat.properties");
	private String wxEmailAuditUrl = PropertiesKit.readPropertiesValue("wxEmailAuditUrl", "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();
		String state="1";
		String pageNo=request.getParameter("page");
		String pageSize=request.getParameter("limit");
		String openId=request.getParameter("openId");
		String orgId=request.getParameter("orgId");
		WxUser wxUser=scWxuserManager.getScWxuserByOpenId(openId);
		try{
			int i=0;
			if(StringUtils.isEmpty(pageNo)){
				pageNo="1";
			}
			if(StringUtils.isEmpty(pageSize)){
				pageSize="10";
			}
			i = Integer.parseInt(pageSize);
			i = Integer.parseInt(pageNo);

			HashMap<String, Object> map = new HashMap<String,Object>();
			if(!StringUtils.isEmpty(state)){
				map.put("state", state);

				i = Integer.parseInt(state);
			}
			//优先传入的orgId参数，如果没有就通过openId拿orgId
			if (StringUtils.isNotEmpty(orgId)) {
				map.put("orgId", orgId);
				i = Integer.parseInt(orgId);
			}else{
				if (wxUser != null && null != wxUser.getOrganizationId()) {
					map.put("orgIds", wxUser.getOrganizationId());
				}else{
					throw new Exception("参数不正确！");
				}
			}


		map.put("type", 4);//微信首页列表
		map.put("receiveType", 1);//只看全部的，不看部分的

			Page page=wxtemplateMessageManager.getDataList(map,Integer.parseInt(pageNo),Integer.parseInt(pageSize));

			ArrayList<TempSaverList> resultList = new ArrayList<TempSaverList>();
			List<Map<String, Object>> list = page.getItems();
	    	 Map<String, Object> tempMap = new LinkedCaseInsensitiveMap<Object>();
	         for(Map<String, Object> e : list) {
	        	 TempSaverList temp = new TempSaverList();

	         	 SimpleDateFormat sdf= new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
	         	 SimpleDateFormat sdfResult= new SimpleDateFormat("yyyy年M月d日 HH:mm:ss");
	        	 if(StringUtils.isNotEmpty((String) e.get("createTime"))){
	        		 Date date= sdf.parse((String) e.get("createTime"));
	        		 temp.setCreateTime(sdfResult.format(date));
	        	 }
	        	 if(StringUtils.isNotEmpty((String) e.get("approval_time"))){
	        		 Date date= sdf.parse((String) e.get("approval_time"));
	        		 temp.setApproval_time(sdfResult.format(date));
	        	 }
	        	 if(StringUtils.isNotEmpty((String) e.get("modifierTime"))){
	        		 Date date= sdf.parse((String) e.get("modifierTime"));
	        		 temp.setModifyTime(sdfResult.format(date));
	        	 }
	        	 temp.setId((Integer) e.get("id"));
	        	 temp.setWechat_template_id((Integer) e.get("wechat_template_id"));
	        	 temp.setOpen_id((String) e.get("open_id"));
	        	 temp.setTitle((String) e.get("title"));
	        	 temp.setUrl((String) e.get("url"));
	        	 temp.setState((Integer) e.get("state"));
	        	 temp.setApproval_user((String) e.get("approval_user"));
	        	 temp.setCreator((String) e.get("creator"));
	        	 temp.setModifier((String) e.get("modifier"));
	        	 temp.setIsEnabled((String) e.get("isEnabled"));
	        	 temp.setTotal((Integer) e.get("total"));
	        	 //根据id获取详情数据
	        	 //模板参数	数据
	        	 List<WxtemplateConfigPara> configParaList = wxtemplateConfigParaManager.getWxTemplConfigByTypeId(temp.getId());
	        	 //模板名字	数据
	        	 WxtemplateMessageTypeModel typeModel = wxTypeManager.get(temp.getWechat_template_id());

	        	 temp.setParamList(configParaList);
	        	 temp.setTemplateName(typeModel.getName());
	        	 resultList.add(temp);
	         }
			json.put("code", "200");
			json.put("data", resultList);
			json.put("msg", "success");
			json.put("count", page.getTotalCount());
			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);
		}
	}


	@RequestMapping(value = "/updateRecord")
	@ResponseBody
	public WebPageResultDto updateRecord(HttpServletRequest request, HttpServletResponse response) throws Exception {

		HashMap<String, Object> map = new HashMap<String, Object>();
		String id  = request.getParameter("id");
		String openId  = request.getParameter("openId");
		String userId  = request.getParameter("userId");
		String orgId  = request.getParameter("orgId");
		String sourceType  = request.getParameter("sourceType");
		log.info("exportReportList ,id:{},orgId:{};openId:{},userId:{};sourceType:{}",id,orgId,openId,userId,sourceType);
		if(StringUtils.isEmpty(id)){
			return new WebPageResultDto(AppConstants.ERROR_CODE, "订单id不能为空", null);
		}
		if(StringUtils.isEmpty(openId) && StringUtils.isEmpty(userId)){
			return new WebPageResultDto(AppConstants.ERROR_CODE, "用户为空", null);
		}
		int i = 0;
		if (!StringUtils.isEmpty(orgId)) {
			map.put("orgId", orgId);
			i = Integer.parseInt(orgId);
		}
		if (!StringUtils.isEmpty(id)) {
			map.put("id", id);
			i = Integer.parseInt(id);
		}
		if (!StringUtils.isEmpty(userId)) {
			map.put("userId", userId);
			i = Integer.parseInt(userId);
		}
		if (!StringUtils.isEmpty(openId)) {
			map.put("openId", openId);
		}
		if (!StringUtils.isEmpty(sourceType)) {
			map.put("sourceType", sourceType);
		}
		try {
			appNoticeRecordManager.updateRecord(map);
			return 	new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功",null);
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return new WebPageResultDto(AppConstants.ERROR_CODE, "修改失败", null);
		}
	}

	@RequestMapping(value = "/getDetail")
	@ResponseBody
	public AppResultDto getDetail(HttpServletRequest request,HttpServletResponse response)throws Exception{

		String type = request.getParameter("type");
		String id=request.getParameter("id");
		int i = Integer.parseInt(id);
		log.info("WxNoticeController.getDetail-------------type:"+type+"id:"+id);

		if(type.equals("APP_NIOTICE_AUDIT")){
			return getAppDetail(request, response);
		}else if(type.equals("SMS_MESSAGE_AUDIT")){
			PushSendDto dto=pushSendService.getDetailInfo(Integer.parseInt(id),1);
			return AppResultUtil.createSuccesDto(dto);
		}else if(type.equals("EMAIL_MESSAGE_AUDIT")){
			PushSendDto dto=pushSendService.getDetailInfo(Integer.parseInt(id),2);
			return AppResultUtil.createSuccesDto(dto);
		}else if(type.equals("WECHAT_MESSAGE_AUDIT")){
			return getWxDetail(request, response);
		}
		return AppResultUtil.createErrorDto("100", "获取详情失败");
	}

	/**
	 * 获取APP公告详情
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getAppDetail")
	@ResponseBody
	public AppResultDto getAppDetail(HttpServletRequest request,HttpServletResponse response)throws Exception{
		try{
			int type=1;
			Integer id = Integer.parseInt(request.getParameter("id"));
			if(StringUtil.isNotEmpty(request.getParameter("sourceType"))){
				type = Integer.parseInt(request.getParameter("sourceType"));
			}
			NoticeDto noticeDto=appNoticeManager.getDetailById(id,type,1);
			//记录当前用户的阅读数
			if(ObjectUtils.allNotNull(noticeDto)){
				articleCensusManager.saveOrUpdate(id, (noticeDto.getOrgId() == null ? noticeDto.getOrgIds() : noticeDto.getOrgId().toString()));
			}

			return AppResultUtil.createSuccesDto(noticeDto);
		}catch(Exception e){
			e.printStackTrace();
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto(AppConstants.GET_NOTICE_DETAIL_ERROR, "查询公告详情失败");
		}
	}



	/**
	 * 获取短信消息详情
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getPhoneDetail")
	@ResponseBody
	public AppResultDto getPhoneDetail(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject json = new JSONObject();
		String id = request.getParameter("id");
		try {
			PhoneMessageModel model = phoneMessageManager.get(Integer.parseInt(id));

			TempSaverDetail tempSaverDetail = new TempSaverDetail();
			tempSaverDetail.setId(model.getId());
			tempSaverDetail.setState(model.getState());
			tempSaverDetail.setContent(model.getContent());
			if(StringUtils.isNotEmpty(model.getCreator())){
				User user=userManager.get(Long.parseLong(model.getCreator()));
				tempSaverDetail.setCreator(user.getFullName());
			}

			SimpleDateFormat sdf= new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			SimpleDateFormat sdfResult= new SimpleDateFormat("M月d日 HH:mm");
	       	 if(model.getCreateTime()!=null){
	       		 tempSaverDetail.setCreateTime(sdfResult.format(model.getCreateTime()));
	       	 }
	       	tempSaverDetail.setApprovalType(model.getApprovalType());
	       	String approvalTypeName="";
			if(null != model.getApprovalType() && 0 != model.getApprovalType().intValue()){
				NoticeApprovalTypeModel typeModel=noticeApprovalsetManager.findById(model.getApprovalType());
				if(null != typeModel){
					approvalTypeName=typeModel.getName();
				}
			}
			tempSaverDetail.setApprovalTypeName(approvalTypeName);
	       	 List<AuditDto> auditList=new ArrayList<AuditDto>();
	       	 if(null != model.getApprovalType() && 0 != model.getApprovalType().intValue()){
	       		auditList=noticeApprovalsetManager.getAuditList(model.getOrgId(), CodeConstants.ORDER_TYPE_MESSAGE, model.getId());
	       	 }else{
	       		 if(null != model.getApproval_time()){
	       			AuditDto auditDto=new AuditDto();
					auditDto.setApprovalOpinion("");
					if(null !=model.getState() && 1 == model.getState().intValue()){
						auditDto.setApprovalResult(1);
					}else{
						auditDto.setApprovalResult(2);
					}
					auditDto.setApprovalTime(DateHelper.formatDate(model.getApproval_time(), DateHelper.DATE_TIME_STRING));
					auditDto.setApprovalUser(model.getApproval_user());
					auditList.add(auditDto);
	       		 }
	       	 }
	       	tempSaverDetail.setAuditList(auditList);
			return AppResultUtil.createSuccesDto(AppConstants.SUCCESS_CODE, tempSaverDetail);
		} catch (Exception e) {
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto(AppConstants.RESULTCODE_ILLEGAL, e.getMessage());
		}

	}


	/**
	 * 获取邮件消息详情
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getEmailDetail")
	public AppResultDto getEmailDetail(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject json = new JSONObject();
		String id = request.getParameter("id");
		try {
			EmailSendModel model = emailSendManager.get(Integer.parseInt(id));
			EmailConfigModel emailConfigModel = emailConfigManager.get(model.getEmailaccount_id());


			TempSaverDetail tempSaverDetail = new TempSaverDetail();
			tempSaverDetail.setId(model.getId());
			tempSaverDetail.setRecipient_email(model.getRecipient_email());
			tempSaverDetail.setState(model.getState());
			tempSaverDetail.setAttach_ment(model.getAttach_ment());
			if(StringUtils.isNotEmpty(model.getCreator())){
				User user=userManager.get(Long.parseLong(model.getCreator()));
				tempSaverDetail.setCreator(user.getFullName());
			}
			tempSaverDetail.setTotal(model.getRecipient_email().split(";").length);
			tempSaverDetail.setEmail_user(emailConfigModel.getEmail_address());
			tempSaverDetail.setContent(model.getEmail_centent());
			String approvalTypeName="";
			if(null != model.getApprovalType() && 0 != model.getApprovalType().intValue()){
				NoticeApprovalTypeModel typeModel=noticeApprovalsetManager.findById(model.getApprovalType());
				if(null != typeModel){
					approvalTypeName=typeModel.getName();
				}
			}
			tempSaverDetail.setApprovalTypeName(approvalTypeName);
			tempSaverDetail.setApprovalType(model.getApprovalType());
	       	 List<AuditDto> auditList=new ArrayList<AuditDto>();
	       	 if(null != model.getApprovalType() && 0 != model.getApprovalType().intValue()){
	       		auditList=noticeApprovalsetManager.getAuditList(model.getOrgId(), CodeConstants.ORDER_TYPE_EMAIL, model.getId());
	       	 }else{
	       		 if(null != model.getApproval_time()){
	       			AuditDto auditDto=new AuditDto();
					auditDto.setApprovalOpinion("");
					if(null !=model.getState() && 1 == model.getState().intValue()){
						auditDto.setApprovalResult(1);
					}else{
						auditDto.setApprovalResult(2);
					}
					auditDto.setApprovalTime(DateHelper.formatDate(model.getApproval_time(), DateHelper.DATE_TIME_STRING));
					auditDto.setApprovalUser(model.getApproval_user());
					auditList.add(auditDto);
	       		 }
	       	 }
	       	tempSaverDetail.setAuditList(auditList);
			return AppResultUtil.createSuccesDto(AppConstants.SUCCESS_CODE, tempSaverDetail);
		} catch (Exception e) {
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto(AppConstants.RESULTCODE_ILLEGAL, e.getMessage());
		}

	}


	/**
	 * 获取模板消息详情
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getWxDetail")
	public  AppResultDto getWxDetail(HttpServletRequest request,HttpServletResponse response)throws Exception{
		JSONObject json=new JSONObject();

		//审核id
		String id=request.getParameter("id");

		try{
			//审核表
			WxtemplateMessageModel model=wxtemplateMessageManager.get(Integer.parseInt(id));
//			if(!model.getIsEnabled().equals("1")){
//				return AppResultUtil.createErrorDto(AppConstants.GET_WC_DETAIL_ERROR,"已经被删除");
//			}
			//配置表
//			List<WxtemplateMessageConfigModel> configList = wxtemplateMessageConfigManager.getWxTemplConfigByTypeId(model.getWechat_template_id());
			List<WxtemplateConfigPara> configList = wxtemplateConfigParaManager.getWxTemplConfigByTypeId(Integer.parseInt(id));
			//公众号
			WxtemplateMessageTypeModel typeModel = wxTypeManager.get(model.getWechat_template_id());

			WxPublicno wxPublicno = wxPubManager.get(typeModel.getWechat_account_id());

			//Page page2 = wxtemplateMessageManager.getWxPublicByWxTableId(Integer.parseInt(id));
			//TemplateLibrary templateLibrary = templateLibraryManager.get(model.getWechat_template_id());


			TempSaverDetail tempSaverDetail = new TempSaverDetail();

			tempSaverDetail.setId(model.getId());
			tempSaverDetail.setWechat_name(wxPublicno.getName());
			tempSaverDetail.setState(model.getState());
			if(StringUtils.isNotEmpty(model.getCreator())){
				User user=userManager.get(Long.parseLong(model.getCreator()));
				tempSaverDetail.setCreator(user.getFullName());
			}
			tempSaverDetail.setTitle(model.getTitle());
			tempSaverDetail.setParaList(configList);


			SimpleDateFormat sdf= new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			SimpleDateFormat sdfResult= new SimpleDateFormat("M月d日 HH:mm");
	       	 if(model.getCreateTime()!=null){
	       		 tempSaverDetail.setCreateTime(sdfResult.format(model.getCreateTime()));
	       	 }
	       	tempSaverDetail.setUrl(model.getUrl());
	       	
	       	tempSaverDetail.setApprovalType(model.getApprovalType());
	       	String approvalTypeName="";
			if(null != model.getApprovalType() && 0 != model.getApprovalType().intValue()){
				NoticeApprovalTypeModel approvalTypeModel=noticeApprovalsetManager.findById(model.getApprovalType());
				if(null != approvalTypeModel){
					approvalTypeName=approvalTypeModel.getName();
				}
			}
			tempSaverDetail.setApprovalTypeName(approvalTypeName);
	      	 List<AuditDto> auditList=new ArrayList<AuditDto>();
	      	 if(null != model.getApprovalType() && 0 != model.getApprovalType().intValue()){
	      		auditList=noticeApprovalsetManager.getAuditList(model.getOrgId(), CodeConstants.ORDER_TYPE_TEMPLE, model.getId());
	      	 }else{
	      		 if(null != model.getApproval_time()){
	      			AuditDto auditDto=new AuditDto();
					auditDto.setApprovalOpinion("");
					if(null !=model.getState() && 1 == model.getState().intValue()){
						auditDto.setApprovalResult(1);
					}else{
						auditDto.setApprovalResult(2);
					}
					auditDto.setApprovalTime(DateHelper.formatDate(model.getApproval_time(), DateHelper.DATE_TIME_STRING));
					auditDto.setApprovalUser(model.getApproval_user());
					auditList.add(auditDto);
	      		 }
	      	 }
	      	tempSaverDetail.setAuditList(auditList);
			return AppResultUtil.createSuccesDto(AppConstants.SUCCESS_CODE, tempSaverDetail);
		}catch(Exception e){
			e.printStackTrace();
			return AppResultUtil.createErrorDto(AppConstants.PARAM_ERROR,"参数错误");
		}

	}


	/**
	 * 公告审核
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/approval")
	@ResponseBody
	public AppResultDto approval(HttpServletRequest request,HttpServletResponse response,PushSendDto dto)throws Exception{
		String types = request.getParameter("types");
		String token=request.getParameter("token");
		if(!StringUtil.isNotEmpty(token)){
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		String userName = baseRedisService.get(token.trim());
		if(userName == null) {
			AppResultDto rt = AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
   		 	return rt;
		}
		if(types.equals("APP_NIOTICE_AUDIT")){
			return approvalAppNoticeNew(request, response);
		}else if(types.equals("SMS_MESSAGE_AUDIT")||types.equals("EMAIL_MESSAGE_AUDIT")){
			dto.setAuditOpinion(request.getParameter("approvalOpinion"));
			return approvalSendNew(request,dto);
		}else if(types.equals("WECHAT_MESSAGE_AUDIT")){
			return approvalWxNoticeNew(request, response);
		}
		return AppResultUtil.createErrorDto("100","审核失败");
	}
	
	
	/**
	 * 审核短信邮件消息-----多级审核
	 *
	 * @param request
	 * @param dto
	 * @return
	 */
	@RequestMapping(value = "/approvalSendNew")
	@ResponseBody
	public AppResultDto approvalSendNew(HttpServletRequest request, PushSendDto dto) {
		String token=request.getParameter("token");
		if(!StringUtil.isNotEmpty(token)){
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		String userName = baseRedisService.get(token.trim());
		if(userName == null) {
			AppResultDto rt = AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
   		 	return rt;
		}
		User user = userManager.getUserByUsername2(userName);
		String auditor = "0";
		if (user != null) {
			auditor = user.getId().toString();
		}
		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", "审核失败:未获取到单据信息");
			}
			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", "审核失败:未获取到单据信息");
			}
			
			codeType=CodeConstants.ORDER_TYPE_EMAIL;
			
			pathUrl = hostUrl + wxEmailAuditUrl.replace("@id", model.getId().toString());
			orgId = model.getOrgId();
			approvalType = model.getApprovalType();
			orderId = model.getId();
		}
		AuditResultVo auditResultVo = null;
		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 resultDto=pushSendService.approvalSend(dto, auditor, carDto, "");
				if(null != auditResultVo && null != auditResultVo.getApprovalModel() && !"200".equals(resultDto.getCode())){
					ApprovalModel approvalModel=auditResultVo.getApprovalModel();
					approvalModel.setEnabled(0);
					approvalModel.setModifier(Integer.parseInt(user.getId().toString()));
					approvalModel.setModifTime(new Date());
					noticeApprovalsetManager.updateApproval(approvalModel);
				}
				return resultDto;
			}
			
			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();
	}
	
	
	
	/**
	 * 审核APP公告-----多级审核
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/approvalAppNoticeNew")
	public AppResultDto approvalAppNoticeNew(HttpServletRequest request, HttpServletResponse response) throws Exception {
		log.info("WxNoticeController.approvalAppNoticeNew()");
		String id        = request.getParameter("id");
		String state     = request.getParameter("state");//1通过2不通过
		String approvalOpinion     = request.getParameter("approvalOpinion");
		String userName = baseRedisService.get(request.getParameter("token"));
		if(userName == null) {
			AppResultDto rt = AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
   		 	return rt;
		}
		User user = userManager.getUserByUsername2(userName);
		try {
			AppNoticeModel appNotice = appNoticeManager.get(Integer.parseInt(id));
			if(null == appNotice){
				return AppResultUtil.createErrorDto("500", "未获取到公告订单");
			}
			int approvalResult=Integer.parseInt(state);
			
			AuditResultVo auditResultVo = new AuditResultVo();
			int haveNext=0;
			if(null != appNotice.getApprovalType() && 0 != appNotice.getApprovalType().intValue()){
				AuditInfoDto dto=new AuditInfoDto(appNotice.getOrgId(),CodeConstants.ORDER_TYPE_NOTICE,appNotice.getId(),
						appNotice.getApprovalType(),Integer.parseInt(user.getId().toString()), userName,
						approvalResult,approvalOpinion);
				auditResultVo=noticeApprovalsetManager.saveAuditInfo(dto);
				haveNext=auditResultVo.getHaveNext();
			}
			if(2 == approvalResult || 0 == haveNext){
				Map<String, Object> resMap = noticePublicnoService.approvalAppNotice(appNotice,request, user, 2);
				if (200 != Integer.parseInt(resMap.get("code").toString())) {
					if(null != auditResultVo && null != auditResultVo.getApprovalModel()){
						ApprovalModel approvalModel=auditResultVo.getApprovalModel();
						approvalModel.setEnabled(0);
						approvalModel.setModifier(Integer.parseInt(user.getId().toString()));
						approvalModel.setModifTime(new Date());
						noticeApprovalsetManager.updateApproval(approvalModel);
					}
					return AppResultUtil.createErrorDto("500", "发布公告失败:"+ resMap.get("msgStr"));
				} else {
					if(1 == approvalResult){
						//审核通过
						log.info("记录通知消息--------------------------------------");
						noticePublicnoService.saveNoticeRecord(appNotice);
					}
					if(null != appNotice.getOrgId() && null != appNotice.getIsPushTemplate() && 1 == appNotice.getIsPushTemplate().intValue()){
						log.info("APP进入发布公告模板推送--------------------------------------");
						String url=appNotice.getUrl_address();
						if(-1 == url.indexOf("http")){
							url="http:"+url;
						}
						if(1 == approvalResult){
							//推送模板消息给所有粉丝
							String res=sendWxTempMsg(appNotice,url);
							log.info("发布公告-模板消息:{}",res);
							if(StringUtils.isNotEmpty(res)){
								return AppResultUtil.createErrorDto("400", "发布模板消息失败:"+ res);
							}
						}
					}

					return AppResultUtil.createSuccesDto(resMap.get("data"));
				}
			}else{
				//推送消息给下一级审核人
				String pathUrl = hostUrl + wxAppNoticeUrl.replace("@id", appNotice.getId().toString()) + "&sourceType=1&isApproval=1&approvalType="+appNotice.getApprovalType();
				List<User> users=noticePublicnoService.getPushMsgUserById(appNotice.getApprovalType(), appNotice.getOrgId(), CodeConstants.ORDER_TYPE_NOTICE, appNotice.getId());
				if(!CollectionUtils.isEmpty(users)){
					appNoticeManager.pushMessage(Long.parseLong(appNotice.getId().toString()), CodeConstants.APP_NOTICE_PUSH_CODE, pathUrl, "您有新的待审核公告资讯，请及时审核！", "有新app公告待审核", users);
				}
			}
			return AppResultUtil.createSuccesDto();
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("500", "发布公告失败:"+ e.getMessage());
		}

	}
	
	private String sendWxTempMsg(AppNoticeModel appNotice,String url){
		Map<String,Object> map=noticePublicnoService.getSentWxTempMsg(appNotice);
		if (200 != Integer.parseInt(map.get("code").toString())){
			return map.get("msg").toString();
		}
		List<NoticeWxTempVo> list=(List<NoticeWxTempVo>)map.get("data");
		
		String content="";
		if(StringUtil.isNotEmpty(appNotice.getTitle())){
			content="新发布了公告《"+appNotice.getTitle()+"》,请注意查看！";
		}else{
			content="新发布了公告,请注意查看！";
		}
		//推送模板消息给所有粉丝
		noticePublicnoService.sendTemplateMsgByWxUser(list,url,content);
		return "";
	}
	
//
//
//
//	/**
//	 * 审核APP公告
//
//	 * @param request
//	 * @param response
//	 * @return
//	 * @throws Exception
//	 */
//	@RequestMapping(value = "/approvalAppNotice")
//	@ResponseBody
//	public AppResultDto approvalAppNotice(HttpServletRequest request,HttpServletResponse response)throws Exception{
//		try {
////			User user = (User) request.getSession().getAttribute("UserCache");
//			String id        = request.getParameter("id");
//			String state     = request.getParameter("state");
//			String userName = baseRedisService.get(request.getParameter("token"));
//			if(userName == null) {
//				AppResultDto rt = AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
//	   		 	return rt;
//			}
//			User user = userManager.getUserByUsername2(userName);
//			AppNoticeModel appNotice = appNoticeManager.get(Integer.parseInt(id));
//			if(null == appNotice){
//				return AppResultUtil.createErrorDto("500", "未获取到公告订单");
//			}
//			Map<String, Object> resMap=noticePublicnoService.approvalAppNotice(appNotice,request, user, 2);
//			if(200!=Integer.parseInt(resMap.get("code").toString())){
//				AppResultDto rt = AppResultUtil.createErrorDto("500", "发布失败");
//	   		 	return rt;
//			}else{
//				AppResultDto rt = AppResultUtil.createSuccesDto(resMap.get("data"));
//	   		 	return rt;
//			}
//
//		}catch(Exception e){
//			return AppResultUtil.createErrorDto("500", "发布失败："+e.getMessage());
//		}
//	}

//
//
//	/**
//	 * 审核短信消息
//	 *
//	 * @param request
//	 * @param response
//	 * @return
//	 * @throws Exception
//	 */
//	@RequestMapping(value = "/approvalPhoneNotice")
//	public AppResultDto approvalPhoneNotice(HttpServletRequest request, HttpServletResponse response) throws Exception {
//		JSONObject json = new JSONObject();
//		try {
////			String userName = baseRedisService.get(request.getHeader("token"));
//			String userName = baseRedisService.get(request.getParameter("token"));
//			int msgCost=0;
//			int total=0;
//			String id = request.getParameter("id");
//			String state = request.getParameter("state");// 未审核-0、已发布-1、已驳回-2
//			if (StringUtils.isNotEmpty(id)) {
//				PhoneMessageModel phoneMessage = phoneMessageManager.get(Integer.parseInt(id));
//				String userId=phoneMessage.getCreator();
//				phoneMessage.setApproval_user(userName);
//				phoneMessage.setApproval_time((new Date()));
//				phoneMessage.setState(Integer.parseInt(state));
//				String[] phones = phoneMessage.getPhones().split(",");
//				total=phones.length;
//				phoneMessage.setTotal(total);
//				phoneMessageManager.updateModel(phoneMessage);
//				String pathUrl=hostUrl+wxMsgUrl.replace("@id", id);
//				List<User> users = new ArrayList<User>();
//				User user1 = userManager.get(Long.parseLong(userId));
//				users.add(user1);
//				if (phoneMessage.getState() == 1) {
//					smsAuthCodeManager.smsSend(phoneMessage.getPhones(), phoneMessage.getContent());
//					PhoneMessageModel phoneMessageModel = phoneMessageManager.get(Integer.parseInt(id));
//					phoneMessageModel.setMsgCost(msgCost);
//					phoneMessageManager.updateModel(phoneMessageModel);
////					emailSendManager.sendMessegWithUrl(id, userId, "3", "审核通过",pathUrl);
//					appNoticeManager.pushMessage(Long.parseLong(id), CodeConstants.MESSAGE_PUSH_CODE,pathUrl, "您发起的短信消息已审核通过","已审核通过", users);
//					return AppResultUtil.createErrorDto(AppConstants.SUCCESS_CODE,"短信发送成功,发送总数:"+total+",发送成功总数:"+msgCost);
//				}else if(phoneMessage.getState() == 0){
//					phoneMessageManager.updateModel(phoneMessage);
//					return AppResultUtil.createErrorDto(AppConstants.SUCCESS_CODE,"未通过审核");
//				}else if(phoneMessage.getState() == 2){
//					phoneMessageManager.updateModel(phoneMessage);
////					emailSendManager.sendMessegWithUrl(id, userId, "3", "被驳回",pathUrl);
//					appNoticeManager.pushMessage(Long.parseLong(id), CodeConstants.MESSAGE_PUSH_CODE,pathUrl, "您发起的短信消息已被驳回","未审核通过", users);
//					return AppResultUtil.createErrorDto(AppConstants.SUCCESS_CODE,"已驳回");
//				}else{
//					return AppResultUtil.createErrorDto(AppConstants.PARAM_ERROR,"参数错误");
//				}
//			} else{
//				return AppResultUtil.createErrorDto(AppConstants.PARAM_ERROR,"参数错误");
//			}
//
//		} catch (Exception e) {
//			e.printStackTrace();
//			return AppResultUtil.createErrorDto(AppConstants.PARAM_ERROR,e.getMessage());
//		}
//
//	}
//
//
//
//	/**
//	 * 审核邮件信息
//	 *
//	 * @param request
//	 * @param response
//	 * @return
//	 * @throws Exception
//	 */
//	@RequestMapping(value = "/approvalEmailNotice")
//	public AppResultDto approvalEmailNotice(HttpServletRequest request, HttpServletResponse response) throws Exception {
//		JSONObject json = new JSONObject();
//		try {
////			String userName = baseRedisService.get(request.getHeader("token"));
//			String userName = baseRedisService.get(request.getParameter("token"));
//
//			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));
//				String userId=emailSend.getCreator();
//				List<User> users = new ArrayList<User>();
//				User user1 = userManager.get(Long.parseLong(userId));
//				users.add(user1);
//				emailSend.setApproval_user(userName);
//				emailSend.setApproval_time((new Date()));
//				emailSend.setState(Integer.parseInt(state));
//				emailSend.setSend_time(new Date());
//
//				emailSend.setTotal(emailSend.getRecipient_email().split(";").length);
////				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=addr.substring(addr.lastIndexOf("/")+1);
//								System.out.println(fileName);
//								helper.addAttachment(fileName, new File(rootPath+"/"+fileName));
//							}
//						}
//					}
//
//					senderImpl.send(mail);
//					emailSendManager.updateModel(emailSend);
////					emailSendManager.sendMessegWithUrl(id, userId, "4", "被驳回",pathUrl);
//					appNoticeManager.pushMessage(Long.parseLong(id), CodeConstants.EMAIL_PUSH_CODE,pathUrl, "您发起的邮箱消息已审核通过","已审核通过", users);
//					return AppResultUtil.createErrorDto(AppConstants.SUCCESS_CODE,"邮件发送成功");
//
//				}else if(emailSend.getState() == 0){
//					emailSendManager.updateModel(emailSend);
//					return AppResultUtil.createErrorDto(AppConstants.SUCCESS_CODE,"未通过审核");
//				}else if(emailSend.getState() == 2){
//					emailSendManager.updateModel(emailSend);
////					emailSendManager.sendMessegWithUrl(id, userId, "4", "被驳回",pathUrl);
//					appNoticeManager.pushMessage(Long.parseLong(id), CodeConstants.EMAIL_PUSH_CODE,pathUrl, "您发起的邮箱消息已被驳回","未审核通过", users);
//					return AppResultUtil.createErrorDto(AppConstants.SUCCESS_CODE,"已驳回");
//				}else{
//					return AppResultUtil.createErrorDto(AppConstants.PARAM_ERROR,"参数错误");
//				}
//			} else{
//				return AppResultUtil.createErrorDto(AppConstants.PARAM_ERROR,"参数错误");
//			}
//
//		} catch (Exception e) {
//			e.printStackTrace();
//			return AppResultUtil.createErrorDto(AppConstants.PARAM_ERROR,e.getMessage());
//		}
//
//	}
	
	
	
	
	/**
	 * 审核微信信息
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unused")
	@RequestMapping(value = "/approvalWxNoticeNew")
	@ResponseBody
	public AppResultDto approvalWxNoticeNew(HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			String userName = baseRedisService.get(request.getParameter("token"));
			if(userName == null) {
				AppResultDto rt = AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
	   		 	return rt;
			}
			User user = userManager.getUserByUsername2(userName);
			String id    = request.getParameter("id");
			String state = request.getParameter("state");
			String approvalOpinion     = request.getParameter("approvalOpinion");
			
			log.info("approvalNew-审核订单:id" + id + ";state:" + state+";approvalOpinion:"+approvalOpinion);
			log.info("approvalNew-操作人:" + userName);
			log.info("approvalNew-审核时间:" + new Date());
			if (StringUtils.isEmpty(id)) {// 更新状态
				return AppResultUtil.createErrorDto("100", "参数异常");
			}
			WxtemplateMessageModel wxSend = wxtemplateMessageManager.get(Integer.parseInt(id));
			if(null == wxSend){
				return AppResultUtil.createErrorDto("100", "参数异常");
			}
			String pathUrl = hostUrl + wxWechatUrl.replace("@id", id.toString());
			int approvalResult=Integer.parseInt(state);
			AuditResultVo auditResultVo = new AuditResultVo();
			int haveNext=0;
			if(null != wxSend.getApprovalType() && 0 != wxSend.getApprovalType().intValue()){
				AuditInfoDto dto=new AuditInfoDto(wxSend.getOrgId(),CodeConstants.ORDER_TYPE_TEMPLE,wxSend.getId(),
						wxSend.getApprovalType(),Integer.parseInt(user.getId().toString()), userName,
						approvalResult,approvalOpinion);
				auditResultVo=noticeApprovalsetManager.saveAuditInfo(dto);
				haveNext=auditResultVo.getHaveNext();
			}
			if(2 == approvalResult || 0 == haveNext){
				AppResultDto dto=approvalNotApprovalTypeOrder(Integer.parseInt(id), wxSend, userName, Integer.parseInt(state),pathUrl);
				if(null != auditResultVo && null != auditResultVo.getApprovalModel() && !"200".equals(dto.getCode())){
					ApprovalModel approvalModel=auditResultVo.getApprovalModel();
					approvalModel.setEnabled(0);
					approvalModel.setModifier(Integer.parseInt(user.getId().toString()));
					approvalModel.setModifTime(new Date());
					noticeApprovalsetManager.updateApproval(approvalModel);
				}
				return dto;
			}else{
				pathUrl=pathUrl+"&isApproval=1&approvalType="+wxSend.getApprovalType();
				//推送消息给下一级审核人
				List<User> users=noticePublicnoService.getPushMsgUserById(wxSend.getApprovalType(), wxSend.getOrgId(), CodeConstants.ORDER_TYPE_TEMPLE, wxSend.getId());
				if(!CollectionUtils.isEmpty(users)){
					appNoticeManager.pushMessage(Long.parseLong(wxSend.getId().toString()), CodeConstants.APP_NOTICE_PUSH_CODE, pathUrl, "您有新的待审核微信模板消息，请及时审核！", "有新微信模板消息待审核", users);
				}
			}
			return AppResultUtil.createSuccesDto();
			
		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "审核异常:"+e.getMessage());
		}
	}
	
	
	
	/**
	 * 发送部分用户
	 * @param wxSend
	 * @param userSize
	 * @param repeat
	 * @param repeatStr
	 * @param total
	 * @param failTotal
	 * @param tem
	 * @param token
	 * @throws KeyManagementException
	 * @throws NoSuchAlgorithmException
	 * @throws NoSuchProviderException
	 * @throws IOException
	 */
	private void sendPartUser(WxtemplateMessageModel wxSend,int userSize,int repeat,StringBuilder repeatStr,int total,int failTotal,TemplateMessage tem,String token) throws KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException, IOException{
		StringBuilder sucUserIds  = new StringBuilder("");
		StringBuilder failUserIds = new StringBuilder("");
		StringBuilder failStr     = new StringBuilder("");//失败原因
		List<AppUser> users       = new ArrayList<>();
		
		String receiveUserIds = wxSend.getReceive_user_id();
		users = appUserManager.getAppUserByIds(receiveUserIds);
		List<String> openIdList = new ArrayList<String>();
		if (null != users && users.size() > 0) {
			userSize = users.size();//选择了所少个用户
			for (AppUser appUser : users) {
				if(StringUtils.isNotEmpty(appUser.getBindOpenid())){
					if (openIdList.contains(appUser.getBindOpenid())) {
						repeat++;
						repeatStr.append(appUser.getBindOpenid() + "已存在;");
					} else {
						openIdList.add(appUser.getBindOpenid());
					}
				}else{
					Integer wxUserId = appUser.getWxUserId();
					if (null != wxUserId && scWxuserManager.exists(wxUserId)) {
						WxUser wxUser = scWxuserManager.get(wxUserId);
						if (null != wxUser && StringUtils.isNotBlank(wxUser.getOpenId())) {
//								openIdSet.add(wxUser.getOpenId());
							if (openIdList.contains(wxUser.getOpenId())) {
								repeat++;
								repeatStr.append(wxUser.getOpenId() + "已存在;");
							} else {
								openIdList.add(wxUser.getOpenId());
							}
						}
					}
				}
			}
		}
		log.info("openIdList:" + JSON.toJSONString(openIdList));
		if (null != openIdList && openIdList.size() > 0) {
			//循环发送
			for (String str : openIdList) {
				tem.setOpenId(str);
				String json2      = tem.toJSON();
				String jsonResult = HttpKit.post(Constants.TEMPLATE_URL.concat(token), json2);
				log.info("审核微信模板消息jsonResult:" + jsonResult);
				Map<String, Object> map = JSON.parseObject(jsonResult, Map.class);
				if (jsonResult != null) {
					if ("0".equals(map.get("errcode").toString())) {
						total++;//发送成功个数
						sucUserIds.append(str + ";");
					} else {
						failTotal++;//发送失败个数
						failStr.append(str + "审核失败原因:" + jsonResult + ";");
						failUserIds.append(str + ";");
					}
				}
			}
		}
	}
	/**
	 * 发送所有用户
	 * @param wxSend
	 * @param userSize
	 * @param repeat
	 * @param repeatStr
	 * @param total
	 * @param failTotal
	 * @param tem
	 * @param token
	 * @param wechatAccount
	 * @param failUserIds
	 * @param sucUserIds
	 * @param failStr
	 * @throws KeyManagementException
	 * @throws NoSuchAlgorithmException
	 * @throws NoSuchProviderException
	 * @throws IOException
	 */
	private void sendAllUser(WxtemplateMessageModel wxSend,int userSize,int repeat,StringBuilder repeatStr,int total,int failTotal,TemplateMessage tem,String token,WxPublicno  wechatAccount,StringBuilder failUserIds,StringBuilder sucUserIds,StringBuilder failStr) throws KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException, IOException{
		Integer orgId = wxSend.getOrgId();
		List<String>              openIdList  = new ArrayList<String>();
		List<Map<String, Object>> orgAllUsers = wxTypeManager.findByOrgIdAndDevelopId(orgId, wechatAccount.getDevelopId());
		log.info("orgAllUsers:" + JSON.toJSONString(orgAllUsers));
		if (null != orgAllUsers && orgAllUsers.size() > 0) {
			for (int i = 0; i < orgAllUsers.size(); i++) {
				Map<String, Object> mapUser = orgAllUsers.get(i);
				String              openId  = mapUser.get("openId") == null ? "" : mapUser.get("openId").toString();
				if (openIdList.contains(openId)) {
					repeat++;
					repeatStr.append(openId + "已存在;");
				} else {
					openIdList.add(openId);
				}
			}
		}

		log.info("openIdList:" + JSON.toJSONString(openIdList));
		if (null != openIdList && openIdList.size() > 0) {
			//循环发送
			for (String str : openIdList) {
				tem.setOpenId(str);
				String json2      = tem.toJSON();
				String jsonResult = HttpKit.post(Constants.TEMPLATE_URL.concat(token), json2);
				log.info("审核微信模板消息jsonResult:" + jsonResult);
				Map<String, Object> map = JSON.parseObject(jsonResult, Map.class);
				if (jsonResult != null) {
					if ("0".equals(map.get("errcode").toString())) {
						total++;//发送成功个数
						sucUserIds.append(str + ";");
					} else {
						failTotal++;//发送失败个数
						failStr.append(str + "审核失败原因:" + jsonResult + ";");
						failUserIds.append(str + ";");
					}
				}
			}
		}
	}
	/**
	 * 审核没有开启审核类型的单据   或最后一步审核
	 * @param id
	 * @param wxSend
	 * @param userName
	 * @param state
	 * @return
	 */
	private AppResultDto approvalNotApprovalTypeOrder(Integer id,WxtemplateMessageModel wxSend,String userName,Integer state,String pathUrl){
		
		//发送成功条数计数器
		int           total     = 0;
		int           failTotal = 0;
		int           userSize  = 0;
		int           repeat    = 0;//重复个数
		StringBuilder repeatStr = new StringBuilder();
		try{
			wxSend.setApproval_user(userName);
			wxSend.setApproval_time((new Date()));
			wxSend.setState(state);
//				wxSend.setSend_time(new Date());
			String     userId   = wxSend.getCreator();
			List<User> userList = new ArrayList<User>();
			User       user2    = userManager.get(Long.parseLong(userId));
			userList.add(user2);
			//审核通过
			if (wxSend.getState() == 1) {
//					发送微信
				//获取消息模板
				//1.获取模板所有配置信息
				List<WxtemplateConfigPara> wxTemplConfigByTypeId = wxtemplateConfigParaManager.getWxTemplConfigByTypeId(wxSend.getId());
				//2.获取推送消息的公众号信息
				WxtemplateMessageTypeModel typeModel     = wxTypeManager.get(wxSend.getWechat_template_id());
				WxPublicno                 wechatAccount = wxPubManager.get(typeModel.getWechat_account_id());
				//3.封装推送信息 tem对象
				TemplateMessage tem = new TemplateMessage();

				tem.setTemplateId(typeModel.getTemplateid());
				//tem.setTopColor("#00DD00");
				tem.setTemplateParamList(wxTemplConfigByTypeId);
//					跳转地址
				tem.setUrl(wxSend.getUrl());

				//4.推送信息操作
				try {
					String token = WeiXinHelper.getToken(wechatAccount.getAppId(), wechatAccount.getAppSecret());
					if (StringUtils.isEmpty(token)) {
						return AppResultUtil.createErrorDto("100", "公众号配置错误或IP未授权");
					}
					StringBuilder sucUserIds  = new StringBuilder("");
					StringBuilder failUserIds = new StringBuilder("");
					StringBuilder failStr     = new StringBuilder("");//失败原因
					if (wxSend.getReceive_type() == 2 || wxSend.getReceive_type() == 3 || wxSend.getReceive_type() == 4) {// 项目部分用户
						if (StringUtils.isBlank(wxSend.getReceive_user_id())){ 
							return AppResultUtil.createErrorDto("100", "未设置发送人");
						}
						sendPartUser(wxSend,userSize,repeat,repeatStr,total,failTotal,tem,token);
					} else if (wxSend.getReceive_type() == 1){// 项目所有用户
						sendAllUser(wxSend,userSize,repeat,repeatStr,total,failTotal,tem,token,wechatAccount,failUserIds,sucUserIds,failStr);
					}

					if (StringUtil.isNotEmpty(failStr.toString())) {
						wxSend.setFail_str(failStr.toString());
					}

					if (failTotal > 0) {
						String msg = "选中用户个数:" + userSize + ";成功个数:" + total + ";失败个数:" + failTotal + ";重复个数:" + repeat;
						wxSend.setTotal(total);
						wxSend.setState(0);
						wxSend.setStatus_str("发送失败:失败个数:" + failTotal + ";重复信息:" + repeatStr.toString());
						if (total > 0) {
							wxSend.setState(1);
							wxSend.setStatus_str("部分成功:" + msg + ";重复信息:" + repeatStr.toString());
						}
						log.info("wxSend:" + JSON.toJSONString(wxSend));
						wxtemplateMessageManager.updateModel(wxSend);
						if (1 == wxSend.getState()) {
							appNoticeManager.pushMessage(Long.parseLong(id.toString()), CodeConstants.WEIXIN_PUSH_CODE, pathUrl, "您发起的微信消息已审核通过", "已审核通过", userList);
						}
						return AppResultUtil.createCommonDto("100", msg,"模板消息发送失败,成功账号:" + sucUserIds.toString() + ";失败账号:" + failUserIds.toString() + ";重复信息:" + repeatStr.toString());
					} else {
						wxSend.setTotal(total);
						wxSend.setStatus_str("发送成功:成功个数:" + total + ";重复个数:" + repeat + ";重复信息:" + repeatStr.toString());
						log.info("wxSend:" + JSON.toJSONString(wxSend));
						wxtemplateMessageManager.updateModel(wxSend);
						appNoticeManager.pushMessage(Long.parseLong(id.toString()), CodeConstants.WEIXIN_PUSH_CODE, pathUrl, "您发起的微信消息已审核通过", "已审核通过", userList);
						return AppResultUtil.createSuccesDto("审核状态-已通过,模板消息全部发送成功");
					}
				} catch (Exception e) {
					wxSend.setTotal(total);
					wxSend.setState(0);
					log.info("wxSend:" + JSON.toJSONString(wxSend));
					wxtemplateMessageManager.updateModel(wxSend);
					e.printStackTrace();
					return AppResultUtil.createErrorDto("100", "审核异常:"+e.getMessage());
				}

			} else if (wxSend.getState() == 0) {
				log.info("wxSend:" + JSON.toJSONString(wxSend));
				wxtemplateMessageManager.updateModel(wxSend);
				return AppResultUtil.createSuccesDto("审核状态-未审核");
				
			} else if (wxSend.getState() == 2) {
				log.info("wxSend:" + JSON.toJSONString(wxSend));
				wxtemplateMessageManager.updateModel(wxSend);
				appNoticeManager.pushMessage(Long.parseLong(id.toString()), CodeConstants.WEIXIN_PUSH_CODE, pathUrl, "您发起的微信消息已被驳回", "未审核通过", userList);
				return AppResultUtil.createSuccesDto("审核状态-已驳回");
			}
		}catch(Exception e){
			e.printStackTrace();
			log.error("审核微信模板失败:"+e.getMessage());
			return AppResultUtil.createErrorDto("100", "审核微信模板失败:"+e.getMessage());
		}
		return AppResultUtil.createErrorDto("100", "审核微信模板失败");
	}
	
	
	


//	/**
//	 * 审核微信模板
//
//	 * @param request
//	 * @param response
//	 * @return
//	 * @throws Exception
//	 */
//	@RequestMapping(value = "/approvalWxNotice")
//	@ResponseBody
//	public AppResultDto approvalWxNotice(HttpServletRequest request,HttpServletResponse response)throws Exception{
//		try {
//			String userName = baseRedisService.get(request.getParameter("token"));
//			//发送成功条数计数器
//			//发送成功条数计数器
//			int total = 0;
//			int failTotal=0;
//			int userSize=0;
//			int repeat=0;//重复个数
//			StringBuilder repeatStr=new StringBuilder();
////			StringBuffer failId = new StringBuffer();
//			if(userName == null) {
//				return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED,"token已过期");
//			}
//			String id = request.getParameter("id");
//			String state = request.getParameter("state");
//			String pathUrl=hostUrl+wxWechatUrl.replace("@id", id);
//			if (StringUtils.isNotEmpty(id)) {// 更新状态
//				//审核表-id ->获取模板   ,  公众号表-wxId
//				WxtemplateMessageModel wxSend = wxtemplateMessageManager.get(Integer.parseInt(id));
//				wxSend.setApproval_user(userName);
//				wxSend.setApproval_time((new Date()));
//				wxSend.setState(Integer.parseInt(state));
//				String userId=wxSend.getCreator();
//				List<User> userList = new ArrayList<User>();
//				User user1 = userManager.get(Long.parseLong(userId));
//				userList.add(user1);
//				if (wxSend.getState() == 1) {
////					发送微信
//					//获取消息模板
//					//1.获取模板所有配置信息
//					List<WxtemplateConfigPara> wxTemplConfigByTypeId = wxtemplateConfigParaManager.getWxTemplConfigByTypeId(wxSend.getId());
//					//2.获取推送消息的公众号信息
//					WxtemplateMessageTypeModel typeModel = wxTypeManager.get(wxSend.getWechat_template_id());
//					WxPublicno wechatAccount = wxPubManager.get(typeModel.getWechat_account_id());
//					//3.封装推送信息 tem对象
//					TemplateMessage tem = new TemplateMessage();
//
//					tem.setTemplateId(typeModel.getTemplateid());
//					tem.setTemplateParamList(wxTemplConfigByTypeId);
////					跳转地址
//					tem.setUrl(wxSend.getUrl());
//
//					//4.推送信息操作
//					try {
//						String token = WeiXinHelper.getToken(wechatAccount.getAppId(), wechatAccount.getAppSecret());
//						if (StringUtils.isEmpty(token)) {
//							return AppResultUtil.createErrorDto(AppConstants.WECHAT_SEND_ERROR,"公众号配置错误或IP未授权");
//						}
//						StringBuilder sucUserIds=new StringBuilder("");
//						StringBuilder failUserIds=new StringBuilder("");
//						StringBuilder failStr=new StringBuilder("");//失败原因
//						List<AppUser> users = new ArrayList<>();
//						if (wxSend.getReceive_type() == 2||wxSend.getReceive_type() == 3) {
//							// 项目部分用户
//							if (StringUtils.isBlank(wxSend.getReceive_user_id())){
//								return AppResultUtil.createErrorDto(AppConstants.WECHAT_SEND_ERROR,"发送用户不能为空");
//							}
//							String receiveUserIds = wxSend.getReceive_user_id();
//							users = appUserManager.getAppUserByIds(receiveUserIds);
//							List<String> openIdList=new ArrayList<String>();
//							if(null!=users&&users.size()>0){
//								userSize=users.size();//选择了所少个用户
//								for (AppUser appUser : users) {
//									Integer wxUserId = appUser.getWxUserId();
//									if (null != wxUserId&&scWxuserManager.exists(wxUserId)) {
//										WxUser wxUser = scWxuserManager.get(wxUserId);
//										if (null != wxUser && StringUtils.isNotBlank(wxUser.getOpenId())) {
////											openIdSet.add(wxUser.getOpenId());
//											if(openIdList.contains(wxUser.getOpenId())){
//												repeat++;
//												repeatStr.append(wxUser.getOpenId()+"已存在;");
//											}else{
//												openIdList.add(wxUser.getOpenId());
//											}
//										}
//									}
//								}
//							}
//							if(null!=openIdList&&openIdList.size()>0){
//								//循环发送
//								 for (String str : openIdList) {
//									 tem.setOpenId(str);
//									 String json2 = tem.toJSON();
//									String jsonResult = HttpKit.post(Constants.TEMPLATE_URL.concat(token), json2);
//									LOG.info("审核微信模板消息jsonResult:" + jsonResult);
//									Map<String, Object> map = JSON.parseObject(jsonResult, Map.class);
//									if (jsonResult != null) {
//										if ("0".equals(map.get("errcode").toString())) {
//											total++;//发送成功个数
//											sucUserIds.append(str+";");
//										} else {
//											failTotal++;//发送失败个数
//											failStr.append(str+"审核失败原因:"+jsonResult+";");
//											failUserIds.append(str+";");
//										}
//									}
//							     }
//							}
//						} else {
//							// 项目所有用户
//							Integer orgId = wxSend.getOrgId();
//							List<String> openIdList=new ArrayList<String>();
//							List<Map<String,Object>> orgAllUsers=wxTypeManager.findByOrgIdAndDevelopId(orgId, wechatAccount.getDevelopId());
//							 LOG.info("orgAllUsers:"+JSON.toJSONString(orgAllUsers));
//							 if(null!=orgAllUsers&&orgAllUsers.size()>0){
//								 for(int i=0;i<orgAllUsers.size();i++){
//									 Map<String,Object> mapUser=orgAllUsers.get(i);
//									 String openId=mapUser.get("openId")==null?"":mapUser.get("openId").toString();
//									 if(openIdList.contains(openId)){
//											repeat++;
//											repeatStr.append(openId+"已存在;");
//										}else{
//											openIdList.add(openId);
//										}
//								 }
//							 }
//
//							 if(null!=openIdList&&openIdList.size()>0){
//									//循环发送
//									 for (String str : openIdList) {
//										 tem.setOpenId(str);
//										 String json2 = tem.toJSON();
//										String jsonResult = HttpKit.post(Constants.TEMPLATE_URL.concat(token), json2);
//										LOG.info("审核微信模板消息jsonResult:" + jsonResult);
//										Map<String, Object> map = JSON.parseObject(jsonResult, Map.class);
//										if (jsonResult != null) {
//											if ("0".equals(map.get("errcode").toString())) {
//												total++;//发送成功个数
//												sucUserIds.append(str+";");
//											} else {
//												failTotal++;//发送失败个数
//												failStr.append(str+"审核失败原因:"+jsonResult+";");
//												failUserIds.append(str+";");
//											}
//										}
//								     }
//								}
//						}
//
//						if(StringUtil.isNotEmpty(failStr.toString())){
//							wxSend.setFail_str(failStr.toString());
//						}
//
//						if(failTotal>0){
//							String msg= "选中用户个数:"+userSize+";成功个数:"+total+";失败个数:"+failTotal+";重复个数:"+repeat;
//							wxSend.setTotal(total);
//							wxSend.setState(0);
//							wxSend.setStatus_str("发送失败:失败个数:"+failTotal+";重复信息:"+repeatStr.toString());
//							if(total>0){
//								wxSend.setState(1);
//								wxSend.setStatus_str("部分成功:"+msg+";重复信息:"+repeatStr.toString());
//							}
//							wxtemplateMessageManager.updateModel(wxSend);
////							json.put("code", "1");
////							json.put("msg", msg);
////							json.put("data", "模板消息发送失败,成功账号:" + sucUserIds.toString()+";失败账号:"+failUserIds.toString());
////							StringUtil.charSet(json, request, response);
//							if(1==wxSend.getState()){
//								appNoticeManager.pushMessage(Long.parseLong(id), CodeConstants.WEIXIN_PUSH_CODE, pathUrl, "您发起的微信消息已审核通过", "已审核通过", userList);
//							}
//							return AppResultUtil.createSuccesDto("模板消息发送失败,成功账号:" + sucUserIds.toString()+";失败账号:"+failUserIds.toString(),null);
//						}else{
//							wxSend.setTotal(total);
//							wxSend.setStatus_str("发送成功:成功个数:"+total+";重复个数:"+repeat+";重复信息:"+repeatStr.toString());
//							wxtemplateMessageManager.updateModel(wxSend);
////							json.put("code", "200");
////							json.put("msg", "success");
////							json.put("data", "审核状态-已通过,模板消息全部发送成功");
////							StringUtil.charSet(json, request, response);
//							appNoticeManager.pushMessage(Long.parseLong(id), CodeConstants.WEIXIN_PUSH_CODE, pathUrl, "您发起的微信消息已审核通过", "已审核通过", userList);
//							return AppResultUtil.createSuccesDto( "审核状态-已通过,模板消息全部发送成功",null);
//						}
//					} catch (Exception e) {
//						wxSend.setTotal(total);
//						wxSend.setState(0);
//						wxtemplateMessageManager.updateModel(wxSend);
////						json.put("code", "1");
////						json.put("msg", "fail");
////						json.put("data", e.getMessage());
//						e.printStackTrace();
////						StringUtil.charSet(json, request, response);
//						return AppResultUtil.createErrorDto(AppConstants.WECHAT_SEND_ERROR,e.getMessage());
//					}
//
//				} else if (wxSend.getState() == 0) {
//					wxtemplateMessageManager.updateModel(wxSend);
////					json.put("code", "200");
////					json.put("msg", "success");
////					json.put("data", "审核状态-未审核");
////					StringUtil.charSet(json, request, response);
//					return AppResultUtil.createSuccesDto( "发布成功","审核状态-未审核");
//				} else if (wxSend.getState() == 2) {
//					wxtemplateMessageManager.updateModel(wxSend);
////					json.put("code", "200");
////					json.put("msg", "success");
////					json.put("data", "审核状态-已驳回");
////					StringUtil.charSet(json, request, response);
////						emailSendManager.sendMesseg(id, userId, "2", "被驳回");
//					appNoticeManager.pushMessage(Long.parseLong(id), CodeConstants.WEIXIN_PUSH_CODE, pathUrl, "您发起的微信消息已被驳回", "未审核通过", userList);
//					return AppResultUtil.createSuccesDto( "发布成功","审核状态-已驳回");
//				}
//
//			}else{
//				return AppResultUtil.createErrorDto(AppConstants.PARAM_ERROR,"参数错误,该id没有审核信息");
//			}
//		}catch (Exception e) {
//			e.printStackTrace();
//			return AppResultUtil.createErrorDto(AppConstants.PARAM_ERROR,e.getMessage());
//		}
//		return AppResultUtil.createErrorDto(AppConstants.PARAM_ERROR,"参数错误");
//	}


	/**
	 *
	 * @param request
	 * @return
	 * 微信端公众号获取banner图列表
	 */
	@RequestMapping(value="/bannerList")
	@ResponseBody
	public AppResultDto bannerList(HttpServletRequest request) {
		//微信端banner图列表
		String openId = request.getParameter("openId");
		String orgId  = request.getParameter("orgId");
		String noticeTypeStr=request.getParameter("noticeType");
		WxUser wxUser = scWxuserManager.getScWxuserByOpenId(openId);

		try {
			//noticeType:1公告、2banner图  positionType:1-app端 2-微信 5楼闪送banner
			int noticeType=2;
			if(org.apache.commons.lang3.StringUtils.isNotEmpty(noticeTypeStr)){
				noticeType=Integer.valueOf(noticeTypeStr);//默认2
			}
			String positionType = "2,4";//展示位置 0-微信+app端/1-app端/2-微信/3-公众号/4-微信+公众号/5-app+公众号/6-微信+app+公众号
			String orgIdParams  = orgId;

			if (StringUtils.isBlank(orgIdParams) || "0".equals(orgIdParams) || "null".equals(orgIdParams)) {
				orgIdParams = wxUser.getOrganizationId() + "";
			}
			/**
			 * 判断orgId 字符串是否可以转化为int
			 * 转化异常 存在sql注入
			 */
			Integer.parseInt(orgIdParams);

			return AppResultUtil.createSuccesDto(appNoticeManager.finByType(noticeType, positionType, orgIdParams));
		} catch (Exception e) {
			log.info("WxNoticeController bannerList Error ==========>:" + e.getMessage());
			return AppResultUtil.createErrorDto(AppConstants.GET_BANNER_DETAIL_ERROR, "查询banner列表失败");
		}
	}

	/**
	 * 分页
	 * 微信端公众号获取新闻资讯列表
	 * @return
	 */
	@RequestMapping(value="/noticeList")
	@ResponseBody
	public AppResultDto noticeList(HttpServletRequest request,HttpServletResponse response){
		try {
			String openId=request.getParameter("openId");
			WxUser wxUser=scWxuserManager.getScWxuserByOpenId(openId);

			String pageNo =request.getParameter("pageNo");
			String pageSize = request.getParameter("pageSize");
			String orgId=request.getParameter("orgId");
			HashMap<String, Object> map = new HashMap<String,Object>();
			if(StringUtils.isEmpty(pageNo)){
				pageNo="1";
			}
			if(StringUtils.isEmpty(pageSize)){
				pageSize="10";
			}
			//noticeType:1公告、2banner图  positionType:展示位置 0-微信+app端/1-app端/2-微信/3-公众号/4-微信+公众号/5-app+公众号/6-微信+app+公众号
			map.put("noticeType",1);
			map.put("positionType","2,4,6");
			//查询审核通过的通告列表
			map.put("state",1);
			map.put("type",5);//app公告咨询
			if (wxUser != null && null != wxUser.getOrganizationId()){
				map.put("orgIds",wxUser.getOrganizationId());
			}
			if(StringUtils.isNotEmpty(orgId)){
				int i = Integer.parseInt(orgId);
				map.put("orgIds",orgId);
			}
			Page page=appNoticeManager.getNewDataList(map,Integer.parseInt(pageNo),Integer.parseInt(pageSize));
			
			int isViews=0;
			if(StringUtils.isNotEmpty(orgId)){
				Map<String,Object> setMap=noticeApprovalsetManager.getSetByOrgId(Integer.parseInt(orgId));
				log.info("noticeList-setMap:{}",JsonUtils.toJson(setMap));
				if(null != setMap && setMap.containsKey("isViews") && null != setMap.get("isViews") && StringUtils.isNotEmpty(setMap.get("isViews").toString()) && 1 == Integer.parseInt(setMap.get("isViews").toString()) ){
					isViews=1;
				}
			}

			if(page !=null && page.getItems() !=null) {
				List<Map<String, Object>> appNoticeModels = page.getItems();
				if (appNoticeModels != null && appNoticeModels.size() > 0) {
					List<Map<String, Object>> resultList = new ArrayList<>();
					for (Map<String, Object> appNotice :
							appNoticeModels) {
						//String dayInfo = DateUtil.getDateTime("yyyy", new Date());
						Map<String, Object> param = new HashMap<>();
						//param.put("dayInfo", dayInfo);
						param.put("orgId", orgId);
						param.put("artId", appNotice.get("id"));
						Integer count = articleCensusManager.getTotal(param);
						appNotice.put("readCount", count == null ? 0 : count);
						
						long views=0;
						String key=CodeConstants.NOTICE_REDIS_TYPE_ORDERID+1+"_"+appNotice.get("noticeId");
						String value=baseRedisService.get(key);
						if(StringUtils.isNotEmpty(value)){
							views=Long.parseLong(value);
						}
						appNotice.put("views", views);
						appNotice.put("isViews", isViews);
						resultList.add(appNotice);
					}
					page.setItems(resultList);
				}
			}

			return AppResultUtil.createSuccesDto(AppConstants.SUCCESS_CODE, page);
		}catch(Exception e ) {
			log.info("WxNoticeController noticeList Error ==========>:" + e.getMessage());
			return AppResultUtil.createErrorDto(AppConstants.GET_BANNER_DETAIL_ERROR, "查询公告notice列表失败");
		}
	}

	/**
	 * 微信端公众号获取商圈发现界面banner图列表
	 *
	 * @return
	 */
	@RequestMapping(value = "discoverBannerList")
	@ResponseBody
	public AppResultDto discoverBannerList(HttpServletRequest request,HttpServletResponse response){

		//商圈/发现 界面banner图列表不区分项目与公众号
		try {
			//noticeType:1公告、2banner图、4商圈发现banner  positionType:1-app端 2-微信
			String positionType="2,4";//展示位置 0-微信+app端/1-app端/2-微信/3-公众号/4-微信+公众号/5-app+公众号/6-微信+app+公众号
			return AppResultUtil.createSuccesDto(appNoticeManager.finByType(4,positionType,""));
		}catch(Exception e ) {
			log.info("WxNoticeController discoverBannerList Error ==========>:" + e.getMessage());
			return AppResultUtil.createErrorDto(AppConstants.GET_BANNER_DETAIL_ERROR, "查询banner列表失败");
		}
	}

	@RequestMapping(value = "/getUserEmail")
	public void getUserEmail(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject json = new JSONObject();
		String orgIds=request.getParameter("orgId");
		try {
			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);
		}

	}
}
