package com.palmnest.service.notice.service.impl;

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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.AppConstants;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.core.util.*;
import com.palmnest.application.dto.*;
import com.palmnest.application.dto.input.AppNoticeDetailDto;
import com.palmnest.application.dto.output.NoticeUserOutDto;
import com.palmnest.application.dto.output.WxUserDto;
import com.palmnest.model.User;
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.model.property.VirtualArchitecture;
import com.palmnest.service.UserManager;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.estateserve.ScWxuserManager;
import com.palmnest.service.estateserve.VirtualArchManager;
import com.palmnest.service.notice.*;
import com.palmnest.service.notice.service.NoticePublicnoService;
import com.palmnest.service.redis.BaseRedisService;
import com.palmnest.service.wechat.WeChatAccessManager;
import com.palmnest.service.wechat.WeChatApiManager;

import kafka.utils.Json;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.*;

@Slf4j
@Service("noticePublicnoService")
public class NoticePublicnoServiceImpl implements NoticePublicnoService {

	@Autowired
	private WxPubManager             wxPubManager;
	@Autowired
	private WxUploadMaterialManager  wxUploadMaterialManager;
	@Autowired
	private AppNoticeDetailManager   appNoticeDetailManager;
	@Autowired
	private WxMassmessageSendManager wxMassmessageSendManager;
	@Autowired
	private AppNoticeContentManager  appNoticeContentManager;
	@Autowired
	private AppNoticeManager         appNoticeManager;

	@Autowired
	private UserManager              userManager;
	@Autowired
	private BaseRedisService         baseRedisService;
	@Autowired
	private WeChatAccessManager      weChatAccessManager;
	@Autowired
	private AppUserManager           appUserManager;
	@Autowired
	private VirtualArchManager       virtualArchManager;
	@Autowired
	private ScWxuserManager          scWxuserManager;
	@Autowired
	private WeChatApiManager weChatApiManager;
	@Autowired
	private AppNoticeRecordManager appNoticeRecordManager;
	@Autowired
	private NoticeApprovalsetManager noticeApprovalsetManager;

	@Autowired
	private NoticeSubGroupManager noticeSubGroupManager;

	private static String image_server   = PropertiesKit.readPropertiesValue("image_server", "wechat.properties");
	private static String attachment     = PropertiesKit.readPropertiesValue("attachment.root", "wechat.properties");
	private        String hostUrl        = PropertiesKit.readPropertiesValue("hostUrl", "wechat.properties");
	private        String wxAppNoticeUrl = PropertiesKit.readPropertiesValue("wxAppNoticeUrl", "wechat.properties");


	/**
	 * 获取token
	 * @param no
	 * @return
	 */
	public String getTokenByOrgId(WxPublicno no) {
		String token = "";
		//然后根据公众号信息找相应的token
		try {
			token = weChatAccessManager.getAccessToken(no.getDevelopId());
			if (!StringUtil.isNotEmpty(token)) {
				log.info("获取token失败,公众号为：" + no.getDevelopId());
				return "";
			}
			return token;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.error("上传图文消息失败：" + e.getMessage());
			return "";
		}
	}

//	/**
//	 * 上传压缩素材图片
//	 */
//	@Override
//	public Map<String, Object> addThumbImg(String imgUrl, Integer userId,
//			String orgIds,Integer sourceId,String author) {
//		Map<String, Object> map=new HashMap<String, Object>();
//		map.put("code", 500);
//		String [] orgArr=orgIds.split(",");
//		if(null==orgArr||orgArr.length<=0){
//			map.put("msg", "获取不到项目信息");
//			return map;
//		}
//		int count=0;
//		StringBuilder sb=new StringBuilder();
//		for(int i=0;i<orgArr.length;i++){
//			WxPublicno no=wxPubManager.getPublicByOrgId(orgArr[i]);
//			if(null==no){
//				count++;
//				sb.append("orgId:"+orgArr[i]+";sourceId:"+sourceId+";该项目下找不到公众号");
//				continue;
//			}
//			String token=getTokenByOrgId(no);
//			if(!StringUtil.isNotEmpty(token)){
//				count++;
//				sb.append("orgId:"+orgArr[i]+";sourceId:"+sourceId+";该项目下的该订单获取token失败");
//				continue;
//			}
//			if(!StringUtil.isNotEmpty(imgUrl)){
//				count++;
//				sb.append("orgId:"+orgArr[i]+";sourceId:"+sourceId+";该项目下的该订单上传素材失败");
//				continue;
//			}
//			String res=saveMaterial(token,imgUrl,userId,no.getDevelopId(),Integer.parseInt(orgArr[i]),sourceId);
//			if(StringUtil.isNotEmpty(res)){
//				count++;
//				sb.append("orgId:"+orgArr[i]+";sourceId:"+sourceId+";该项目下的该订单上传素材失败:"+res);
//				continue;
//			}
//		}
//		if(count>0){
//			map.put("code", 500);
//			map.put("msg", "添加素材异常");
//			map.put("msgStr", sb.toString());
//			map.put("bugCount", count);
//			return map;
//		}
//		map.put("code", 200);
//		map.put("msg", "成功");
//		map.put("msgStr", sb.toString());
//		map.put("bugCount", count);
//		return map;
//	}
//	

	/**
	 * 保存图文缩略素材
	 *
	 * @param token
	 * @param imgUrl
	 * @param userId
	 * @param developid
	 * @param orgId
	 * @param sourceId
	 * @return
	 */
	private Map<String, Object> saveMaterial(String token, String imgUrl, Integer userId, String developid, Integer orgId, Integer sourceId) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", 500);
		map.put("mediaId", "");
		String              type = "thumb";
		Map<String, String> resImgMap;
		try {
			resImgMap = WechatMsgMassUtils.uploadMaterial(imgUrl, token, type, "", "");
			if (StringUtil.isNotEmpty(resImgMap.get("errcode"))) {
				map.put("msg", "上传素材失败:" + resImgMap.get("errmsg"));
				return map;
			}
			String url      = resImgMap.get("url") != null ? resImgMap.get("url").toString() : "";
			String media_id = resImgMap.get("media_id") != null ? resImgMap.get("media_id").toString() : "";
			if (StringUtil.isNotEmpty(url) && StringUtil.isNotEmpty(media_id)) {
				WxUploadMaterialModel uploadMaterial = new WxUploadMaterialModel();
				uploadMaterial.setCreated_at(new Date());
				uploadMaterial.setCreated_by(userId);
				uploadMaterial.setDevelopid(developid);
				uploadMaterial.setUrl(url);
				uploadMaterial.setIsEnabled(1);
				uploadMaterial.setM_type(type);
				uploadMaterial.setOrgId(orgId);
				uploadMaterial.setSourceId(sourceId);
				uploadMaterial.setMedia_id(media_id);
				//---------------保存数据库
				wxUploadMaterialManager.save(uploadMaterial);
				map.put("code", 200);
				map.put("msg", "");
				map.put("mediaId", media_id);
				return map;
			} else {
				//保存失败
				map.put("msg", "获取到的素材为空");
				return map;
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("msg", "上传素材失败");
			return map;
		}
	}

//	/**
//	 * 删除素材
//	 */
//	@Override
//	public Map<String, Object> deleteNews(String orgIds,Integer noticeDetailId,Integer userId) {
//		Map<String, Object> map=new HashMap<String, Object>();
//		map.put("code", 500);
//		String [] orgArr=orgIds.split(",");
//		if(null==orgArr||orgArr.length<=0){
//			map.put("msg", "获取不到项目信息");
//			return map;
//		}
//		int count=0;
//		StringBuilder sb=new StringBuilder();
//		for(int i=0;i<orgArr.length;i++){
//			String token=getTokenByOrgId(orgArr[i]);
//			if(!StringUtil.isNotEmpty(token)){
//				count++;
//				sb.append("该项目获取不到token："+orgArr[i]);
//				continue;
//			}
//			WxUploadMaterialModel  model=wxUploadMaterialManager.findBySourceId(noticeDetailId, "thumb", Integer.parseInt(orgArr[i]));
//			if(null==model){
//				sb.append("该项目获取不到相应的压缩素材（thumb）："+orgArr[i]);
//				continue;
//			}
//			Map<String, String> delMap=WechatMsgMassUtils.deleteNews(token, model.getMedia_id());
//			//成功
//			boolean bool=null!=delMap&&delMap.containsKey("code")&&"200".equals(delMap.get("code"));
//			if(!bool){
//				count++;
//				sb.append("该项目删除压缩素材失败："+orgArr[i]);
//			}
//			//删除相应的记录
//			model.setIsEnabled(0);
//			model.setUpdated_at(new Date());
//			model.setUpdated_by(userId);
//			wxUploadMaterialManager.updateModel(model);
//		}
//		if(count>0){
//			map.put("code", 500);
//			map.put("msg", "添加素材异常");
//			map.put("msgStr", sb.toString());
//			map.put("bugCount", count);
//			return map;
//		}
//		map.put("code", 200);
//		map.put("msg", "成功");
//		map.put("msgStr", sb.toString());
//		map.put("bugCount", count);
//		return map;
//	}

//	@Override
//	public Map<String, Object> sendPublicno(AppNoticeModel appNotice,
//			Integer userId) {
//		//首先上传素材---得到素材的相关url以及素材的media_id;
////		Map<String, Object> map=addThumbImg(appNotice.getCoverUrl(),userId,appNotice.getOrgIds(),appNotice.getId());
//		//上传图文消息素材
//		
//		
//		return null;
//	}


//	/**
//	 * 修改素材
//	 */
//	@Override
//	public Map<String, Object> updateNews(AppNoticeModel appNotice,String author){
//		Map<String, Object> map=new HashMap<String, Object>();
//		map.put("code", 500);
//		String orgIds="";
//		if(StringUtil.isNotEmpty(appNotice.getOrgIds())){
//			orgIds=appNotice.getOrgIds();
//		}else{
//			orgIds=appNotice.getOrgId().toString();
//		}
//		String [] orgArr=orgIds.split(",");
//		if(null==orgArr||orgArr.length<=0){
//			map.put("msg", "获取不到项目信息");
//			return map;
//		}
//		int count=0;
//		StringBuilder sb=new StringBuilder();
//		for(int i=0;i<orgArr.length;i++){
//			String token=getTokenByOrgId(orgArr[i]);
//			if(!StringUtil.isNotEmpty(token)){
//				count++;
//				sb.append("该项目获取不到token："+orgArr[i]);
//				continue;
//			}
//			updateNewsInfo(token,appNotice,Integer.parseInt(orgArr[i]),author);
//		}
//		if(count>0){
//			map.put("code", 500);
//			map.put("msg", "修改素材异常");
//			map.put("msgStr", sb.toString());
//			map.put("bugCount", count);
//			return map;
//		}
//		map.put("code", 200);
//		map.put("msg", "成功");
//		map.put("msgStr", sb.toString());
//		map.put("bugCount", count);
//		return map;
//	}

//	/**
//	 * 修改素材
//	 * @param token
//	 * @param appNotice
//	 * @param orgId
//	 * @param author
//	 * @return
//	 */
//	private String updateNewsInfo(String token,AppNoticeModel appNotice,Integer orgId,String author){
//		//首先拿公告详情
//		List<AppNoticeDetailModel> list=appNoticeDetailManager.getNoticeDetail(appNotice.getId());
//		if(null==list||list.size()<=0){
//			return "未获取到详情";
//		}
//		try {
//			for(AppNoticeDetailModel model:list){
//				WxUploadMaterialModel mateModel=wxUploadMaterialManager.findBySourceId(model.getId(),"news",orgId);
//				if(null==mateModel){
//					continue;
//				}
//				WxArticle wxArticle=getWxArticle(model,author,orgId);
//				if(null==wxArticle){
//					continue;
//				}
//				WechatMsgMassUtils.updateNews(token, mateModel.getMedia_id(), wxArticle, model.getPosition());
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//			log.error("修改素材失败:"+e.getMessage());
//			return "修改素材失败";
//		}
//		return "";
//	}
//	
//	/**
//	 * 修改素材时设置的相关信息
//	 * @param model
//	 * @param author
//	 * @param orgId
//	 * @return
//	 */
//	private WxArticle getWxArticle(AppNoticeDetailModel model,String author,Integer orgId){
//		WxUploadMaterialModel thumbModel=wxUploadMaterialManager.findBySourceId(model.getId(),"thumb",orgId);
//		if(null==thumbModel){
//			return null;
//		}
//		WxArticle wxArticle=new WxArticle();
//		wxArticle.setAuthor(author);
//		wxArticle.setContent(model.getContent());
//		wxArticle.setDigest(model.getSummaryInfo());
//		if(null!=model.getPosition()&&0==model.getPosition().intValue()){
//			wxArticle.setShow_cover_pic("1");
//		}else{
//			wxArticle.setShow_cover_pic("0");
//		}
//		wxArticle.setThumb_media_id(thumbModel.getMedia_id());
//		wxArticle.setTitle(model.getTitle());
//		return wxArticle;
//	}
//	


//	@Override
//	public Map<String,Object> uploadnews(String orgIds, Integer userId,AppNoticeModel appNotice) {
//		Map<String, Object> map=new HashMap<String, Object>();
//		map.put("code", 500);
//		String [] orgArr=orgIds.split(",");
//		if(null==orgArr||orgArr.length<=0){
//			map.put("msg", "获取不到项目信息");
//			return map;
//		}
//		int count=0;
//		StringBuilder sb=new StringBuilder();
//		for(int i=0;i<orgArr.length;i++){
//			WxPublicno no=wxPubManager.getPublicByOrgId(orgArr[i]);
//			if(null==no){
//				count++;
//				sb.append("orgId:"+orgArr[i]+";sourceId:"+appNotice.getId()+";该项目下的该订单上找不到公众号");
//				continue;
//			}
//			String token=getTokenByOrgId(no);
//			String res="";
//			if(StringUtil.isNotEmpty(res)){
//				count++;
//				sb.append("orgId:"+orgArr[i]+";sourceId:"+appNotice.getId()+";该项目下的该订单上传素材失败:"+res);
//				continue;
//			}
//		}
//		if(count>0){
//			map.put("code", 500);
//			map.put("msg", "添加素材异常");
//			map.put("msgStr", sb.toString());
//			map.put("bugCount", count);
//			return map;
//		}
//		map.put("code", 200);
//		map.put("msg", "成功");
//		map.put("msgStr", sb.toString());
//		map.put("bugCount", count);
//		return map;
//	}
//	

//	
//	private String saveNews(String token,Integer userId,String  developid,Integer orgId,List<WxArticle> ls,Integer sourceId){
//		String res="";
//		 String type="news";
//		Map<String, String> resImgMap;
//		try {
//				resImgMap = WechatMsgMassUtils.UploadNewsWithMedia(token,ls);
//				 if(StringUtil.isNotEmpty(resImgMap.get("errcode"))){
//		             return "上传素材失败:"+resImgMap.get("errmsg");
//		         }
//	           Map<String, Object> imgMap = JSONObject.parseObject(resImgMap.get("data"));
//	           String url = imgMap.get("url")!=null?imgMap.get("url").toString():"";
//	           String media_id = imgMap.get("media_id")!=null?imgMap.get("media_id").toString():"";
//	           if(StringUtil.isNotEmpty(url)&&StringUtil.isNotEmpty(media_id)){
//	               WxUploadMaterialModel uploadMaterial = new WxUploadMaterialModel();
//	               uploadMaterial.setCreated_at(new Date());
//	               uploadMaterial.setCreated_by(userId);
//	               uploadMaterial.setDevelopid(developid);
//	               uploadMaterial.setUrl(url);
//	               uploadMaterial.setUpdated_at(new Date());
//	               uploadMaterial.setUpdated_by(userId);
//	               uploadMaterial.setM_type(type);
//	               uploadMaterial.setOrgId(orgId);
//	               uploadMaterial.setSourceId(sourceId);
//	               uploadMaterial.setMedia_id(media_id);
//	               //---------------保存数据库
//	               wxUploadMaterialManager.save(uploadMaterial);
//	               return res;
//	           }else{
//	               //保存失败
//	        	   return "获取到的素材为空";
//	           }
//		} catch (Exception e) {
//			e.printStackTrace();
//			 return "上传素材失败";
//		}
//	}

	/**
	 * 保存修改公告的详情
	 */
	@Override
	public String saveDetaile(String noticeDetail, Integer noticeId,
							  String userId,Boolean insert,Integer publicId) {
		List<AppNoticeDetailDto> detailList = new ArrayList<AppNoticeDetailDto>();
		if (StringUtils.isNotEmpty(noticeDetail)) {
			detailList = JSON.parseArray(noticeDetail, AppNoticeDetailDto.class);
		}
		if (null == detailList || detailList.size() <= 0) {
			return "未获取到内容";
		}
		for (AppNoticeDetailDto dto : detailList) {
			if (null == dto.getId() || insert) {
				AppNoticeDetailModel model = new AppNoticeDetailModel();
				model.setContent(dto.getContent());
				model.setContentTxt(dto.getContentTxt());
				model.setCoverUrl(dto.getCoverUrl().replaceAll("https:", "").replaceAll("http:", ""));
				model.setCreateTime(new Date());
				model.setCreator(userId);
				model.setIsEnabled("1");
				model.setSourceId(noticeId);

				model.setSummaryInfo(dto.getSummaryInfo());
				model.setTitle(dto.getTitle());
				model.setPosition(dto.getPosition());
				appNoticeDetailManager.saveModel(model);
				String url = hostUrl + wxAppNoticeUrl.replace("@id", model.getId().toString()) + "&hideButton=1&sourceType=2";
				if(null != publicId){
					url = url + "&publicId="+publicId;
				}
				model.setUrl_address(url.replaceAll("https:", "").replaceAll("http:", ""));
				appNoticeDetailManager.updateModel(model);
			} else {
				AppNoticeDetailModel model = appNoticeDetailManager.get(dto.getId());
				String               url   = hostUrl + wxAppNoticeUrl.replace("@id", dto.getId().toString()) + "&hideButton=1&sourceType=2";
				model.setContent(dto.getContent());
				model.setContentTxt(dto.getContentTxt());
				model.setCoverUrl(dto.getCoverUrl().replaceAll("https:", "").replaceAll("http:", ""));
				model.setSummaryInfo(dto.getSummaryInfo());
				model.setTitle(dto.getTitle());
				if(null != publicId){
					url = url + "&publicId="+publicId;
				}
				model.setUrl_address(url.replaceAll("https:", "").replaceAll("http:", ""));
				model.setPosition(dto.getPosition());
				model.setModifier(userId);
				model.setModifyTime(new Date());
				appNoticeDetailManager.updateModel(model);
			}
		}
		return "";
	}

	//首先保存压缩图

	//然后拿到压缩图的id新增图文素材
	//然后再发送图文素材

	/**
	 * 删除分支
	 */
	@Override
	public String delDetaile(Integer noticeDetailId, String userId) {
		AppNoticeDetailModel model = appNoticeDetailManager.get(noticeDetailId);
		if (null == model) {
			return "找不到该素材";
		}
		model.setIsEnabled("0");
		model.setModifier(userId);
		model.setModifyTime(new Date());
		appNoticeDetailManager.updateModel(model);
		return "";
	}

	/**
	 * 发布
	 */
	@Transactional
	public Map<String, Object> uploadnews(AppNoticeModel appNotice, User user) {
		return sendMedial(appNotice, user);
	}

	/**
	 * 第一步 首先新增压缩图片，然后将上传的压缩图片返回的url及medialId存到我们的表中；
	 * 第二步 上传素材，需要带上之前上传上去的压缩图片，然后上传；
	 * 第三步  发送相关人员
	 */

	@Transactional
	public Map<String, Object> sendMedial(AppNoticeModel appNotice, User user) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", 500);
		int     count  = 0;
		Integer userId = Integer.parseInt(user.getId().toString());
		//挨个项目的发送
		String orgIds ;
		if (StringUtil.isNotEmpty(appNotice.getOrgIds())) {
			orgIds = appNotice.getOrgIds();
		} else {
			orgIds = appNotice.getOrgId().toString();
		}
		String[] orgArr = orgIds.split(",");
		if (null == orgArr || orgArr.length <= 0) {
			count++;
			map.put("msg", "获取不到项目信息");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return map;
		}

		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < orgArr.length; i++) {
			WxPublicno no = wxPubManager.getPublicByOrgId(orgArr[i]);
			if (null == no) {
				count++;
				sb.append("orgId:" + orgArr[i] + ";sourceId:" + appNotice.getId() + ";该项目下的该订单上找不到公众号");
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				continue;
			}
			String  developId = no.getDevelopId();
			Integer orgId     = Integer.parseInt(orgArr[i]);
			String  token     = getTokenByOrgId(no);
			if (!StringUtil.isNotEmpty(token)) {
				count++;
				sb.append("orgId:" + orgArr[i] + ";sourceId:" + appNotice.getId() + ";该项目下获取不到token");
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				continue;
			}

			log.info("--------上传内容中的图片-------setImages begin--------------------");
			//上传内容中的图片，然后将内容替换
			List<AppNoticeDetailModel> list = appNoticeDetailManager.getNoticeDetail(appNotice.getId());
			int                        type = 1;
			if (list != null && list.size() > 0) {
				type = 2;
				for (AppNoticeDetailModel model : list) {
					String content = setImages(model.getId(), model.getContent(), type, userId, token, orgId, developId);
					log.info("---------------setImages_model_content:{}",content);
					model.setContent(content);
					model.setModifier(userId.toString());
					model.setModifyTime(new Date());
					appNoticeDetailManager.updateModel(model);
				}
			} else {
				String content = setImages(appNotice.getId(), appNotice.getContent(), type, userId, token, orgId, developId);
				log.info("---------------setImages_content:{}",content);
				appNotice.setContent(content);
				appNotice.setModifier(userId.toString());
				appNotice.setModifyTime(new Date());
				appNoticeManager.updateModel(appNotice);

			}
			log.info("---------------setImages end--------------------");
			
			//上传压缩图
			String author = "";
			if (StringUtil.isNotEmpty(user.getFullName())) {
				author = user.getFullName();
			} else {
				author = user.getUsername();
			}
			log.info("---------------addThumbImg begin--------------------");
			//上传压缩图
			List<WxArticle> ls = addThumbImg(token, appNotice.getId(), userId, developId, orgId, author, appNotice.getUrl_address());
			if (null==ls||ls.size()<=0) {
				count++;
				sb.append("orgId:" + orgArr[i] + ";sourceId:" + appNotice.getId() + ";该项目下的该订单上传压缩图失败");
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				continue;
			}
			log.info("addThumbImg-ls:" + JsonUtils.toJson(ls));
			log.info("---------------addThumbImg end--------------------");
			log.info("-----------上传素材----sendNews begin--------------------");
			//上传素材
			String media_id = sendNews(token, ls, userId, developId, appNotice.getId(), orgId);
			log.info("----------上传素材-----sendNews end--------------------media_id:{}",media_id);
			//发布
			if (!StringUtil.isNotEmpty(media_id)) {
				count++;
				sb.append("orgId:" + orgArr[i] + ";sourceId:" + appNotice.getId() + ";该项目下的该订单上传素材失败");
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				continue;
			}
			String res = "";
			//发送公众号下面所有的用户
			if (null != appNotice.getPublicObj() && 1 == appNotice.getPublicObj().intValue()) {
				//显示在列表就给公众号下面所有的用户发送
				if (1 == appNotice.getIsMessageList()) {
					res = sendNewsMSGAll(token, media_id, developId, userId);
				} else {
					//不显示在列表就给公众号下查询到的所有的用户发送
//					List<String> openIds = wxMassmessageSendManager.getUserByDevelopid(developId);
					List<String> openIds = getWxPublicUser(developId);
					//推送的人必须大于2
					if(CollectionUtils.isEmpty(openIds) || (!CollectionUtils.isEmpty(openIds) && openIds.size()<2)){
						count++;
						sb.append("orgId:" + orgArr[i] + ";sourceId:" + appNotice.getId() + ";该项目下不显示在列表中的用户人数不超过2个");
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						continue;
					}
					res = sendNewsMSG(token, openIds, media_id, developId, userId,1);
				}
			} else if (null != appNotice.getPublicObj() && 2 == appNotice.getPublicObj().intValue()) {
				//发送项目下所有的用户
				List<String> openIds = getOpenIds(orgArr[i], 1);
				//推送的人必须大于2
				if(CollectionUtils.isEmpty(openIds) || (!CollectionUtils.isEmpty(openIds) && openIds.size()<2)){
					count++;
					sb.append("orgId:" + orgArr[i] + ";sourceId:" + appNotice.getId() + ";该项目下发送项目下所有用户的用户人数不超过2个");
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					continue;
				}
				res = sendNewsMSG(token, openIds, media_id, developId, userId,0);
			} else if (null != appNotice.getPublicObj() && 3 == appNotice.getPublicObj().intValue()) {
				//发送项目下部分用户      sssss
				List<String> openIds = getOpenIds(appNotice.getOpenIds(), 2);
				//推送的人必须大于2
				if(CollectionUtils.isEmpty(openIds) || (!CollectionUtils.isEmpty(openIds) && openIds.size()<2)){
					count++;
					sb.append("orgId:" + orgArr[i] + ";sourceId:" + appNotice.getId() + ";该项目下发送项目下部分用户的用户人数不超过2个");
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					continue;
				}
				res = sendNewsMSG(token, openIds, media_id, developId, userId,0);
			} else if (null != appNotice.getPublicObj() && 4 == appNotice.getPublicObj().intValue()) {
				List<DeptUserVo> deptUserVoList =getDeptUser(1,appNotice.getId(),appNotice.getOrgId());
				StringBuffer sf = new StringBuffer();
				for (DeptUserVo deptUserVo : deptUserVoList) {
					sf.append(deptUserVo.getUserId()).append(",");
				}
				sf.deleteCharAt(sf.length()-1);

				//发送部门/分组下用户
				List<String> openIds = getOpenIds(sf.toString(), 3);
				//推送的人必须大于2
				if(CollectionUtils.isEmpty(openIds) || (!CollectionUtils.isEmpty(openIds) && openIds.size()<2)){
					count++;
					sb.append("orgId:" + orgArr[i] + ";sourceId:" + appNotice.getId() + ";该项目下发送分组/部门下部分用户的用户人数不超过2个");
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					continue;
				}
				res = sendNewsMSG(token, openIds, media_id, developId, userId,0);
			}
			if (StringUtil.isNotEmpty(res)) {
				count++;
				sb.append("orgId:" + orgArr[i] + ";sourceId:" + appNotice.getId() + ";该项目下的该订单发送消息失败");
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				continue;
			}
		}
		if (count > 0) {
			map.put("code", 500);
			map.put("msg", "添加素材异常");
			map.put("msgStr", sb.toString());
			map.put("bugCount", count);
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return map;
		}
		map.put("code", 200);
		map.put("msg", "成功");
		map.put("msgStr", sb.toString());
		map.put("bugCount", count);
		return map;
	}



	/**
	 * type==1时str=项目Id
	 * type==2时str=openIds
	 *type==3时str=userId
	 * @param str
	 * @param type
	 * @return
	 */
	public List<String> getOpenIds(String str, int type) {
		List<String> openIds = new ArrayList<String>();
		if (1 == type) {
			List<WxPublicnoUserDto> list = wxMassmessageSendManager.getUserByOrgId(str, "");
			if (null == list || list.size() <= 0) {
				return null;
			}
			for (WxPublicnoUserDto dto : list) {
				String openId = dto.getOpenId();
				if (StringUtil.isNotEmpty(openId)) {
					openIds.add(openId);
				}
			}
		} else if(2==type){
			String[] strs = str.split(",");
			if (null == strs || strs.length <= 0) {
				return null;
			}
			for (int i = 0; i < strs.length; i++) {
				if (StringUtil.isNotEmpty(strs[i])) {
					openIds.add(strs[i]);
				}
			}
		}else {
			List<Map<String, Object>> list= wxMassmessageSendManager.getByUser(str);
			if (null == list || list.size() <= 0) {
				return null;
			}
			for (Map<String, Object> map : list) {
				if(map.containsKey("bindOpenid") && null != map.get("bindOpenid")){
					openIds.add(map.get("bindOpenid").toString());
				}else if(map.containsKey("openId") && null != map.get("openId")){
					openIds.add(map.get("openId").toString());
				}
			}
		}
		List<String> listNew=new ArrayList<String>(new TreeSet<String>(openIds));
		return listNew;
	}

	/**
	 * 发送该项目下部分用户
	 *
	 * @param token
	 * @param openIds
	 * @param medisId
	 * @param developId
	 * @param userId
	 * @return
	 */
	private String sendNewsMSG(String token, List<String> openIds, String medisId, String developId, Integer userId,int isPublicUser) {
		String              msgtype    = "mpnews";
		Map<String, String> resNewsMap = WechatMsgMassUtils.SendMassMSGWithOpenId(msgtype, token, openIds, medisId, "", "", 0,isPublicUser);

		log.info("sendNewsMSG===> resNewsMap:"+JsonUtils.toJson(resNewsMap));

		if (resNewsMap.get("code").equals("200")) {
			System.out.println(resNewsMap);
			WxMassmessageSendModel massmessageSend = new WxMassmessageSendModel();
			massmessageSend.setCreated_at(new Date());
			massmessageSend.setCreated_by(userId);
			massmessageSend.setDevelopid(developId);
			massmessageSend.setIs_to_all("false");
			massmessageSend.setMedia_id(medisId);
			massmessageSend.setMsgtype(msgtype);
			massmessageSend.setSend_ignore_reprint(0);
			massmessageSend.setMsg_id(resNewsMap.get("msg_id"));
			if (msgtype.equals("mpnews")) {
				massmessageSend.setMsg_data_id(resNewsMap.get("msg_data_id"));
			}
			wxMassmessageSendManager.save(massmessageSend);
			return "";
		} else {
			if(resNewsMap.get("code").equals("40001")) {
				//accessToken失效重新获取
				String accessToken = null;
				try {
					accessToken = weChatApiManager.getAccessToken(developId);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return sendNewsMSG(accessToken, openIds, medisId, developId, userId,isPublicUser);
			}
			return resNewsMap.get("msg");
		}
	}

	/**
	 * 发送公众号下所有的用户
	 *
	 * @param token
	 * @param medisId
	 * @param developId
	 * @param userId
	 * @return
	 */
	private String sendNewsMSGAll(String token, String medisId, String developId, Integer userId) {
		String              msgtype    = "mpnews";
		Map<String, String> resNewsMap = WechatMsgMassUtils.SendMassMSGAll(msgtype, token, true, null, medisId, 0);

		log.info("sendNewsMSGAll===> resNewsMap:"+JsonUtils.toJson(resNewsMap));

		if (resNewsMap.get("code").equals("200")) {
			System.out.println(resNewsMap);
			WxMassmessageSendModel massmessageSend = new WxMassmessageSendModel();
			massmessageSend.setCreated_at(new Date());
			massmessageSend.setCreated_by(userId);
			massmessageSend.setDevelopid(developId);
			massmessageSend.setIs_to_all("true");
			massmessageSend.setMedia_id(medisId);
			massmessageSend.setMsgtype(msgtype);
			massmessageSend.setSend_ignore_reprint(0);
			massmessageSend.setMsg_id(resNewsMap.get("msg_id"));
			if (msgtype.equals("mpnews")) {
				massmessageSend.setMsg_data_id(resNewsMap.get("msg_data_id"));
			}
			wxMassmessageSendManager.save(massmessageSend);
			return "";
		} else {
			if (resNewsMap.get("code").equals("40001")) {
				//accessToken失效重新获取
				String accessToken = null;
				try {
					accessToken = weChatApiManager.getAccessToken(developId);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return sendNewsMSGAll(accessToken, medisId, developId, userId);
			}

			return resNewsMap.get("msg");
		}
	}

	/**
	 * 上传压缩图
	 *
	 * @param token
	 * @param noticeId
	 * @param userId
	 * @param developid
	 * @param orgId
	 * @return
	 */
	@Transactional
	public List<WxArticle> addThumbImg(String token, Integer noticeId, Integer userId, String developid, Integer orgId, String author, String url_address) {
		List<WxArticle>            ls   = new ArrayList<WxArticle>();
		StringBuilder              sb   = new StringBuilder();
		List<AppNoticeDetailModel> list = appNoticeDetailManager.getNoticeDetail(noticeId);
		if (null == list || list.size() <= 0) {
			return null;
		}
		for (AppNoticeDetailModel model : list) {
			String coverUrl=model.getCoverUrl();
			if(coverUrl.indexOf(CodeConstants.HTTPS) == -1 && coverUrl.indexOf(CodeConstants.HTTP) == -1){
				coverUrl=CodeConstants.HTTP+coverUrl;
			}
			log.info("------------addThumbImg-coverUrl:{}",JsonUtils.toJson(coverUrl));
			if (coverUrl.indexOf(image_server) != -1) {
				String              path     = coverUrl.replace(image_server, "");
				String              filePath = attachment + path;
				Map<String, Object> matMap   = saveMaterial(token, filePath, userId, developid, orgId, model.getId());
				log.info("------------addThumbImg-matMap:{}",JsonUtils.toJson(matMap));
				if (200 == Integer.parseInt(matMap.get("code").toString()) && StringUtil.isNotEmpty(matMap.get("mediaId").toString())) {
					String mediaId = matMap.get("mediaId").toString();
					String show    = "0";
//					if (0 == model.getPosition().intValue()) {
//						show = "1";
//					}
					ls.add(new WxArticle(mediaId, author, model.getTitle(),CodeConstants.HTTP+url_address, model.getContent(), model.getSummaryInfo(), show, "0", "0"));
				} else {
					sb.append(matMap.get("msg").toString());
					continue;
				}
			} else {
				continue;
			}
		}
		return ls;
	}

	/**
	 * 上传素材
	 *
	 * @param token
	 * @param ls
	 * @param userId
	 * @param developid
	 * @param noticeId
	 * @param orgId
	 * @return
	 */
	private String sendNews(String token, List<WxArticle> ls, Integer userId, String developid, Integer noticeId, Integer orgId) {
		String              type       = "news";
		Map<String, String> resNewsMap = WechatMsgMassUtils.UploadNewsWithMediaForever(token, ls);
		if (resNewsMap.get("code").equals("200")) {
			WxUploadMaterialModel uploadMaterial = new WxUploadMaterialModel();
			uploadMaterial.setCreated_at(new Date());
			uploadMaterial.setCreated_by(userId);
			uploadMaterial.setDevelopid(developid);
			uploadMaterial.setIsEnabled(1);
			uploadMaterial.setM_type(type);
			uploadMaterial.setOrgId(orgId);
			uploadMaterial.setSourceId(noticeId);
			uploadMaterial.setMedia_id(resNewsMap.get("media_id"));
			//---------------保存数据库
			wxUploadMaterialManager.save(uploadMaterial);
			return resNewsMap.get("media_id");
		} else {
			return "";
		}
	}

	public String uploadImages(Integer orgId, String path, Integer userId, String developId, String token) {
		Map<String, String> resImgMap = WechatMsgMassUtils.UploadimgWithMedia(token, path);
		if (resImgMap.get("code").equals("200")) {
			Map<String, Object> imgMap = JSONObject.parseObject(resImgMap.get("data"));
			String              url    = imgMap.get("url") != null ? imgMap.get("url").toString() : "";
			if (StringUtils.isNotEmpty(url)) {
				WxUploadMaterialModel uploadMaterial = new WxUploadMaterialModel();
				uploadMaterial.setCreated_at(new Date());
				uploadMaterial.setCreated_by(userId);
				uploadMaterial.setDevelopid(developId);
				uploadMaterial.setUrl(url);
				uploadMaterial.setM_type("image");
				uploadMaterial.setOrgId(orgId);
				wxUploadMaterialManager.save(uploadMaterial);
				return url;
			} else {
				return "";
			}
		} else {
			return "";
		}
	}

//	@Override
//	public String saveImages(AppNoticeModel appNotice, User user) {
//		StringBuilder sb=new StringBuilder("");
//		Integer userId=Integer.parseInt(user.getId().toString());
//		 //挨个项目的发送
//		 String orgIds="";
//		 if(StringUtil.isNotEmpty(appNotice.getOrgIds())){
//			 orgIds=appNotice.getOrgIds();
//		 }else{
//			 orgIds=appNotice.getOrgId().toString();
//		 }
//			String [] orgArr=orgIds.split(",");
//			if(null==orgArr||orgArr.length<=0){
//				sb.append("未获取到项目");
//				return "";
//			}
//			for(int i=0;i<orgArr.length;i++){
//				WxPublicno no=wxPubManager.getPublicByOrgId(orgArr[i]);
//				if(null==no){
//					sb.append("orgId:"+orgArr[i]+";sourceId:"+appNotice.getId()+";该项目下的该订单上找不到公众号");
//					continue;
//				}
//				String developId=no.getDevelopId();
//				Integer orgId=Integer.parseInt(orgArr[i]);
//				String token=getTokenByOrgId(no);
//				if(!StringUtil.isNotEmpty(token)){
//					sb.append("orgId:"+orgArr[i]+";sourceId:"+appNotice.getId()+";该项目下获取不到token");
//					continue;
//				}
//				String content="";
//				List<AppNoticeDetailModel> list=appNoticeDetailManager.getNoticeDetail(appNotice.getId());
//				int type=1;
//				if(list!=null&&list.size()>0){
//					 type=2;
//					for(AppNoticeDetailModel model:list){
//						content=setImages(model.getId(), model.getContent(), type, userId, token, orgId, developId);
//						model.setContent(content);
//						model.setModifier(userId.toString());
//						model.setModifyTime(new Date());
//						appNoticeDetailManager.updateModel(model);
//					}
//				}else{
//					content=setImages(appNotice.getId(), appNotice.getContent(), type, userId, token, orgId, developId);
//					appNotice.setContent(content);
//					appNotice.setModifier(userId.toString());
//					appNotice.setModifyTime(new Date());
//					appNoticeManager.updateModel(appNotice);
//					
//				}
//			}
//		return "";
//	}

	private String setImages(Integer id, String content, int type, Integer userId, String token, Integer orgId, String developId) {
		List<String> list = StringUtil.getImgSrc(content);
		if (null == list || list.size() <= 0) {
			return content;
		}
		for (int i = 0; i < list.size(); i++) {
			String image = list.get(i);
			//是我们服务器的地址
			if (image.indexOf(image_server) != -1) {
				AppNoticeContentModel model = appNoticeContentManager.findByIdAndImage(id, image, type, 1);
				if (null == model) {
					//上传图片且得到地址
					String path     = image.replace(image_server, "");
					String filePath = attachment + path;
					String url      = uploadImages(orgId, filePath, userId, developId, token);
					if (StringUtil.isNotEmpty(url)) {
						model = new AppNoticeContentModel();
						model.setCreateTime(new Date());
						model.setCreator(userId);
						model.setIsEnabled(1);
						model.setNewImage(url);
						model.setOldImage(image);
						model.setSourceId(id);
						model.setType(type);
						appNoticeContentManager.save(model);
						//将内容的地址替换
						content = content.replace(image, url);
					}
				} else {
					continue;
				}
			} else {
				continue;
			}

		}
		return content;
	}

	@Transactional
	public Map<String, Object> approvalAppNotice(AppNoticeModel appNotice,HttpServletRequest request, User user, int type) throws Exception {
		String id        = request.getParameter("id");
		String state     = request.getParameter("state");

		log.info("NoticePublicnoServiceImpl.approvalAppNotice ===> id:" + id + " state:" + state +" type:" + type);
		Map<String, Object> resMap = new HashMap<String, Object>();
		resMap.put("code", 500);
		resMap.put("data", null);
		int count = 0;
		try {
			String isEnabled = "2";//通知公告 上线
			if (!StringUtil.isNotEmpty(id)) {//修改
				count++;
				resMap.put("msg", "发布失败");
				resMap.put("msgStr", "发布失败:获取不到单据id");
				resMap.put("bugCount", count);
				return resMap;
			}
			appNotice.setApproval_user(user.getFullName() == "" ? user.getUsername() : user.getFullName());
			appNotice.setApproval_time((new Date()));
			appNotice.setState(Integer.parseInt(state));
			String userId = appNotice.getCreator();
			if (state.equals("3")) {//3-原文链接
				StringBuilder stringHtml = new StringBuilder();
				Date          dtnow      = new Date();
				//打开文件
				String   rootPath = FileUploadUtils.getATTACHMENT_ROOT();
				Calendar cal      = Calendar.getInstance();
				String   htmlPath = "/" + cal.get(Calendar.YEAR) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DAY_OF_MONTH);
				File     file     = new File(rootPath + htmlPath);
				if (!file.exists()) {
					file.mkdirs();
				}
				PrintStream printStream = new PrintStream(new FileOutputStream(rootPath + htmlPath + "/" + dtnow.getTime() + ".html"));
				//输入HTML文件内容
				stringHtml.append("<html><head>");
				stringHtml.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
				stringHtml.append("<title>消息通知</title>");
				stringHtml.append("</head>");
				stringHtml.append("<body>");
				stringHtml.append(appNotice.getContent());
				stringHtml.append("</body></html>");

				//将HTML文件内容写入文件中
				printStream.println(stringHtml.toString());
				String url=hostUrl + htmlPath + "/" + dtnow.getTime() + ".html";
				appNotice.setUrl_address(url.replaceAll(CodeConstants.HTTPS, "").replaceAll(CodeConstants.HTTP, ""));
				appNoticeManager.updateModel(appNotice);
				printStream.close();

				resMap.put("code", 200);
				resMap.put("msgStr", "");
				resMap.put("data", appNotice);
				resMap.put("bugCount", count);
				resMap.put("msg", "发布成功");
				return resMap;
			}
			//生成成功后才去改变值
			//当状态为审核通过且是公告的时候需要判断有没有公众号推送，有的话就调用公众号推送相关信息
			if ("1".equals(state) && 1 == appNotice.getNoticeType().intValue() && appNotice.getIsPublic() != null && 1 == appNotice.getIsPublic().intValue()) {
//					noticePublicnoService.saveImages(appNotice, user);
				//新增图片压缩素材相关处理
				//新增素材
				//发送素材
				log.info("-------------uploadnews begin---------------");
				Map<String, Object> map  = uploadnews(appNotice, user);
				log.info("-------------uploadnews end---------------map:/n{}",JsonUtils.toJson(map));
				int                 code = Integer.parseInt(map.get("code").toString());
				if (200 != code) {
					resMap.put("msgStr", "发布失败：" + map.get("msgStr"));
					resMap.put("bugCount", Integer.parseInt(map.get("bugCount").toString()));
					resMap.put("msg", "发布失败");
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return resMap;
				}
			}
			if (count > 0) {
				resMap.put("msgStr", "发布失败");
				resMap.put("bugCount", count);
				resMap.put("msg", "发布失败");
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return resMap;
			}
			appNotice.setIsEnabled(isEnabled);
			appNoticeManager.updateModel(appNotice);
			//推送消息type==1代表pc端审核type=2代表app端
			if (type == 1 && appNotice.getContentType() != 4) {
				push(appNotice, state, userId);
			} else {
				push(appNotice, state, userId);
			}
			
			resMap.put("code", 200);
			resMap.put("msgStr", "");
			resMap.put("data", appNotice);
			resMap.put("bugCount", count);
			resMap.put("msg", "发布成功");
			return resMap;
		} catch (Exception e) {
			log.error(e.getMessage());
			resMap.put("msgStr", "发布失败：" + e.getMessage());
			resMap.put("bugCount", count);
			resMap.put("msg", "发布失败");
			resMap.put("code", 500);
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			throw new Exception();
		}
	}

	@Async
	public void push(AppNoticeModel appNotice, String state, String userId) throws Exception {
		//推送消息 (公告类型不为商圈发现banner时进行推送)
		List<User> users = new ArrayList<User>();
		User       user2 = userManager.get(Long.parseLong(userId));
		users.add(user2);

		String pathUrl = hostUrl + wxAppNoticeUrl.replace("@id", appNotice.getId().toString());
		if (state.equals("1")) {
			appNoticeManager.pushMessage(Long.parseLong(appNotice.getId().toString()), CodeConstants.APP_NOTICE_PUSH_CODE, pathUrl, "您发起的公告已审核通过", "已审核通过", users);
		}

		if ("2".equals(state)) {
			appNoticeManager.pushMessage(Long.parseLong(appNotice.getId().toString()), CodeConstants.APP_NOTICE_PUSH_CODE, pathUrl, "您发起的公告已被驳回", "未审核通过", users);
		}
	}

	@Override
	public AppResultDto importUserInfo(String orgId, InputStream ins, String developId)
			throws Exception {
		Map<String, Object> retMap   = importUser(ins, orgId, developId);
		int                 bugCount = Integer.parseInt(retMap.get("bugCount").toString());
		if (bugCount > 0) {//出现错误时
			//出现失败时，可将返回的名单设置进页面，给出提示失败信息，但不做异常处理
			return AppResultUtil.createCommonDto("300", retMap.get("bugStr").toString(), retMap.get("list"));
		} else {
			return AppResultUtil.createSuccesDto("导入成功", retMap.get("list"));
		}
	}


	/**
	 * 读取excel，然后查找excel中对应的用户信息
	 *
	 * @param ins
	 * @param orgId
	 * @return
	 */
	public Map<String, Object> importUser(InputStream ins, String orgId, String developId) {
		Map<String, Object>    retMap   = new HashMap<String, Object>();
		List<NoticeUserOutDto> list     = new ArrayList<NoticeUserOutDto>();
		List<String>           mobils   = new ArrayList<String>();
		int                    bugCount = 0;
		StringBuffer           bugStr   = new StringBuffer();
		StringBuffer           countStr = new StringBuffer();
		Sheet                  sheet    = null;

		try {
			Workbook workbook = WorkbookFactory.create(ins);
			sheet = workbook.getSheet("NoticeUser");
		} catch (Exception e) {
			bugCount++;
			bugStr.append("模板格式有问题，请下载最新的模板");
		}
		try {
			if (sheet == null) {
				bugCount++;
				bugStr.append("模板格式有问题，请下载最新的模板");
			} else {
				int rows = sheet.getLastRowNum();
				//如果大于2000行数据
				if (rows > 20000) {
					bugCount++;
					bugStr.append("数据量太大，不能大于2w行");
				} else if (rows < 1) {
					bugCount++;
					bugStr.append("数据为空，请录入账单信息");
				} else {
					for (int i = 1; i <= rows; i++) {
						if (sheet.getRow(i) == null) {
							continue;
						}
						if (sheet.getRow(i).getCell(0) == null) {
							bugStr.append("第" + i + "行第1列数据有问题，请检查，问题：手机号码必填，请导出系统模板匹配录入<br/>");
							bugCount++;
							continue;
						}
						sheet.getRow(i).getCell(0).setCellType(Cell.CELL_TYPE_STRING);
						if (StringUtils.isBlank(sheet.getRow(i).getCell(0).getStringCellValue())) {
							bugStr.append("第" + i + "行第1列数据有问题，请检查，问题：手机号码必填，请导出系统模板匹配录入<br/>");
							bugCount++;
							continue;
						}
						String  mobile = sheet.getRow(i).getCell(0).getStringCellValue();
						boolean bool   = RegularPattern.isMobileNO(mobile);//验证手机格式是否正确
						if (StringUtils.isNotEmpty(mobile) && !bool) {
							bugStr.append("第" + i + "行第1列数据有问题，请检查，问题：" + mobile + "手机号码格式有问题，请导出系统模板匹配录入<br/>");
							bugCount++;
							continue;
						}
						if (mobils.contains(mobile)) {
							bugStr.append("第" + i + "行第1列数据有问题，请检查，问题：手机号码为" + mobile + "，在该表格中已存在，请导出系统模板匹配录入<br/>");
							bugCount++;
							continue;
						}
						AppUser userInfo = appUserManager.getAppUsersByPhoneAndOrg(mobile, Integer.parseInt(orgId));
						if (null == userInfo) {
							bugStr.append("第" + i + "行第1列数据有问题，请检查，问题：手机号码为" + mobile + "，在该项目下未找到白名单用户，请导出系统模板匹配录入<br/>");
							bugCount++;
							continue;
						}

						Integer wxUserId = userInfo.getWxUserId();
						if (null == wxUserId) {
							bugStr.append("第" + i + "行第1列数据有问题，请检查，问题：手机号码为" + mobile + "，该号码无openId，请导出系统模板匹配录入<br/>");
							bugCount++;
							continue;
						}
						if (!scWxuserManager.exists(wxUserId)) {
							bugStr.append("第" + i + "行第1列数据有问题，请检查，问题：手机号码为" + mobile + "，该号码无openId，请导出系统模板匹配录入<br/>");
							bugCount++;
							continue;
						}
						WxUser wxUser = scWxuserManager.get(wxUserId);
						if (null == wxUser || StringUtils.isBlank(wxUser.getOpenId())) {
							bugStr.append("第" + i + "行第1列数据有问题，请检查，问题：手机号码为" + mobile + "，该号码无openId，请导出系统模板匹配录入<br/>");
							bugCount++;
							continue;
						}

						if (!developId.equals(wxUser.getDevelopId())) {
							bugStr.append("第" + i + "行第1列数据有问题，请检查，问题：手机号码为" + mobile + "，该手机号目前登录的公众号并不是该项目所关联的公众号，请导出系统模板匹配录入<br/>");
							bugCount++;
							continue;
						}
						NoticeUserOutDto dto = new NoticeUserOutDto();
						dto.setId(userInfo.getId().toString());
						dto.setName(userInfo.getUserName());
						dto.setMobile(mobile);
						if (null != userInfo.getVirtualArchId() && virtualArchManager.exists(userInfo.getVirtualArchId())) {
							VirtualArchitecture virt = virtualArchManager.get(userInfo.getVirtualArchId());
							if (null != virt) {
								dto.setVirtName(virt.getName());
							}
						}
						list.add(dto);
						mobils.add(mobile);

					}
				}
			}
			retMap.put("bugCount", bugCount);
			retMap.put("countStr", countStr);
			retMap.put("bugStr", bugStr.toString());
			retMap.put("list", list);
			retMap.put("okCount", list.size());
			return retMap;

		} catch (Exception e) {
			log.error(e.getMessage());
			bugCount++;
			bugStr.append(e.getMessage());
			retMap.put("bugCount", bugCount);
			retMap.put("countStr", countStr);
			retMap.put("bugStr", bugStr.toString());
			retMap.put("list", list);
			retMap.put("okCount", list.size());
			e.printStackTrace();
			return retMap;
		}
	}

	/**
	 * 推送消息给下一级审核的角色对应的人     肯定是多级审批的才会进来
	 */
	@Override
	public List<User> getPushMsgUserById(Integer approvalTypeId,Integer orgId,Integer type,Integer id) {
		//审核类型id
		if(null == approvalTypeId || 0 == approvalTypeId.intValue()){
			return null;
		}
		//778,1,2,13,160
		Map<String,Object> roleMap=noticeApprovalsetManager.getRoleIdByOrderId(orgId, CodeConstants.APPROVAL_TYPE_NOTICE,type, approvalTypeId, id);
		if(null == roleMap || !roleMap.containsKey("roleId") || null == roleMap.get("roleId") || StringUtils.isBlank(roleMap.get("roleId").toString())){
			return null;
		}
		
		String roleId=roleMap.get("roleId").toString();
		if(StringUtils.isBlank(roleId)){
			return null;
		}
		log.info("getPushMsgUserById-roleId:"+roleId);
		List<User> users=noticeApprovalsetManager.getAppUserByRoleId(roleId);
		if(CollectionUtils.isEmpty(users)){
			return null;
		}
		return users;
	}

	/**
	 * 推送模板消息给所有粉丝
	 */
	@Async
	public void sendTemplateMsgByWxUser(String orgIds,String title,String url,List<String> openIds) {
		log.info("发布公告-发布模板消息-sendTemplateMsgByWxUser-orgIds:{},title:{};url:{}",orgIds,title,url);
		String[] orgArr = orgIds.split(",");
		for (int i = 0; i < orgArr.length; i++) {
			Integer orgId     = Integer.parseInt(orgArr[i]);
			WxPublicno wxPub=wxPubManager.getPublicByOrgId(orgId.toString());
			log.info("发布公告-发布模板消息-sendTemplateMsgByWxUser-wxPub:{}",JsonUtils.toJson(wxPub));
			if(null == wxPub || null == wxPub.getTemplateId() || !StringUtil.isNotEmpty(wxPub.getTemplateId())){
				return;
			}
//			List<WxUserDto> list=scWxuserManager.getWxUserByDevelopId(wxPub.getDevelopId());
//			log.info("发布模板消息给所有粉丝-sendTemplateMsgByWxUser-list:{}",JsonUtils.toJson(list));
//			if(CollectionUtils.isEmpty(list)){
//				return;
//			}
			String content="";
			if(StringUtil.isNotEmpty(title)){
				content="新发布了公告《"+title+"》,请注意查看！";
			}else{
				content="新发布了公告,请注意查看！";
			}
			int sumCount=openIds.size();
			int successCount=0;
			log.info("发布模板消息给所有粉丝-sendTemplateMsgByWxUser1-sumCount:{},successCount:{}",sumCount,successCount);
			int k = 1;
			for(String openId:openIds){
				if(k % 200 == 0){
					try {
						log.info("k:"+k+"--------------------休眠1秒--------------------------2");
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						log.info("休眠异常2:{}",e.getMessage());
					}
				}
				i++;
				//String res=weChatApiManager.sendTemplateMsg12("o9oSq0wFGYb630NECvzTiUbDapGM", "huJFx12IsqqJSMQOJoKmi6df68a5ElgSkZFM", url, content,"gh_bb8ab88fc77a", "");
				String res=weChatApiManager.sendTemplateMsg12(openId, wxPub.getTemplateId(), url, content, wxPub.getDevelopId(), "");
				if("success".equals(res)){
					successCount++;
				}
			}
			log.info("发布模板消息给所有粉丝-sendTemplateMsgByWxUser2-sumCount:{},successCount:{}",sumCount,successCount);
		}
	}
	
	/**
	 * 获取微信公众号下所有的粉丝
	 * List  openid;
	 */
	@Override
	public List<String> getWxPublicUser(String developId){
		log.info("getWxPublicUser-developId:{};",developId);
		String access_token="";
		try {
			access_token = weChatApiManager.getAccessToken(developId);
			log.info("getWxPublicUser-developId:{};-access_token:{}",developId,access_token);
		} catch (Exception e) {
			e.printStackTrace();
			log.info("getWxPublicUser-developId:{};获取失败:{}",developId,e.getMessage());
			return null;
		}
		if(StringUtils.isBlank(access_token)){
			return null;
		}
		List<String> list=new ArrayList<String>();
		try {
			list = WeiXinHelper.getUserList(access_token);
		} catch (Exception e) {
			e.printStackTrace();
			log.info("getWxPublicUser-developId:{};获取失败:{}",developId,e.getMessage());
			return null;
		}
		if(CollectionUtils.isEmpty(list)){
			return null;
		}
		log.info("getWxPublicUser-developId:{};-list.size:{}",developId,list.size());
		return list;
	}

	
	/**
	 * 发送公告-获取发送模板消息的用户
	 */
	@Override
	public Map<String, Object> getSentWxTempMsg(AppNoticeModel appNotice) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", 500);
		List<String> openIds=new ArrayList<String>();
		if(null == appNotice.getPublicObj()){
			map.put("msg", "发布公告-模板消息时：发布对象为空");
			return map;
		}
		Map<String,NoticeWxTempVo> openIdMap=new HashMap<String, NoticeWxTempVo>();
		//挨个项目的发送
		String orgIds ="";
		if (StringUtil.isNotEmpty(appNotice.getOrgIds())) {
			orgIds = appNotice.getOrgIds();
		} else {
			orgIds = appNotice.getOrgId().toString();
		}
		String[] orgArr = orgIds.split(",");
		if (null == orgArr || orgArr.length <= 0) {
				map.put("msg", "发布公告-模板消息时：项目为空");
				return map;
		}
		List<String> developIds=new ArrayList<String>();
		int count=0;
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < orgArr.length; i++) {
			Integer orgId     = Integer.parseInt(orgArr[i]);
			WxPublicno no = wxPubManager.getPublicByOrgId(orgId.toString());
			if (null == no) {
				count++;
				sb.append("orgId:" + orgArr[i] + ";sourceId:" + appNotice.getId() + ";该项目下的该订单上找不到公众号");
				continue;
			}
			String  developId = no.getDevelopId();
			if (StringUtils.isEmpty(developId)) {
				count++;
				sb.append("orgId:" + orgArr[i] + ";sourceId:" + appNotice.getId() + ";该项目下的该订单上找不到developId");
				continue;
			}
			
			if (StringUtils.isEmpty(no.getTemplateId())) {
				count++;
				sb.append("orgId:" + orgArr[i] + ";sourceId:" + appNotice.getId() + ";该项目下的该订单上找不到templateId");
				continue;
			}
			developIds.add(developId);
			if(openIdMap.containsKey(developId)){
				NoticeWxTempVo vo=openIdMap.get(developId);
				openIds=vo.getOpenIds();
				if(1 == appNotice.getPublicObj().intValue()){
					//公众号下所有用户
//					openIds.addAll(getWxPublicUser(developId));
				}else if(2 == appNotice.getPublicObj().intValue()){
					//项目下所有登录过的用户
					openIds.addAll(getOpenIds(orgArr[i], 1));
				}if(3 == appNotice.getPublicObj().intValue()){
					//项目下部分用户
					openIds.addAll(getOpenIds(appNotice.getOpenIds(), 2));
				}if(4 == appNotice.getPublicObj().intValue()){
					//部门分组用户
					openIds.addAll(getOpenIds(appNotice.getOpenIds(), 2));
				}
				vo.setOpenIds(openIds);
				openIdMap.put(developId, vo);
			}else{
				NoticeWxTempVo vo=new NoticeWxTempVo();
				vo.setDevelopId(developId);
				vo.setTemplateId(no.getTemplateId());
				if(1 == appNotice.getPublicObj().intValue()){
					//公众号下所有用户
					openIds=getWxPublicUser(developId);
				}else if(2 == appNotice.getPublicObj().intValue()){
					//项目下所有登录过的用户
					openIds=getOpenIds(orgArr[i], 1);
					
				}if(3 == appNotice.getPublicObj().intValue()){
					//项目下部分用户
					openIds=getOpenIds(appNotice.getOpenIds(), 2);
				}if(4 == appNotice.getPublicObj().intValue()){
					//部门分组用户
					openIds.addAll(getOpenIds(appNotice.getOpenIds(), 2));
				}
				vo.setOpenIds(openIds);
				openIdMap.put(developId, vo);
			}
		}
		if(count > 0){
			map.put("msg", "发布公告-模板消息时："+sb.toString());
			return map;
		}
		if(CollectionUtils.isEmpty(developIds)){
			map.put("msg", "发布公告-模板消息时：发布的公众号为空");
			return map;
		}
		if(CollectionUtils.isEmpty(openIds)){
			map.put("msg", "发布公告-模板消息时：发布的用户为空");
			return map;
		}
		List<NoticeWxTempVo> list=new ArrayList<NoticeWxTempVo>();
		List<String> newDevelopIds=new ArrayList<String>(new TreeSet<String>(developIds));
		for(String developId : newDevelopIds){
			NoticeWxTempVo vo=openIdMap.get(developId);
			list.add(vo);
		}
		//openId去重
		map.put("msg", "成功");
		map.put("code", 200);
		map.put("data", list);
		return map;
	}
	
	/**
	 * 发布公告-发送模板消息
	 */
	@Async
	public void sendTemplateMsgByWxUser(List<NoticeWxTempVo> list, String url,String content) {
		log.info("发布公告-发布模板消息-发送接口-sendTemplateMsgByWxUser1-url:{}-content:{}；开始时间:{};{}",url,content,DateHelper.formatDate(new Date(), DateHelper.DATE_TIME_STRING),System.currentTimeMillis());
		for(NoticeWxTempVo vo:list){
			int sumCount=vo.getOpenIds().size();
			int successCount=0;
			log.info("发布公告-发布模板消息-发送接口-sendTemplateMsgByWxUser1-developId:{}-sumCount:{},successCount:{}",vo.getDevelopId(),sumCount,successCount);
			int i = 1 ;
			for(String openId:vo.getOpenIds()){
				String linkUrl=url;
				if(StringUtils.isNotEmpty(url)){
					linkUrl=linkUrl+"&openId="+openId;
				}
				log.info("sendTemplateMsgByWxUser1-linkUrl:{}",linkUrl);
				if(i % 200 == 0){
					try {
						log.info("i:"+i+"--------------------休眠1秒--------------------------1");
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						log.info("休眠异常:{}",e.getMessage());
					}
				}
				i++;
				String res=weChatApiManager.sendTemplateMsg12(openId, vo.getTemplateId(), linkUrl, content, vo.getDevelopId(), "");
				if("success".equals(res)){
					successCount++;
				}
			}
			log.info("发布公告-发布模板消息-发送接口-sendTemplateMsgByWxUser2-developId:{}-sumCount:{},successCount:{};结束时间:{};{}",vo.getDevelopId(),sumCount,successCount,DateHelper.formatDate(new Date(), DateHelper.DATE_TIME_STRING),System.currentTimeMillis());
		}
	}

	public static List<Map<String, Object>> toListMap(String json){
		List<Object> list =JSON.parseArray(json);
		List< Map<String,Object>> listw = new ArrayList<Map<String,Object>>();
		for (Object object : list){
			Map<String,Object> ageMap = new HashMap<String,Object>();
			Map <String,Object> ret = (Map<String, Object>) object;//取出list里面的值转为map
			listw.add(ret);
		}
		return listw;
	}

	public 	List<DeptUserVo> getDeptUser(Integer type,Integer id,Integer orgId){
		List<DeptGroupDto> dtoList=noticeSubGroupManager.getDeptGroupDto(type, id);
		DeptGroupVo deptGroupVo=new DeptGroupVo();
		deptGroupVo.setOrgId(orgId);
		deptGroupVo.setList(dtoList);
		List<DeptUserVo>	deptUserVos=appNoticeManager.getDeptGroupUserListByOrgId(deptGroupVo);
		return  deptUserVos;
	}

	@Override
	public void saveNoticeRecord(AppNoticeModel appNotice) {
		List<NoticeRecordVo> list=new ArrayList<NoticeRecordVo>();
		Map<String,NoticeRecordVo> openIdMap=new HashMap<String, NoticeRecordVo>();
		//挨个项目的发送
		String orgIds ="";
		if (StringUtil.isNotEmpty(appNotice.getOrgIds())) {
			orgIds = appNotice.getOrgIds();
		} else {
			orgIds = appNotice.getOrgId().toString();
		}
		if(null != appNotice.getPublicObj() && 2 == appNotice.getPublicObj().intValue()){
			//项目下所有登录过的用户
			List<Map<String,Object>> mapList=appUserManager.getAllUserByOrgIds(orgIds,"","");
			NoticeRecordVo vo=new NoticeRecordVo();
			vo.setOrgIds(orgIds);
			vo.setUserList(mapList);
			list.add(vo);
		}else if(null != appNotice.getPublicObj() && 3 == appNotice.getPublicObj().intValue()) {
			if (null != appNotice.getUserIds() && StringUtils.isNotEmpty(appNotice.getUserIds())) {
				//项目下所有登录过的用户
				List<Map<String, Object>> mapList = appUserManager.getAllUserByOrgIds(orgIds, appNotice.getUserIds(), "");
				NoticeRecordVo vo = new NoticeRecordVo();
				vo.setOrgIds(orgIds);
				vo.setUserList(mapList);
				list.add(vo);
			}
		}else if(null != appNotice.getPublicObj() &&  4 == appNotice.getPublicObj().intValue()){
			if (null != appNotice.getUserIds() && StringUtils.isNotEmpty(appNotice.getUserIds())) {
				//项目下所有登录过的用户
				List<Map<String, Object>> mapList = appUserManager.getAllUserByOrgIds(orgIds, appNotice.getUserIds(), "");

				NoticeRecordVo vo = new NoticeRecordVo();
				vo.setOrgIds(orgIds);
				vo.setUserList(mapList);
				list.add(vo);
			}
		}else if(null != appNotice.getPublicObj() && 1 == appNotice.getPublicObj().intValue()){
			/*
			// 全量粉丝推送时，不记录推送具体用户 2022-2-18
			String[] orgArr = orgIds.split(",");
			List<String> developIds=new ArrayList<String>();
			for (int i = 0; i < orgArr.length; i++) {
				Integer orgId     = Integer.parseInt(orgArr[i]);
				WxPublicno no = wxPubManager.getPublicByOrgId(orgId.toString());
				if (null == no) {
					continue;
				}
				String  developId = no.getDevelopId();
				if (StringUtils.isEmpty(developId)) {
					continue;
				}
				
				developIds.add(developId);
				if(openIdMap.containsKey(developId)){
					continue;
				}else{
					NoticeRecordVo vo=new NoticeRecordVo();
					vo.setDevelopId(developId);
					//公众号下所有用户
					List<String> openIds=getWxPublicUser(developId);
					if(!CollectionUtils.isEmpty(openIds)){
						vo.setSumOpenids(openIds);
						vo.setSumCount(openIds.size());
						List<Map<String,Object>> mapList=appUserManager.getAllUserByOrgIds(orgIds,appNotice.getUserIds(),"");
						vo.setUserList(mapList);
					}
					openIdMap.put(developId, vo);
				}
			}
			List<String> newDevelopIds=new ArrayList<String>(new TreeSet<String>(developIds));
			for(String developId : newDevelopIds){
				NoticeRecordVo vo=openIdMap.get(developId);
				list.add(vo);
			}
			*/
		}
		
		if(!CollectionUtils.isEmpty(list)){
			appNoticeRecordManager.saveOrUpdateAppNoticeRecordModel(list,appNotice.getId(),appNotice.getPublicObj().intValue());
			if(null != appNotice.getPublicObj() && 1 == appNotice.getPublicObj().intValue()){
				///baseRedisService.set(CodeConstants.NOTICE_REDIS_ORDERID+appNotice.getId(), JSON.toJSONString(list));
			}else if(null != appNotice.getPublicObj() && 4 == appNotice.getPublicObj().intValue() && null != appNotice.getOrgId()){
				NoticeRecordVo vo=list.get(0);
				log.info("saveNoticeRecordaa{}",JsonUtils.toJson(vo));
				if(vo.getUserList()!=null && vo.getUserList().size()>0){
					StringBuilder sb=new StringBuilder("");
					for (Map<String, Object> map : vo.getUserList()) {
						if(null == map.get("openId") || StringUtils.isEmpty(map.get("openId").toString())){
							continue;
						}
						sb.append(map.get("openId")).append(",");
					}

					String openIds="";
					if(StringUtils.isNotEmpty(sb.toString())){
						openIds=sb.substring(0,sb.length()-1);
					}
					appNotice.setOpenIds(openIds);
					log.info("openIds{},sb{}",openIds,sb.toString());
					appNoticeManager.saveOrUpdateAppNoticeModel(appNotice);
				}

			}
			
		}
	}
}
