package com.palmnest.service.notice.impl;

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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.core.util.DateHelper;
import com.palmnest.application.core.util.HttpKit;
import com.palmnest.application.core.util.PropertiesKit;
import com.palmnest.application.core.util.PushMessageHelper;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.application.dto.DeptGroupDto;
import com.palmnest.application.dto.DeptGroupVo;
import com.palmnest.application.dto.DeptUserVo;
import com.palmnest.application.dto.UserTokenDto;
import com.palmnest.application.dto.input.AppNoticeDetailDto;
import com.palmnest.application.dto.output.AuditDto;
import com.palmnest.application.dto.output.NoticeDto;
import com.palmnest.dao.OrganizationDao;
import com.palmnest.dao.RoleDao;
import com.palmnest.dao.UserDao;
import com.palmnest.dao.notice.AppNoticeContentDao;
import com.palmnest.dao.notice.AppNoticeDao;
import com.palmnest.dao.notice.AppNoticeDetailDao;
import com.palmnest.model.Role;
import com.palmnest.model.User;
import com.palmnest.model.estateserve.WxPublicno;
import com.palmnest.model.notice.AppNoticeContentModel;
import com.palmnest.model.notice.AppNoticeDetailModel;
import com.palmnest.model.notice.AppNoticeModel;
import com.palmnest.model.notice.NoticeApprovalTypeModel;
import com.palmnest.service.impl.GenericManagerImpl;
import com.palmnest.service.notice.AppNoticeManager;
import com.palmnest.service.notice.NoticeApprovalsetManager;
import com.palmnest.service.notice.NoticeSubGroupManager;
import com.palmnest.service.notice.WxPubManager;
import com.palmnest.service.redis.BaseRedisService;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Slf4j
@Service("appNoticeManager")
public class AppNoticeManagerImpl extends GenericManagerImpl<AppNoticeModel, Integer> implements AppNoticeManager {

	@Autowired
	private UserDao             userDao;
	@Autowired
	private RoleDao             roleDao;
	@Autowired
	private OrganizationDao     organizationDao;
	private AppNoticeDao        appNoticeDao;
	@Autowired
	private AppNoticeDetailDao  appNoticeDetailDao;
	@Autowired
	private AppNoticeContentDao appNoticeContentDao;
	@Autowired
	private NoticeApprovalsetManager noticeApprovalsetManager;
	
	@Autowired
    private BaseRedisService baseRedisService;
	@Autowired
	private NoticeSubGroupManager noticeSubGroupManager;

	@Autowired
	private WxPubManager wxPubManager;
	
	public static       String deptGroupUserUrl               = PropertiesKit.readPropertiesValue("deptGroupUser", "wechat.properties");
	
	public static       String deptGroupUserListUrl               = PropertiesKit.readPropertiesValue("deptGroupUserList", "wechat.properties");

	@Autowired
	public void setRoomInfoDao(AppNoticeDao appNoticeDao) {
		this.appNoticeDao = appNoticeDao;
		this.dao = appNoticeDao;
	}

	@Override
	public Page getDataList(Map<String, Object> map, int pageNo, int pageSize) throws Exception {
		Page page=appNoticeDao.getDataList(map, pageNo, pageSize);
		List<Map<String, Object>> list=page.getItems();
		if(CollectionUtils.isEmpty(list)){
			return page;
		}
		String roleIds="";
		if(map.containsKey("roleIds") && null != map.get("roleIds") && StringUtils.isNotBlank(map.get("roleIds").toString())){
			roleIds=map.get("roleIds").toString();
		}
		if(StringUtils.isBlank(roleIds)){
			return page;
		}
		String [] roleArr=roleIds.split(",");
		if(null == roleArr || roleArr.length<=0 ){
			return page;
		}
		List<String> roleList = new ArrayList<>();
		roleList = Arrays.asList(roleArr);
		log.info("getDataList-roleList:{}",JsonUtils.toJson(roleList));
		for(int i=0;i<list.size();i++){
			Map<String, Object> resMap=list.get(i);
			resMap.put("isPublish", 0);
			Integer id=null;
			if(resMap.containsKey("id") && null != resMap.get("id") && StringUtils.isNotBlank(resMap.get("id").toString())){
				id=Integer.parseInt(resMap.get("id").toString());
			}
			if(null == id){
				continue;
			}
			
			Integer orgId=null;
			if(resMap.containsKey("orgId") && null != resMap.get("orgId") && StringUtils.isNotBlank(resMap.get("orgId").toString())){
				orgId=Integer.parseInt(resMap.get("orgId").toString());
			}
			//项目为空时不执行多审批相关的数据
			if(null == orgId){
				continue;
			}
			
			
			Integer approvalTypeId=null;
			if(resMap.containsKey("approvalType") && null != resMap.get("approvalType") && StringUtils.isNotBlank(resMap.get("approvalType").toString())){
				approvalTypeId=Integer.parseInt(resMap.get("approvalType").toString());
			}
			
			Integer state=null;
			if(resMap.containsKey("state") && null != resMap.get("state") && StringUtils.isNotBlank(resMap.get("state").toString())){
				state=Integer.parseInt(resMap.get("state").toString());
			}
			//非未审核状态的直接返回，不需要判断
			if(null != state && 0 == state.intValue()){
				//不为空说明该项目设置了多级审核权限,则需要判断当前登录的人是否有审核权限
				if(null != approvalTypeId && 0 != approvalTypeId.intValue()){
					Map<String,Object> roleMap=noticeApprovalsetManager.getRoleIdByOrderId(orgId, CodeConstants.APPROVAL_TYPE_NOTICE,CodeConstants.ORDER_TYPE_NOTICE, approvalTypeId, id);
					String roleId="";
					if(roleMap.containsKey("roleId") && null != roleMap.get("roleId") && StringUtils.isNotBlank(roleMap.get("roleId").toString())){
						roleId=roleMap.get("roleId").toString();
						log.info("单据：{}；当前审核角色:{}",id,roleId);
					}
					String roleName=roleMap == null ? "" : roleMap.get("roleName") == null ? "" : roleMap.get("roleName") .toString();
					resMap.put("roleId", roleId);
					resMap.put("roleName", roleName);
					//不为空则和当前登录的角色做比对,存在当前的角色中，订单状态为未审核，则代表有审核权限
					if(StringUtils.isNotBlank(roleId) && roleList.contains(roleId) && 0 == state.intValue()){
						resMap.put("isApproval", 1);
					}
				}else{
					resMap.put("isPublish",1);
				}
			}
		}
		return page;
	}



	@Override
	public Page getNewDataList(Map<String, Object> map, int pageNo, int pageSize)
			throws Exception {
		return appNoticeDao.getNewDataList(map, pageNo, pageSize);
	}

	@Override
	public AppNoticeModel getDataById(int id) throws Exception {

		return appNoticeDao.getDataById(id);
	}

	@Override
	public AppNoticeModel saveOrUpdateAppNoticeModel(AppNoticeModel appNotice) {

		String         isSuccess = "fail";
		AppNoticeModel model     = null;
		if (appNotice.getId() == null) {
			model = appNoticeDao.save(appNotice);
			if (model != null) {
				isSuccess = "success";
			}
		} else {
			try {
				appNoticeDao.updateObj(appNotice);
				isSuccess = "success";
			} catch (Exception e) {

				isSuccess = "fail";
			}
		}
		return model;
	}

	@Override
	public Integer getTotal(String orgIds) {
		return appNoticeDao.getTotal(orgIds);
	}

	@Async
	@Override
	public void pushMessage(Long id, String code, String url, String title, String content, List<User> users) throws Exception {
		PushMessageHelper helper=new PushMessageHelper();
		helper.pushMessage(id, code, url, users, title, content);
	}

	@Override
	public NoticeDto getDetailById(int id, int type,int from) throws Exception {
		long count=0;
		String noticeId="";
		if(2 == type){
			AppNoticeDetailModel model = appNoticeDetailDao.get(id);
			if (null == model) {
				return null;
			}
			AppNoticeModel notice = appNoticeDao.getDataById(model.getSourceId());
			if (null == notice) {
				return null;
			}
			noticeId=notice.getId().toString();
		}else if(1 == type){
			noticeId=id+"";
		}
		
		String key=CodeConstants.NOTICE_REDIS_TYPE_ORDERID+1+"_"+noticeId;
		String value=baseRedisService.get(key);
		if(StringUtils.isNotEmpty(value)){
			count=Long.parseLong(value);
		}
		if(1 == from){
			count=count+1;
			baseRedisService.set(key, count+"");
		}
		if (1 == type) {
			//拿总单据的详情
			AppNoticeModel notice = appNoticeDao.getDataById(id);
			if(1 == from && (notice.getNoticeType() == 1 && !notice.getIsEnabled().equals("2") && null != notice.getApproval_time())){
				throw new Exception();
			}
			if (null == notice) {
				return null;
			}
			int isViews=0;
			Integer orgId=null;
			if(null != notice.getOrgId()){
				orgId=notice.getOrgId();
			}else if(StringUtils.isNotEmpty(notice.getOrgIds())){
				String [] arr=notice.getOrgIds().split(",");
				if(null != arr && arr.length == 1 && StringUtils.isNotEmpty(arr[0])){
					orgId=Integer.parseInt(arr[0]);
				}
			}
			log.info("getDetailById-orgId1:{}",orgId);
			if(null != orgId){
				Map<String,Object> setMap=noticeApprovalsetManager.getSetByOrgId(orgId);
				log.info("getDetailById-setMap1:{}",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;
				}
			}
			NoticeDto noticeDto=convertToDto(notice);
			if(null != noticeDto){
				noticeDto.setViews(count);
				noticeDto.setIsViews(isViews);
			}
			if(noticeDto.getPublicObj()!=null && noticeDto.getPublicObj()==4){
				noticeDto.setDeptGroupJson(noticeSubGroupManager.getDeptGroupDto(1, id));
			}
			return noticeDto;
		} else {
			//拿分录单据的详情
			AppNoticeDetailModel model = appNoticeDetailDao.get(id);
			if (null == model) {
				return null;
			}
			AppNoticeModel notice = appNoticeDao.getDataById(model.getSourceId());
			if (null == notice) {
				return null;
			}

			int isViews=0;
			Integer orgId=null;
			if(null != notice.getOrgId()){
				orgId=notice.getOrgId();
			}else if(StringUtils.isNotEmpty(notice.getOrgIds())){
				String [] arr=notice.getOrgIds().split(",");
				if(null != arr && arr.length == 1 && StringUtils.isNotEmpty(arr[0])){
					orgId=Integer.parseInt(arr[0]);
				}
			}
			log.info("getDetailById-orgId2:{}",orgId);
			if(null != orgId){
				Map<String,Object> setMap=noticeApprovalsetManager.getSetByOrgId(orgId);
				log.info("getDetailById-setMap2:{}",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;
				}
			}
			NoticeDto noticeDto=convertToDto(notice, model);
			if(null != noticeDto){
				noticeDto.setViews(count);
				noticeDto.setIsViews(isViews);
			}
			noticeDto.setDeptGroupJson(noticeSubGroupManager.getDeptGroupDto(1, id));
			return noticeDto;
		}
	}

	@Override
	public List<NoticeDto> finByType(Integer noticeType, String positionType, String orgIds) {
		List<AppNoticeModel> list = appNoticeDao.getByType(noticeType, positionType, orgIds);
		List<NoticeDto>      dtos = new ArrayList<NoticeDto>();
		for (AppNoticeModel model : list) {
			dtos.add(this.convertToDto(model));
//			List<AppNoticeDetailModel>  detailModelList=appNoticeDetailDao.getNoticeDetail(model.getId());
//			//新的单据都会在这个表中生成一条数据
//			if(detailModelList!=null&&detailModelList.size()>0){
//				for(AppNoticeDetailModel detailModel:detailModelList){
//					dtos.add(this.convertToDto(model,detailModel));
//				}
//			}
//			else{
//				//老的单据就还是获取原有的值
//				dtos.add(this.convertToDto(model));
//			}
		}
		return dtos;
	}

	private NoticeDto convertToDto(AppNoticeModel notice, AppNoticeDetailModel detailModel) {
		String content = getContentInfo(detailModel.getContent(), 2, detailModel.getId());
		NoticeDto dto = new NoticeDto(detailModel.getId(), detailModel.getTitle(), content, detailModel.getContentTxt(),
				notice.getUrl_address(), notice.getState(), notice.getNoticeType(), notice.getContentType(), detailModel.getCoverUrl(), detailModel.getSummaryInfo());
		dto.setApprovalUser(notice.getApproval_user());
		dto.setApprovalTime(notice.getApproval_time() == null ? null : DateHelper.toDateTimeString(notice.getApproval_time()));
		//格式化时间
		dto.setCreateTime(detailModel.getCreateTime() == null ? null : DateHelper.toDateTimeString(detailModel.getCreateTime()));
		User user = null;
		try {
			user = userDao.get(Long.parseLong(detailModel.getCreator()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
//		//当前登录的人的角色id
//		String roleIds       = getRoleIds(user);
//		int isApproval=0;
//		String [] roleArr=roleIds.split(",");
//		if(null != roleArr && roleArr.length > 0 ){
//			List<String> roleList = new ArrayList<>();
//			roleList = Arrays.asList(roleArr);
//			//非未审核状态的直接返回，不需要判断
//			if(null != notice && null != notice.getState() && 0 == notice.getState().intValue()){
//				//不为空说明该项目设置了多级审核权限,则需要判断当前登录的人是否有审核权限
//				if(null != notice.getApprovalType() && 0 != notice.getApprovalType().intValue()){
//					Map<String,Object> roleMap=noticeApprovalsetManager.getRoleIdByOrderId(notice.getOrgId(), CodeConstants.APPROVAL_TYPE_NOTICE,CodeConstants.ORDER_TYPE_NOTICE, notice.getApprovalType(), notice.getId());
//					String roleId="";
//					if(roleMap.containsKey("roleId") && null != roleMap.get("roleId") && StringUtils.isNotBlank(roleMap.get("roleId").toString())){
//						roleId=roleMap.get("roleId").toString();
//					}
//					//不为空则和当前登录的角色做比对,存在当前的角色中，订单状态为未审核，则代表有审核权限
//					if(StringUtils.isNotBlank(roleId) && roleList.contains(roleId)){
//						isApproval=1;
//					}
//				}
//			}
//		}
//		dto.setIsApproval(isApproval);


		Integer publicId = null;
		if(null != notice.getOrgId()){
			WxPublicno wxPublicno = wxPubManager.getPublicByOrgId(notice.getOrgId().toString());
			if(null != wxPublicno){
				publicId = wxPublicno.getId();
				dto.setDevelopid(wxPublicno.getDevelopId());
				dto.setPublicId(publicId);
			}
		}
		if(null != publicId && StringUtils.isNotEmpty(dto.getUrlAddress()) && -1 == dto.getUrlAddress().indexOf("publicId=")){
			if(-1 == dto.getUrlAddress().indexOf("?")){
				dto.setUrlAddress(dto.getUrlAddress()+"?publicId="+publicId);
			}else{
				dto.setUrlAddress(dto.getUrlAddress()+"&publicId="+publicId);
			}
		}

		dto.setCreator(user == null ? user.getUsername() : user.getFullName());
		dto.setModifier(notice.getModifier());
		dto.setModifyTime(notice.getModifyTime() == null ? null : DateHelper.toDateTimeString(notice.getModifyTime()));
		dto.setPositionType(notice.getPositionType());
		dto.setOrgId(notice.getOrgId());
		dto.setOrgIds(notice.getOrgIds());
		dto.setSourceType(2);
		dto.setSourceId(notice.getId());
		dto.setOpenIds(notice.getOpenIds());
		dto.setUserIds(notice.getUserIds());
		dto.setIsApp(notice.getIsApp());
		dto.setIsMessageList(notice.getIsMessageList());
		dto.setIsPublic(notice.getIsPublic());
		dto.setIsWechat(notice.getIsWechat());
		dto.setPublicObj(notice.getPublicObj());
		dto.setDetailList(getNoticeDetail(notice.getId()));
		dto.setApprovalType(notice.getApprovalType());
		dto.setIsPushTemplate(null == notice.getIsPushTemplate()? 0 : notice.getIsPushTemplate());
		String approvalTypeName="";
		if(null != notice.getApprovalType() && 0 != notice.getApprovalType().intValue()){
			NoticeApprovalTypeModel typeModel=noticeApprovalsetManager.findById(notice.getApprovalType());
			if(null != typeModel){
				approvalTypeName=typeModel.getName();
			}
		}
		
		dto.setApprovalTypeName(approvalTypeName);
		List<AuditDto> auditList=new ArrayList<AuditDto>();
		if(null != notice.getApprovalType() && 0 != notice.getApprovalType().intValue()){
			auditList=noticeApprovalsetManager.getAuditList(notice.getOrgId(), CodeConstants.ORDER_TYPE_NOTICE, notice.getId());
			dto.setAuditList(auditList);
		}else{
			if(null != dto.getApprovalTime() && StringUtils.isNotBlank(dto.getApprovalTime())){
				AuditDto auditDto=new AuditDto();
				auditDto.setApprovalTime(dto.getApprovalTime());
				auditDto.setApprovalOpinion("");
				if(null != dto.getState() && 1 == dto.getState().intValue()){
					auditDto.setApprovalResult(1);
				}else{
					auditDto.setApprovalResult(2);
				}
				auditDto.setApprovalUser(dto.getApprovalUser());
				auditList.add(auditDto);
			}
		}
		dto.setAuditList(auditList);
		return dto;
	}
	
	@Override
	public String getRoleIds(User user){
		String roleIds="";
		Set<Role> roles=user.getRoles();
		if(null != roles && roles.size()>0){
			StringBuilder sb=new StringBuilder("");
			for(Role role:roles){
				if(null == role || null == role.getId()){
					continue;
				}
				sb.append(role.getId()+",");
			}
			if(StringUtils.isNotBlank(sb.toString())){
				roleIds=sb.substring(0,sb.length()-1);
			}
		}
		return roleIds;
	}

	@Override
	public NoticeDto convertToDto(AppNoticeModel notice) {
		NoticeDto dto = new NoticeDto(notice.getId(), notice.getTitle(), notice.getContent(), notice.getContentTxt(),
				notice.getUrl_address(), notice.getState(), notice.getNoticeType(), notice.getContentType(), notice.getCoverUrl(), notice.getSummaryInfo());
		dto.setApprovalUser(notice.getApproval_user());
		dto.setApprovalTime(notice.getApproval_time() == null ? null : DateHelper.toDateTimeString(notice.getApproval_time()));
		//格式化时间
		dto.setCreateTime(notice.getCreateTime() == null ? null : DateHelper.formatDateToStr(DateHelper.parseToDate(notice.getCreateTime(), DateHelper.DATE_TIME_STRING)));
		User user = null;
		try {
			user = userDao.get(Long.parseLong(notice.getCreator()));
		} catch (Exception e) {
			e.printStackTrace();
		}

		Integer publicId = null;
		if(null != notice.getOrgId()){
			WxPublicno wxPublicno = wxPubManager.getPublicByOrgId(notice.getOrgId().toString());
			if(null != wxPublicno){
				publicId = wxPublicno.getId();
				dto.setDevelopid(wxPublicno.getDevelopId());
				dto.setPublicId(publicId);
			}
		}
		if(null != publicId && StringUtils.isNotEmpty(dto.getUrlAddress()) && -1 == dto.getUrlAddress().indexOf("publicId=")){
			if(-1 == dto.getUrlAddress().indexOf("?")){
				dto.setUrlAddress(dto.getUrlAddress()+"?publicId="+publicId);
			}else{
				dto.setUrlAddress(dto.getUrlAddress()+"&publicId="+publicId);
			}

		}

		dto.setCreator(user == null ? "" : user.getFullName());
		dto.setModifier(notice.getModifier());
		dto.setModifyTime(notice.getModifyTime() == null ? null : DateHelper.toDateTimeString(notice.getModifyTime()));
		dto.setPositionType(notice.getPositionType());
		dto.setOrgId(notice.getOrgId());
		dto.setOrgIds(notice.getOrgIds());
		dto.setSourceType(1);
		dto.setOpenIds(notice.getOpenIds());
		dto.setUserIds(notice.getUserIds());
		dto.setIsApp(notice.getIsApp());
		dto.setIsMessageList(notice.getIsMessageList());
		dto.setIsPublic(notice.getIsPublic());
		dto.setIsWechat(notice.getIsWechat());
		dto.setPublicObj(notice.getPublicObj());
		dto.setDetailList(getNoticeDetail(notice.getId()));
		dto.setApprovalType(notice.getApprovalType());
		dto.setIsPushTemplate(null == notice.getIsPushTemplate()? 0 : notice.getIsPushTemplate());
		String approvalTypeName="";
		if(null != notice.getApprovalType() && 0 != notice.getApprovalType().intValue()){
			NoticeApprovalTypeModel typeModel=noticeApprovalsetManager.findById(notice.getApprovalType());
			if(null != typeModel){
				approvalTypeName=typeModel.getName();
			}
		}
		
		dto.setApprovalTypeName(approvalTypeName);
		List<AuditDto> auditList=new ArrayList<AuditDto>();
		if(null != notice.getApprovalType() && 0 != notice.getApprovalType().intValue()){
			auditList=noticeApprovalsetManager.getAuditList(notice.getOrgId(), CodeConstants.ORDER_TYPE_NOTICE, notice.getId());
			dto.setAuditList(auditList);
		}else{
			if(null != dto.getApprovalTime() && StringUtils.isNotBlank(dto.getApprovalTime())){
				AuditDto auditDto=new AuditDto();
				auditDto.setApprovalTime(dto.getApprovalTime());
				auditDto.setApprovalOpinion("");
				if(null != dto.getState() && 1 == dto.getState().intValue()){
					auditDto.setApprovalResult(1);
				}else{
					auditDto.setApprovalResult(2);
				}
				auditDto.setApprovalUser(dto.getApprovalUser());
				auditList.add(auditDto);
			}
		}
		dto.setAuditList(auditList);
		return dto;
	}


	private List<AppNoticeDetailDto> getNoticeDetail(Integer noticeId) {
		List<AppNoticeDetailDto>   detailList = new ArrayList<AppNoticeDetailDto>();
		List<AppNoticeDetailModel> list       = appNoticeDetailDao.getNoticeDetail(noticeId);
		if (list != null && list.size() > 0) {
			for (AppNoticeDetailModel model : list) {
				AppNoticeDetailDto dto = new AppNoticeDetailDto();
				dto.setId(model.getId());
				String content = getContentInfo(model.getContent(), 2, model.getId());
				dto.setContent(content);
				dto.setContentTxt(model.getContentTxt());
				dto.setCoverUrl(model.getCoverUrl());
				dto.setPosition(model.getPosition());
				dto.setSummaryInfo(model.getSummaryInfo());
				dto.setTitle(model.getTitle());
				detailList.add(dto);
			}

			Collections.sort(detailList, new Comparator<AppNoticeDetailDto>() {
				public int compare(AppNoticeDetailDto o1, AppNoticeDetailDto o2) {
					String name1 = String.valueOf(o1.getPosition());//name1是从你list里面拿出来的一个
					String name2 = String.valueOf(o2.getPosition()); //name1是从你list里面拿出来的第二个name
					return name1.compareTo(name2);
				}
			});
		}
		return detailList;
	}

	/**
	 * 将公众号的图片换成我们服务器的图片
	 *
	 * @param content
	 * @return
	 */
	private String getContentInfo(String content, int type, Integer id) {
		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("http://mmbiz.qpic.cn/mmbiz_jpg") != -1) {
				AppNoticeContentModel model = appNoticeContentDao.findByIdAndImage(id, image, type, 2);
				if (null == model) {
					continue;
				}
				content = content.replace(image, model.getOldImage());
			}
		}
		return content;
	}


	@Override
	public AppResultDto getOrgListByCity(String orgIds, String city) {
		List<Map<String, Object>>        list   = organizationDao.getOrgOrderbyCity(orgIds, city);
		Map<String, Map<String, Object>> resMap = new HashMap<String, Map<String, Object>>();
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> map = list.get(i);
				if (map != null && map.containsKey("cityName") && map.get("cityName") != null) {
					String cityName = map.get("cityName").toString();
					String orgId    = map.get("orgId") == null ? "" : map.get("orgId").toString();
					String orgName  = map.get("orgName") == null ? "" : map.get("orgName").toString();
					if (resMap.containsKey(cityName)) {
						Map<String, Object> putMap = resMap.get(cityName);
						putMap.put(orgId, orgName);
					} else {
						Map<String, Object> putMap = new HashMap<String, Object>();
						putMap.put(orgId, orgName);
						resMap.put(cityName, putMap);
					}
				}
			}
		}
		return AppResultUtil.createSuccesDto(resMap);
	}

	@Override
	public void setTopByNum(int id, String userId, Integer num) {
		AppNoticeModel model = appNoticeDao.get(id);
		model.setModifier(userId);
		model.setModifyTime(new Date());
		model.setOrderNum((num == null) ? appNoticeDao.getMaxSortNum() + 1 : num);

		log.info("setTopByNum:" + JSONObject.toJSONString(model));

		this.updateModel(model);
	}

	@Override
	public void unSetTop(int id, String userId) {
		AppNoticeModel model = appNoticeDao.get(id);
		model.setModifier(userId);
		model.setModifyTime(new Date());
		model.setOrderNum(0);

		log.info("unSetTop:" + JSONObject.toJSONString(model));

		this.updateModel(model);
	}

	@Override
	public List<Map<String, Object>> getApprovalRole(Integer orgId,
			String syscode) {
		return roleDao.getRoleByFunc(orgId, syscode);
	}
	
	/**
	 * 根据部门分组获取用户失败
	 * @param orgId
	 * @param type
	 * @param id
	 * @return
	 */
	public List<DeptUserVo> getDeptGroupUserByOrgId(Integer orgId,Integer type,Integer id){
		List<DeptUserVo> list=new ArrayList<DeptUserVo>();
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("orgId", orgId);
		map.put("type", type);
		map.put("id", id);
		String params=HttpKit.getParamString(map);
		try {
			log.info("getDeptGroupUserByOrgId-params:{}",params);
			log.info("getDeptGroupUserByOrgId-deptGroupUserUrl:{}",deptGroupUserUrl);
			String     result = HttpKit.HttpPost(params, deptGroupUserUrl);
			log.info("getDeptGroupUserByOrgId-result:{}",result);
			if(StringUtils.isBlank(result)){
				return list;
			}
			JSONObject jsonObj=JSONObject.parseObject(result);
			if(!jsonObj.containsKey("code") || 200 != jsonObj.getInteger("code") || !jsonObj.containsKey("data")){
				return list;
			}
			JSONArray jsonArray=jsonObj.getJSONArray("data");
			if(null == jsonArray){
				return list;
			}
			list=JSONObject.parseArray(jsonArray.toJSONString(),DeptUserVo.class);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			log.error("根据部门分组获取用户失败-getDeptGroupUserByOrgId：{}",e.getMessage());
			return list;
		}
	}
	
	/**
	 * 根据部门分组获取用户失败
	 * @param orgId
	 * @param type
	 * @param id
	 * @return
	 */
	public List<DeptUserVo> getDeptGroupUserListByOrgId(DeptGroupVo vo){
		List<DeptUserVo> list=new ArrayList<DeptUserVo>();
		try {
			String jsonObject=JsonUtils.toJson(vo);
			log.info("getDeptGroupUserListByOrgId-jsonObject:{}",jsonObject);
			log.info("getDeptGroupUserListByOrgId-deptGroupUserListUrl:{}",deptGroupUserListUrl);
			String     result = HttpKit.HttpClientPost(jsonObject, deptGroupUserListUrl);
			log.info("getDeptGroupUserListByOrgId-result:{}",result);
			if(StringUtils.isBlank(result)){
				return list;
			}
			JSONObject jsonObj=JSONObject.parseObject(result);
			if(!jsonObj.containsKey("code") || 200 != jsonObj.getInteger("code") || !jsonObj.containsKey("data")){
				return list;
			}
			JSONArray jsonArray=jsonObj.getJSONArray("data");
			if(null == jsonArray){
				return list;
			}
			list=JSONObject.parseArray(jsonArray.toJSONString(),DeptUserVo.class);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			log.error("根据部门分组获取用户失败-getDeptGroupUserByOrgId：{}",e.getMessage());
			return list;
		}
	}
	
	
	/**
	 * 设置用户信息  
	 * @param orgId
	 * @param dtoList
	 * @param type 1，邮件 2。短信 3.模板消息
	 * @return
	 */
	@Override
	public AppResultDto setUserInfo(String orgId,List<DeptGroupDto> dtoList,int type){
		DeptGroupVo deptGroupVo=new DeptGroupVo();
		deptGroupVo.setOrgId(Integer.parseInt(orgId));
		deptGroupVo.setList(dtoList);
		List<DeptUserVo> userList=getDeptGroupUserListByOrgId(deptGroupVo);
		if(CollectionUtils.isEmpty(userList)){
			return AppResultUtil.createErrorDto("1", "发送的对象为空");
		}
		List<String> list=new ArrayList<String>();
		StringBuilder sb=new StringBuilder("");
		for(DeptUserVo vo:userList){
			if(null == vo || null == vo.getUserId()){
				continue;
			}
			if(1 == type){
				if(StringUtils.isEmpty(vo.getEmail())){
					continue;
				}
				if(list.contains(vo.getEmail())){
					continue;
				}
				sb.append(vo.getEmail());
				sb.append(";");
				list.add(vo.getEmail());
			}else if(2 == type){
				if(StringUtils.isEmpty(vo.getUserMobile())){
					continue;
				}
				if(list.contains(vo.getUserMobile())){
					continue;
				}
				sb.append(vo.getUserMobile());
				sb.append(",");
				list.add(vo.getUserMobile());
			}else if(3 == type){
				String userId=vo.getUserId().toString();
				if(list.contains(userId)){
					continue;
				}
				sb.append(userId);
				sb.append(",");
				list.add(userId);
			}
		}
		String str=sb.toString();
		if(3 == type && StringUtils.isNotEmpty(str)){
			str=str.substring(0,str.length()-1);
		}
		return AppResultUtil.createCommonDto("200", str, str);
	}
}
