package com.palmnest.webapp.controller.notice;

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

import com.alibaba.fastjson.JSONObject;
import com.mongodb.util.Hash;
import com.palmnest.application.AppConstants;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.*;
import com.palmnest.application.dto.*;
import com.palmnest.application.dto.output.AuditInfoDto;
import com.palmnest.model.Role;
import com.palmnest.model.User;
import com.palmnest.model.estateserve.WxPublicno;
import com.palmnest.model.notice.AppNoticeModel;
import com.palmnest.model.notice.ApprovalModel;
import com.palmnest.service.UserManager;
import com.palmnest.service.notice.*;
import com.palmnest.service.notice.service.NoticePublicnoService;
import com.palmnest.webapp.controller.BaseFormController;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import scala.Array;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@Controller
@RequestMapping("notice/appNotice*")
public class AppNoticeController extends BaseFormController {

	@Autowired
	private AppNoticeManager      appNoticeManager;

	@Autowired
	private AppNoticeRecordManager      appNoticeRecordManager;
	@Autowired
	private UserManager           userManager;
	@Autowired
	private NoticePublicnoService noticePublicnoService;
	@Autowired
	private NoticeApprovalsetManager noticeApprovalsetManager;

	@Autowired
	private AppNoticeReminderRecordManager appNoticeReminderRecordManager;

	@Autowired
	private NoticeSubGroupManager noticeSubGroupManager;

	@Autowired
	private WxPubManager                   wxPubManager;

	private String hostUrl        = PropertiesKit.readPropertiesValue("hostUrl", "wechat.properties");
	private String wxAppNoticeUrl = PropertiesKit.readPropertiesValue("wxAppNoticeUrl", "wechat.properties");





	/**
	 * 获取APP公告列表
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getList")
	@ResponseBody
	public WebPageResultDto getList(HttpServletRequest request, HttpServletResponse response) throws Exception {

		//获取当前登录用户所管辖项目
		User   user   = (User) request.getSession().getAttribute("UserCache");
		String orgIds = getUserManageOrgIds(user);//例如:1,25,2
		
//		log.info("user:{}",JsonUtils.toJson(user));
//		log.info("roles:{}",JsonUtils.toJson(user.getRoleList()));
//		log.info("roles:{}",JsonUtils.toJson(user.getRoles()));
		String c_beginTime = request.getParameter("c_beginTime");
		String c_endTime   = request.getParameter("c_endTime");
		String a_beginTime = request.getParameter("a_beginTime");
		String a_endTime   = request.getParameter("a_endTime");
		String state       = request.getParameter("state");
		String pageNo      = request.getParameter("page");
		String noticeType  = request.getParameter("noticeType");
		String orgId       = request.getParameter("orgId");
		String isEnabled   = request.getParameter("isEnabled");
		String title       = request.getParameter("title");
		
		if (StringUtils.isEmpty(pageNo)) {
			pageNo = "1";
		}
		String pageSize = request.getParameter("limit");
		if (StringUtils.isEmpty(pageSize)) {
			pageSize = "10";
		}
		HashMap<String, Object> map = new HashMap<String, Object>();
		if (!StringUtils.isEmpty(c_beginTime)) {
			map.put("c_beginTime", c_beginTime);
		}
		if (!StringUtils.isEmpty(c_endTime)) {
			map.put("c_endTime", c_endTime);
		}
		if (!StringUtils.isEmpty(a_beginTime)) {
			map.put("a_beginTime", a_beginTime);
		}
		if (!StringUtils.isEmpty(a_endTime)) {
			map.put("a_endTime", a_endTime);
		}
		if (!StringUtils.isEmpty(state)) {
			map.put("state", state);
		}
		if (!StringUtils.isEmpty(noticeType)) {
			map.put("noticeType", Integer.parseInt(noticeType));
		}
		if (!StringUtils.isEmpty(orgIds)) {
			map.put("orgIds", orgIds);
		}
		if (!StringUtils.isEmpty(orgId)) {
			map.put("orgId", orgId);
		}

		if (user != null) {
			map.put("userType", user.getUserType());
		}
		if (!StringUtils.isEmpty(isEnabled)) {
			map.put("isEnabled", isEnabled);
		}

		if (!StringUtils.isEmpty(title)) {
			map.put("title", title);
		}
		
		
		
		//当前登录的人的角色id
		String roleIds       = request.getParameter("roleIds");
		if(StringUtils.isNotBlank(roleIds)){
			map.put("roleIds", roleIds);
		}else{
			roleIds=getRoleIds(user);
			log.info("当前登录人的角色:roleIds：{}",roleIds);
			map.put("roleIds", roleIds);
		}
		
		String approvalType       = request.getParameter("approvalType");
		if (!StringUtils.isEmpty(approvalType)) {
			map.put("approvalType", approvalType);
		}
		
		
		try {
			Page page = appNoticeManager.getDataList(map, Integer.parseInt(pageNo), Integer.parseInt(pageSize));

			WebPageResultDto dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", page.getItems());
			dto.setCount(page.getTotalCount());
			return dto;
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return new WebPageResultDto(AppConstants.GET_NOTICE_LIST_ERROR, "查询列表失败", null);
		}


	}


	/**
	 * 获取APP公告详情
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getDetail")
	@ResponseBody
	public AppResultDto getDetail(Integer id) {
		try {
			return AppResultUtil.createSuccesDto(appNoticeManager.getDetailById(id, 1,0));
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto(AppConstants.GET_NOTICE_DETAIL_ERROR, "查询公告详情失败");
		}
	}

	@RequestMapping(value = "/recordNotice")
	@ResponseBody
	public WebPageResultDto recordNotice( HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			String id  = request.getParameter("id");
			String orgId  = request.getParameter("orgId");
				String content  = request.getParameter("content");
			log.info("recordNotice ,id:{},orgId:{},content:{}",id,orgId,content);

			HashMap<String, Object> map = new HashMap<String, Object>();
			if (!StringUtils.isEmpty(id)) {
				map.put("id", id);
			}
			if (!StringUtils.isEmpty(orgId)) {
				map.put("orgId", orgId);
			}
			if (!StringUtils.isEmpty(content)) {
				map.put("content", content);
			}
			   appNoticeRecordManager.recordNotice(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 = "/exportReportList")
	@ResponseBody
	public AppResultDto exportReportList(HttpServletRequest request)throws Exception {
		String id  = request.getParameter("id");
		String orgId  = request.getParameter("orgId");
		log.info("exportReportList ,id:{},orgId:{}",id,orgId);
		HashMap<String, Object> map = new HashMap<String, Object>();
		if (!StringUtils.isEmpty(id)) {
			map.put("id", id);
		}
		if (!StringUtils.isEmpty(orgId)) {
			map.put("orgId", orgId);
		}
		return appNoticeRecordManager.exportReportList(map);
	}

	@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 userId  = request.getParameter("userId");
		String orgId  = request.getParameter("orgId");
		log.info("exportReportList ,id:{},orgId:{}",id,orgId);
		if (!StringUtils.isEmpty(orgId)) {
			map.put("orgId", orgId);
		}
		if (!StringUtils.isEmpty(id)) {
			map.put("id", id);
		}
		if (!StringUtils.isEmpty(userId)) {
			map.put("userId", userId);
		}
		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 = "/getRecordList")
	@ResponseBody
	public WebPageResultDto getRecordList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String pageNo      = request.getParameter("page");
		String id  = request.getParameter("id");
		String orgId  = request.getParameter("orgId");
		String pageSize = request.getParameter("limit");
		log.info("getRecordList ,pageNo:{},id:{},orgId:{},pageSize:{}",pageNo,id,orgId,pageSize);
		if (StringUtils.isEmpty(pageNo)) {
			pageNo = "1";
		}

		if (StringUtils.isEmpty(pageSize)) {
			pageSize = "10";
		}

		HashMap<String, Object> map = new HashMap<String, Object>();
		if (!StringUtils.isEmpty(id)) {
			map.put("id", id);
		}
		if (!StringUtils.isEmpty(orgId)) {
			map.put("orgId", orgId);
		}
		try {
			AppNoticeRecordVo appNoticeRecordVo = appNoticeRecordManager.getRecordList(map, Integer.parseInt(pageNo), Integer.parseInt(pageSize));
			WebPageResultDto dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功",appNoticeRecordVo);
			if(appNoticeRecordVo!=null && !CollectionUtils.isEmpty(appNoticeRecordVo.getItems())){
				dto.setCount((long)appNoticeRecordVo.getItems().size());
			}else{
				dto.setCount((long)0);
			}
			return dto;
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return new WebPageResultDto(AppConstants.ERROR_CODE, "失败", null);
		}

	}




	/**
	 * 新增修改APP公告
	 *
	 * @param appNotice
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/saveUpdateAppNotice")
	@ResponseBody
	public AppResultDto saveUpdateAppNotice(@ModelAttribute("appNoticeModel") AppNoticeModel appNotice, MultipartHttpServletRequest request, HttpServletResponse response) throws Exception {

		try {
			User             user = (User) request.getSession().getAttribute("UserCache");
			Integer createBy=null;
			if(null != user){
				createBy=Integer.parseInt(user.getId().toString());
			}
			SimpleDateFormat sif  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String           id   = request.getParameter("id");

			String noticeDetail = request.getParameter("noticeDetailList");
			String deptGroupJson   = request.getParameter("deptGroupJson");//部门或分组
			MultipartFile multipartFile = request.getFile("coverFile");
			//获得文件原始名称
			InputStream stream    ;
			String      fileExt   ;//图片后缀
			String      fileName  ;//图片名称
			String      coverUrl = "";//图片完整路径
			if (multipartFile != null) {
				stream = multipartFile.getInputStream();
				fileName = multipartFile.getOriginalFilename();
				fileName = new String(fileName.getBytes(), "utf-8");
				fileExt = StringUtils.isNotEmpty(fileName) ? fileName
						.substring(fileName.lastIndexOf("."))
						: StringUtils.EMPTY;

				if (stream != null) {
					FileUploadUtils fileUploadUtils = new FileUploadUtils();
					fileUploadUtils.init();
					String url1 = fileUploadUtils.uploadFile(stream, fileExt);
					coverUrl = fileUploadUtils.fullVisitPath(url1);
				}
			} else {
				coverUrl = appNotice.getCoverUrl();
			}

			if (StringUtil.isNotEmpty(appNotice.getOpenIds())) {
				String[] openIds = appNotice.getOpenIds().split(",");
				if (openIds.length < 2) {
					return AppResultUtil.createErrorDto("500", "选中的用户不能小于2人");
				}
			}

			Integer noticeId=null;

			Integer publicId = null;
			if(null != appNotice.getOrgId()){
				WxPublicno wxPublicno = wxPubManager.getPublicByOrgId(appNotice.getOrgId().toString());
				if(null != wxPublicno){
					publicId = wxPublicno.getId();
				}
			}
			log.info("saveUpdateAppNotice-publicId:{}",publicId);
			if (StringUtils.isNotEmpty(id)) { //修改
				AppNoticeModel appNoticeModel = appNoticeManager.get(Integer.parseInt(id));
				appNoticeModel.setTitle(appNotice.getTitle());
				appNoticeModel.setContent(appNotice.getContent());
				appNoticeModel.setContentTxt(appNotice.getContentTxt());
				appNoticeModel.setModifier(user.getId().toString());
				appNoticeModel.setModifyTime((new Date()));
				appNoticeModel.setPositionType(appNotice.getPositionType());
				appNoticeModel.setSummaryInfo(appNotice.getSummaryInfo());
				//notice_type 公告类型：1公告、2banner图、3跳转链接 4-商圈发现banner 5-楼闪送banner
				//content_type 内容类型：1图文消息、2跳转链接
				if (null != appNotice.getNoticeType()) {
					appNoticeModel.setNoticeType(appNotice.getNoticeType());
				}
				if (null != appNotice.getContentType()) {
					appNoticeModel.setContentType(appNotice.getContentType());
				}

				if(null != appNoticeModel.getState() && -1 == appNoticeModel.getState()){
					appNoticeModel.setState(0);
				}
				appNoticeModel.setIsApp(appNotice.getIsApp());
				appNoticeModel.setIsWechat(appNotice.getIsWechat());
				appNoticeModel.setIsPublic(appNotice.getIsPublic());
				appNoticeModel.setIsPushTemplate(appNotice.getIsPushTemplate());
				if (null != appNotice.getIsPublic() && 1 == appNotice.getIsPublic().intValue()) {
					appNoticeModel.setIsMessageList(appNotice.getIsMessageList());
					appNoticeModel.setOpenIds(appNotice.getOpenIds());
					appNoticeModel.setUserIds(appNotice.getUserIds());
				}
				appNoticeModel.setPublicObj(appNotice.getPublicObj());
				appNoticeModel.setOrgId(appNotice.getOrgId());
				appNoticeModel.setOrgIds(appNotice.getOrgIds());
				//删除原来的封面
				if (null != appNotice.getNoticeType() && 1 == appNotice.getNoticeType().intValue()) {
					coverUrl = appNotice.getCoverUrl();
					if(null != coverUrl && StringUtils.isNotBlank(coverUrl)){
						appNoticeModel.setCoverUrl(coverUrl.replaceAll("https:", "").replaceAll("http:", ""));
					}
				} else {
					String formerUrl = appNoticeModel.getCoverUrl();//之前图片路径
					if (appNoticeModel != null && StringUtils.isNotBlank(formerUrl) && StringUtils.isNotBlank(coverUrl)) {
						String delUrl = formerUrl.replace(FileUploadUtils.getVisitPrefix(), "");
						FileUploadUtils.deleteFileByPath(FileUploadUtils.getATTACHMENT_ROOT() + File.separator + delUrl);
						appNoticeModel.setCoverUrl(coverUrl.replaceAll("https:", "").replaceAll("http:", ""));
					}
				}


				//当发布类型为公告  或者banner图的图文消息时生成跳转链接
				if ((appNotice.getNoticeType() == 1 && appNotice.getContentType() == 1) ||
						(appNotice.getNoticeType() == 2 && appNotice.getContentType() == 1) ||
						appNotice.getNoticeType() == 3 ) {

					String url = hostUrl + wxAppNoticeUrl.replace("@id", appNotice.getId().toString()) + "&hideButton=1&sourceType=1";
					if(null != publicId){
						url = url + "&publicId="+publicId;
					}
					appNoticeModel.setUrl_address(url.replaceAll("https:", "").replaceAll("http:", ""));
				}

				appNoticeManager.saveOrUpdateAppNoticeModel(appNoticeModel);
				//保存提交的内容详情
				if (StringUtil.isNotEmpty(noticeDetail)) {
					noticePublicnoService.saveDetaile(noticeDetail, appNotice.getId(), user.getId().toString(),false,publicId);
				}
				noticeId=Integer.parseInt(id);
			} else {
				if(null != coverUrl && StringUtils.isNotBlank(coverUrl)){
					appNotice.setCoverUrl(coverUrl.replaceAll("https:", "").replaceAll("http:", ""));
				}
				appNotice.setCreator(user.getId().toString());
				appNotice.setState(0);
				appNotice.setCreateTime(sif.format(new Date()));
				appNotice.setIsEnabled("1");
				if(null == appNotice.getApprovalType()){
					appNotice.setApprovalType(0);
				}
				//保存公告
				appNotice = appNoticeManager.saveOrUpdateAppNoticeModel(appNotice);
				//当发布类型为公告  或者banner图的图文消息时生成跳转链接
				if ((appNotice.getNoticeType() == 1 && appNotice.getContentType() == 1) ||
						(appNotice.getNoticeType() == 2 && appNotice.getContentType() == 1) ||
						appNotice.getNoticeType() == 3 ) {

					String url = hostUrl + wxAppNoticeUrl.replace("@id", appNotice.getId().toString()) + "&hideButton=1&sourceType=1";
					if(null != publicId){
						url = url + "&publicId="+publicId;
					}
					appNotice.setUrl_address(url.replaceAll("https:", "").replaceAll("http:", ""));

				}
				appNoticeManager.updateModel(appNotice);
				//保存提交的内容详情
				if (StringUtil.isNotEmpty(noticeDetail)) {
					noticePublicnoService.saveDetaile(noticeDetail, appNotice.getId(), user.getId().toString(),true,publicId);
				}
				noticeId=appNotice.getId();
			}

			if(StringUtils.isNotEmpty(deptGroupJson)){
				List<DeptGroupDto> dtoList=JSONObject.parseArray(deptGroupJson,DeptGroupDto.class);
				log.info("dtoList:{}",JsonUtils.toJson(dtoList));
				if(!CollectionUtils.isEmpty(dtoList)){
					//类型：1-公告;2-微信模板;3-短信;4-邮件;
					noticeSubGroupManager.saveByDeptGroup(1, appNotice.getId(), dtoList, createBy);
					if(null != appNotice.getOrgId()){
						//保存完了之后把用户信息查出来，然后保存到相应的数据里面去
						AppResultDto dto=appNoticeManager.setUserInfo(appNotice.getOrgId().toString(), dtoList, 3);
						if("200".equals(dto.getCode())){
							appNotice=appNoticeManager.get(noticeId);
							appNotice.setUserIds(dto.getMsg());
							appNoticeManager.saveOrUpdateAppNoticeModel(appNotice);
						}
					}
					
				}
			}

			String pathUrl = hostUrl + wxAppNoticeUrl.replace("@id", appNotice.getId().toString()) + "&sourceType=1&isApproval=1&approvalType="+appNotice.getApprovalType();
			//如果有开启多级审核，给第一级审核人推送消息------新增才推送
			if(null != appNotice.getApprovalType() && 0 != appNotice.getApprovalType().intValue() && StringUtils.isBlank(id)){
				//推送消息给下一级审核人
				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);
				}
			}else{
				//推送消息
				if (StringUtil.isNotEmpty(appNotice.getOrgIds())) { //如果是多项目情况发布公告，则给新增人自己推送审核消息
					List<User> users = new ArrayList<User>();
					users.add(user);
//					String pathUrl=hostUrl+wxAppNoticeUrl.replace("@id", appNotice.getId().toString());
					if (appNotice.getNoticeType() != 3 && StringUtils.isBlank(id)) {//当公告类型不为生成链接类型 并且是新增时才进行推送
						appNoticeManager.pushMessage(Long.parseLong(appNotice.getId().toString()), CodeConstants.APP_NOTICE_PUSH_CODE, pathUrl, "有新公告通知待审核", "有新app公告待审核", users);
					}
				} else {//单项目情况下，给该项目下所有审核权限的人推送
					List<User> users = userManager.findByFunction(appNotice.getOrgId(), CodeConstants.AUDIT_NOTICE_PERMISSION);
//					String pathUrl=hostUrl+wxAppNoticeUrl.replace("@id", appNotice.getId().toString());
					if (appNotice.getNoticeType() != 3 && StringUtils.isBlank(id)) {//当公告类型不为生成链接类型 并且是新增时才进行推送
						appNoticeManager.pushMessage(Long.parseLong(appNotice.getId().toString()), CodeConstants.APP_NOTICE_PUSH_CODE, pathUrl, "有新公告通知待审核", "有新app公告待审核", users);
					}
				}
			}
			
			return AppResultUtil.createSuccesDto(appNotice);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto(AppConstants.ADD_NOTICE_ERROR, "fail");
		}

	}
	
	
	
	
	
	
	/**
	 * 新增修改APP公告-------预览保存
	 *
	 * @param appNotice
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/previewAppNotice")
	@ResponseBody
	public AppResultDto previewAppNotice(@ModelAttribute("appNoticeModel") AppNoticeModel appNotice, MultipartHttpServletRequest request, HttpServletResponse response) throws Exception {

		try {
			User             user = (User) request.getSession().getAttribute("UserCache");
			SimpleDateFormat sif  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String           id   = request.getParameter("id");

			String noticeDetail = request.getParameter("noticeDetailList");

			MultipartFile multipartFile = request.getFile("coverFile");
			//获得文件原始名称
			InputStream stream    ;
			String      fileExt   ;//图片后缀
			String      fileName  ;//图片名称
			String      coverUrl = "";//图片完整路径
			if (multipartFile != null) {
				stream = multipartFile.getInputStream();
				fileName = multipartFile.getOriginalFilename();
				fileName = new String(fileName.getBytes(), "utf-8");
				fileExt = StringUtils.isNotEmpty(fileName) ? fileName
						.substring(fileName.lastIndexOf("."))
						: StringUtils.EMPTY;

				if (stream != null) {
					FileUploadUtils fileUploadUtils = new FileUploadUtils();
					fileUploadUtils.init();
					String url1 = fileUploadUtils.uploadFile(stream, fileExt);
					coverUrl = fileUploadUtils.fullVisitPath(url1);
				}
			} else {
				coverUrl = appNotice.getCoverUrl();
			}

			if (StringUtil.isNotEmpty(appNotice.getOpenIds())) {
				String[] openIds = appNotice.getOpenIds().split(",");
				if (openIds.length < 2) {
					return AppResultUtil.createErrorDto("500", "选中的用户不能小于2人");
				}
			}

			Integer publicId = null;
			if(null != appNotice.getOrgId()){
				WxPublicno wxPublicno = wxPubManager.getPublicByOrgId(appNotice.getOrgId().toString());
				if(null != wxPublicno){
					publicId = wxPublicno.getId();
				}
			}

			if (StringUtils.isNotEmpty(id)) { //修改
				AppNoticeModel appNoticeModel = appNoticeManager.get(Integer.parseInt(id));
				appNoticeModel.setTitle(appNotice.getTitle());
				appNoticeModel.setContent(appNotice.getContent());
				appNoticeModel.setContentTxt(appNotice.getContentTxt());
				appNoticeModel.setModifier(user.getId().toString());
				appNoticeModel.setModifyTime((new Date()));
				appNoticeModel.setPositionType(appNotice.getPositionType());
				appNoticeModel.setSummaryInfo(appNotice.getSummaryInfo());
				//notice_type 公告类型：1公告、2banner图、3跳转链接 4-商圈发现banner 5-楼闪送banner
				//content_type 内容类型：1图文消息、2跳转链接
				if (null != appNotice.getNoticeType()) {
					appNoticeModel.setNoticeType(appNotice.getNoticeType());
				}
				if (null != appNotice.getContentType()) {
					appNoticeModel.setContentType(appNotice.getContentType());
				}
				appNoticeModel.setIsApp(appNotice.getIsApp());
				appNoticeModel.setIsWechat(appNotice.getIsWechat());
				appNoticeModel.setIsPublic(appNotice.getIsPublic());
				appNoticeModel.setIsPushTemplate(appNotice.getIsPushTemplate());
				if (null != appNotice.getIsPublic() && 1 == appNotice.getIsPublic().intValue()) {
					appNoticeModel.setIsMessageList(appNotice.getIsMessageList());
					appNoticeModel.setOpenIds(appNotice.getOpenIds());
					appNoticeModel.setUserIds(appNotice.getUserIds());
					appNoticeModel.setPublicObj(appNotice.getPublicObj());
				}

				appNoticeModel.setOrgId(appNotice.getOrgId());
				appNoticeModel.setOrgIds(appNotice.getOrgIds());
				//删除原来的封面
				if (null != appNotice.getNoticeType() && 1 == appNotice.getNoticeType().intValue()) {
					coverUrl = appNotice.getCoverUrl();
					if(null != coverUrl && StringUtils.isNotBlank(coverUrl)){
						appNoticeModel.setCoverUrl(coverUrl.replaceAll("https:", "").replaceAll("http:", ""));
					}
				} else {
					String formerUrl = appNoticeModel.getCoverUrl();//之前图片路径
					if (appNoticeModel != null && StringUtils.isNotBlank(formerUrl) && StringUtils.isNotBlank(coverUrl)) {
						String delUrl = formerUrl.replace(FileUploadUtils.getVisitPrefix(), "");
						FileUploadUtils.deleteFileByPath(FileUploadUtils.getATTACHMENT_ROOT() + File.separator + delUrl);
						appNoticeModel.setCoverUrl(coverUrl.replaceAll("https:", "").replaceAll("http:", ""));
					}
				}

				//当发布类型为公告  或者banner图的图文消息时生成跳转链接
				if ((appNotice.getNoticeType() == 1 && appNotice.getContentType() == 1) ||
						(appNotice.getNoticeType() == 2 && appNotice.getContentType() == 1) ||
						appNotice.getNoticeType() == 3 ) {

					String url = hostUrl + wxAppNoticeUrl.replace("@id", appNotice.getId().toString()) + "&hideButton=1&sourceType=1";
					if(null != publicId){
						url = url + "&publicId="+publicId;
					}
					appNoticeModel.setUrl_address(url.replaceAll("https:", "").replaceAll("http:", ""));
				}

				appNoticeManager.saveOrUpdateAppNoticeModel(appNoticeModel);
				//保存提交的内容详情
				if (StringUtil.isNotEmpty(noticeDetail)) {
					noticePublicnoService.saveDetaile(noticeDetail, appNotice.getId(), user.getId().toString(),false,publicId);
				}
				appNotice=appNoticeModel;
			} else {
				if(null != coverUrl && StringUtils.isNotBlank(coverUrl)){
					appNotice.setCoverUrl(coverUrl.replaceAll("https:", "").replaceAll("http:", ""));
				}
				appNotice.setCreator(user.getId().toString());
				appNotice.setState(-1);
				appNotice.setCreateTime(sif.format(new Date()));
				appNotice.setIsEnabled("1");
				if(null == appNotice.getApprovalType()){
					appNotice.setApprovalType(0);
				}
				//保存公告
				appNotice = appNoticeManager.saveOrUpdateAppNoticeModel(appNotice);
				//当发布类型为公告  或者banner图的图文消息时生成跳转链接
				if ((appNotice.getNoticeType() == 1 && appNotice.getContentType() == 1) ||
						(appNotice.getNoticeType() == 2 && appNotice.getContentType() == 1) ||
						appNotice.getNoticeType() == 3 ) {

					String url = hostUrl + wxAppNoticeUrl.replace("@id", appNotice.getId().toString()) + "&hideButton=1&sourceType=1";
					if(null != publicId){
						url = url + "&publicId="+publicId;
					}
					appNotice.setUrl_address(url.replaceAll("https:", "").replaceAll("http:", ""));

				}
				appNoticeManager.updateModel(appNotice);
				//保存提交的内容详情
				if (StringUtil.isNotEmpty(noticeDetail)) {
					noticePublicnoService.saveDetaile(noticeDetail, appNotice.getId(), user.getId().toString(),true,publicId);
				}
			}
			return AppResultUtil.createSuccesDto(appNotice);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto(AppConstants.ADD_NOTICE_ERROR, "fail");
		}

	}



	/**
	 * 直接生成链接
	 *
	 * @param appNotice
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/saveUpdateAppNoticeCreateLink")
	public void saveUpdateAppNoticeCreateLink(@ModelAttribute("appNoticeModel") AppNoticeModel appNotice, HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject json = new JSONObject();
		try {
			User user = (User) request.getSession().getAttribute("UserCache");

			SimpleDateFormat sif     = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String           title   = request.getParameter("title");
			String           content = request.getParameter("content");
			String           id      = request.getParameter("id");
			if (StringUtils.isEmpty(id)) {

				appNotice.setTitle(title);
				appNotice.setCreator(user.getFullName());
				appNotice.setContent(content);
				appNotice.setState(3);
				appNotice.setCreateTime(sif.format(new Date()));
				appNotice.setIsEnabled("1");
				appNotice.setCreator(user.getId() + "");

				try {
					appNotice = appNoticeManager.save(appNotice);

					Integer publicId = null;
					if(null != appNotice.getOrgId()){
						WxPublicno wxPublicno = wxPubManager.getPublicByOrgId(appNotice.getOrgId().toString());
						if(null != wxPublicno){
							publicId = wxPublicno.getId();
						}
					}

					String url = hostUrl + wxAppNoticeUrl.replace("@id", appNotice.getId().toString()) + "&hideButton=1";
					if(null != publicId){
						url = url + "&publicId="+publicId;
					}
					appNotice.setUrl_address(url.replaceAll("https:", "").replaceAll("http:", ""));
					appNoticeManager.updateModel(appNotice);


					json.put("code", "200");
					json.put("msg", "success");
					json.put("data", appNotice);
					StringUtil.charSet(json, request, response);

				} catch (Exception e) {
					appNotice.setState(0);
					appNoticeManager.updateModel(appNotice);

					json.put("code", "1");
					json.put("msg", e.getMessage());
					json.put("data", appNotice);
					StringUtil.charSet(json, request, response);
					e.printStackTrace();
				}

			} else {
				json.put("code", "1");
				json.put("msg", "fail");
				json.put("data", appNotice);
				StringUtil.charSet(json, request, response);
			}

		} catch (Exception e) {

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

	}

	/**
	 * 公告置顶
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/setTop")
	public void setAppNoticeTop(HttpServletRequest request, HttpServletResponse response) throws Exception {
		User   user  = (User) request.getSession().getAttribute("UserCache");
		String id    = request.getParameter("id");
		String num   = request.getParameter("num");
		String isTop = request.getParameter("isTop"); //1:设置置顶 0取消置顶
		if ("1".equals(isTop)) {
			appNoticeManager.setTopByNum(Integer.parseInt(id), user.getId().toString(), StringUtil.isNotEmpty(num) ? Integer.parseInt(num) : null);
		} else {
			appNoticeManager.unSetTop(Integer.parseInt(id), user.getId().toString());
		}

		JSONObject json = new JSONObject();
		json.put("code", "200");
		json.put("msg", "success");
		StringUtil.charSet(json, request, response);
	}
	
	
	/**
	 * 审核APP公告
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/approvalAppNoticeNew")
	@ResponseBody
	public AppResultDto approvalAppNoticeNew(HttpServletRequest request, HttpServletResponse response) throws Exception {
		log.info("AppNoticeController.approvalAppNoticeNew()；----------------------审核公告开始:{};{}",DateHelper.formatDate(new Date(), DateHelper.DATE_TIME_STRING),System.currentTimeMillis());
		String id        = request.getParameter("id");
		String state     = request.getParameter("state");//1通过2不通过
		String approvalOpinion     = request.getParameter("approvalOpinion");
		log.info("AppNoticeController.approvalAppNoticeNew()；id:{},state:{}",id,state);
		User   user   = (User) request.getSession().getAttribute("UserCache");
		String userName=StringUtils.isNotBlank(user.getFullName()) ? user.getFullName() : user.getUsername();
		AuditResultVo auditResultVo = new AuditResultVo();
			AppNoticeModel appNotice = appNoticeManager.get(Integer.parseInt(id));
			if(null == appNotice){
				return AppResultUtil.createErrorDto("500", "未获取到公告订单");
			}
			int approvalResult=Integer.parseInt(state);
			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();
			}
//			log.info("approvalAppNoticeNew-auditResultVo:{}",JsonUtils.toJson(auditResultVo));
//			log.info("approvalAppNoticeNew-haveNext:{}",haveNext);
			if(2 == approvalResult || 0 == haveNext){
				Map<String, Object> resMap = noticePublicnoService.approvalAppNotice(appNotice,request, user, 1);
//				log.info("approvalAppNoticeNew-resMap:{}",JsonUtils.toJson(resMap));
				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("PC进入发布公告模板推送--------------------------------------");
						String url=appNotice.getUrl_address();
						if(-1 == url.indexOf("http")){
							url="http:"+url;
						}
						if(1 == approvalResult){
							//推送模板消息给所有粉丝
//							noticePublicnoService.sendTemplateMsgByWxUser(appNotice.getOrgId(),appNotice.getTitle(),url);
							String res=sendWxTempMsg(appNotice,url);
							log.info("发布公告-模板消息:{}",res);
							if(StringUtils.isNotEmpty(res)){
								return AppResultUtil.createErrorDto("400", "发布模板消息失败:"+ res);
							}
						}
					}
					log.info("AppNoticeController.approvalAppNoticeNew()；----------------------审核公告结束:{}；{}",DateHelper.formatDate(new Date(), DateHelper.DATE_TIME_STRING),System.currentTimeMillis());
					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();
	}
	
	
	private String sendWxTempMsg(AppNoticeModel appNotice,String url){
		Map<String,Object> map=noticePublicnoService.getSentWxTempMsg(appNotice);
		log.info("sendWxTempMsg-map:{}",JsonUtils.toJson(map));
		if (200 != Integer.parseInt(map.get("code").toString())){
			return map.get("msg").toString();
		}
		List<NoticeWxTempVo> list=(List<NoticeWxTempVo>)map.get("data");
		if(CollectionUtils.isEmpty(list)){
			return "发送的用户不能为空";
		}
		String content="";
		if(StringUtil.isNotEmpty(appNotice.getTitle())){
			
			if(null != appNotice.getNoticeType() && 2 == appNotice.getNoticeType().intValue()){
				content="新发布了banner《"+appNotice.getTitle()+"》,请注意查看！";
			}else{
				content="新发布了公告《"+appNotice.getTitle()+"》,请注意查看！";
			}
		}else{
			if(null != appNotice.getNoticeType() && 2 == appNotice.getNoticeType().intValue()){
				content="新发布了banner,请注意查看！";
			}else{
				content="新发布了公告,请注意查看！";
			}
			
		}
		//推送模板消息给所有粉丝
		noticePublicnoService.sendTemplateMsgByWxUser(list,url,content);
		return "";
	}


	/**
	 * 发布APP公告
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/approvalAppNotice")
	public void approvalAppNotice(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject json = new JSONObject();
		log.info("AppNoticeController.approvalAppNotice()");
		String id        = request.getParameter("id");
		String state     = request.getParameter("state");
		User                user   = (User) request.getSession().getAttribute("UserCache");
		log.info("AppNoticeController.approvalAppNotice ===> id:" + id + " state:" + state + " user:" + JsonUtils.toJson(user));
		Map<String, Object> resMap =new HashMap<String, Object>();
		AppNoticeModel appNotice =null;
		try {
			appNotice = appNoticeManager.get(Integer.parseInt(id));
			if(null != appNotice){
				resMap =noticePublicnoService.approvalAppNotice(appNotice,request, user, 1);
			} else{
				json.put("code", "1");
				json.put("msg", "发布失败");
				json.put("msgStr", "发布失败:未找到订单信息");
				log.error("发布失败:未找到订单信息");
				StringUtil.charSet(json, request, response);
				return;
			}
		}catch (Exception e) {

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

		if (200 != Integer.parseInt(resMap.get("code").toString())) {
			json.put("code", "1");
			json.put("msg", "发布失败");
			json.put("msgStr", "发布失败:" + resMap.get("msgStr"));
			log.error("发布失败:" + resMap.get("msgStr"));
			StringUtil.charSet(json, request, response);
		} else {
			if(1 == Integer.parseInt(state)){
				//审核通过
				log.info("记录通知消息--------------------------------------");
				noticePublicnoService.saveNoticeRecord(appNotice);
			}
			if(null != appNotice.getOrgId() && null != appNotice.getIsPushTemplate() && 1 == appNotice.getIsPushTemplate().intValue()){
				log.info("PC进入发布公告模板推送--------------------------------------");
				String url=appNotice.getUrl_address();
				if(-1 == url.indexOf("http")){
					url="http:"+url;
				}
				if(1 == Integer.parseInt(state)){
					//推送模板消息给所有粉丝
//							noticePublicnoService.sendTemplateMsgByWxUser(appNotice.getOrgId(),appNotice.getTitle(),url);
					String res=sendWxTempMsg(appNotice,url);
					log.info("发布公告-模板消息:{}",res);
					if(StringUtils.isNotEmpty(res)){
						json.put("code", "400");
						json.put("msg", "发布模板消息失败:"+ res);
						StringUtil.charSet(json, request, response);
						return;
					}
				}
			}
			json.put("code", "200");
			json.put("msg", "success");
			json.put("data", resMap.get("data"));
			StringUtil.charSet(json, request, response);
		}
	}

	/**
	 * 删除APP公告
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/deleteNotice")
	@ResponseBody
	public void deleteNotice(HttpServletRequest request, HttpServletResponse response) throws Exception {
		User   user      = (User) request.getSession().getAttribute("UserCache");
		String id        = request.getParameter("id");
		String isEnabled = request.getParameter("isEnabled");
		// String isEnabled = "2";//原先0为删除 1代表下线,2代表上线
		AppNoticeModel model = appNoticeManager.get(Integer.parseInt(id));
		model.setModifier(user.getId().toString());
		model.setModifyTime(new Date());
		model.setIsEnabled(isEnabled);
		appNoticeManager.updateModel(model);
		//		appNoticeManager.remove(Integer.parseInt(id));
		JSONObject json = new JSONObject();
		json.put("code", "200");
		json.put("msg", "success");
		StringUtil.charSet(json, request, response);
	}

	/**
	 * 新增/修改 商圈发现banner
	 *
	 * @param request   图片请求对象
	 * @param appNotice 参数封装类
	 * @return
	 */
	@RequestMapping(value = "saveUpdateDiscoverBanner")
	@ResponseBody
	public AppResultDto saveUpdateDiscoverBanner(@ModelAttribute("appNoticeModel") AppNoticeModel appNotice, MultipartHttpServletRequest request) {

		try {
			User user = (User) request.getSession().getAttribute("UserCache");

			String id = request.getParameter("id");

			MultipartFile multipartFile = request.getFile("coverFile");

			//获得文件原始名称
			InputStream stream   = null;
			String      fileExt  = null;//图片后缀
			String      fileName = "";//图片名称
			String      coverUrl = "";//图片完整路径
			if (multipartFile != null) {
				stream = multipartFile.getInputStream();
				fileName = multipartFile.getOriginalFilename();
				fileName = new String(fileName.getBytes(), "utf-8");
				fileExt = StringUtils.isNotEmpty(fileName) ? fileName
						.substring(fileName.lastIndexOf("."))
						: StringUtils.EMPTY;

				if (stream != null) {
					FileUploadUtils fileUploadUtils = new FileUploadUtils();
					fileUploadUtils.init();
					String url1 = fileUploadUtils.uploadFile(stream, fileExt);
					coverUrl = fileUploadUtils.fullVisitPath(url1);
				}
			}

			Integer publicId = null;
			if(null != appNotice.getOrgId()){
				WxPublicno wxPublicno = wxPubManager.getPublicByOrgId(appNotice.getOrgId().toString());
				if(null != wxPublicno){
					publicId = wxPublicno.getId();
				}
			}
			if (StringUtils.isNotBlank(id)) {//修改

				AppNoticeModel appNoticeModel = appNoticeManager.get(Integer.parseInt(id));
				appNoticeModel.setTitle(appNotice.getTitle());
				appNoticeModel.setContent(appNotice.getContent());
				appNoticeModel.setContentTxt(appNotice.getContentTxt());
				appNoticeModel.setModifier(user.getId().toString());
				appNoticeModel.setModifyTime((new Date()));
				appNoticeModel.setSummaryInfo(appNotice.getSummaryInfo());
				if(StringUtils.isNotBlank(appNotice.getUrl_address())){
					appNoticeModel.setUrl_address(appNotice.getUrl_address().replaceAll("https:", "").replaceAll("http:", ""));
				}else{
					appNoticeModel.setUrl_address(appNotice.getUrl_address());
				}
				
				//当发布类型为公告  或者banner图的图文消息时生成跳转链接
				if (appNotice.getContentType() == 1) {
					String url = hostUrl + wxAppNoticeUrl.replace("@id", appNotice.getId().toString()) + "&hideButton=1";
					if(null != publicId){
						url = url + "&publicId="+publicId;
					}
					appNoticeModel.setUrl_address(url.replaceAll("https:", "").replaceAll("http:", ""));
				}

				//如果更换了banner图,则删除原来的封面
				String formerUrl = appNoticeModel.getCoverUrl();//之前图片路径
				if (appNoticeModel != null && StringUtils.isNotBlank(formerUrl) && StringUtils.isNotBlank(coverUrl)) {
					String delUrl = formerUrl.replace(FileUploadUtils.getVisitPrefix(), "");
					FileUploadUtils.deleteFileByPath(FileUploadUtils.getATTACHMENT_ROOT() + File.separator + delUrl);
					appNoticeModel.setCoverUrl(coverUrl.replaceAll("https:", "").replaceAll("http:", ""));
				}

				appNoticeManager.saveOrUpdateAppNoticeModel(appNoticeModel);

			} else {//新增
				appNotice.setCoverUrl(coverUrl.replaceAll("https:", "").replaceAll("http:", ""));
				appNotice.setCreator(user.getId().toString());
				//新增公告类型为商圈banner,则不要审核,状态直接设置为审核通过
				appNotice.setState(1);
				appNotice.setCreateTime(DateHelper.toDateTimeString(new Date()));
				appNotice.setIsEnabled("1");
				//微信公众号端商圈发现  类型notice_type:4  展示位置(微信端)position_type:2
				appNotice.setNoticeType(4);
				appNotice.setPositionType(2);
				appNotice = appNoticeManager.saveOrUpdateAppNoticeModel(appNotice);
				//当发布类型为公告  或者banner图的图文消息时生成跳转链接
				if (appNotice.getContentType() == 1) {
					String url = hostUrl + wxAppNoticeUrl.replace("@id", appNotice.getId().toString()) + "&hideButton=1";
					if(null != publicId){
						url = url + "&publicId="+publicId;
					}
					appNotice.setUrl_address(url.replaceAll("https:", "").replaceAll("http:", ""));
				}
				appNoticeManager.updateModel(appNotice);
			}

			return AppResultUtil.createSuccesDto(appNotice);
		} catch (Exception e) {
			log.error("AppNoticeController saveUpdateDiscoverBanner Error ===========>:" + e.getMessage());
			return AppResultUtil.createErrorDto(AppConstants.ADD_NOTICE_ERROR, "fail");
		}

	}


	/**
	 * 获取商圈发现banner列表
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getDiscoverBannerList")
	@ResponseBody
	public WebPageResultDto getDiscoverBannerList(HttpServletRequest request, HttpServletResponse response) throws Exception {

		String c_beginTime = request.getParameter("c_beginTime");
		String c_endTime   = request.getParameter("c_endTime");
		String a_beginTime = request.getParameter("a_beginTime");
		String a_endTime   = request.getParameter("a_endTime");
		String state       = request.getParameter("state");
		String pageNo      = request.getParameter("page");

		String noticeType = "4";//banner类型设置为商圈发现banner

		if (StringUtils.isEmpty(pageNo)) {
			pageNo = "1";
		}
		String pageSize = request.getParameter("limit");
		if (StringUtils.isEmpty(pageSize)) {
			pageSize = "10";
		}
		HashMap<String, Object> map = new HashMap<String, Object>();
		if (!StringUtils.isEmpty(c_beginTime)) {
			map.put("c_beginTime", c_beginTime);
		}
		if (!StringUtils.isEmpty(c_endTime)) {
			map.put("c_endTime", c_endTime);
		}
		if (!StringUtils.isEmpty(a_beginTime)) {
			map.put("a_beginTime", a_beginTime);
		}
		if (!StringUtils.isEmpty(a_endTime)) {
			map.put("a_endTime", a_endTime);
		}
		if (!StringUtils.isEmpty(state)) {
			map.put("state", state);
		}
		if (!StringUtils.isEmpty(noticeType)) {
			map.put("noticeType", Integer.parseInt(noticeType));
		}


		try {
			Page page = appNoticeManager.getDataList(map, Integer.parseInt(pageNo), Integer.parseInt(pageSize));

			WebPageResultDto dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", page.getItems());
			dto.setCount(page.getTotalCount());
			return dto;
		} catch (Exception e) {
			log.info("" + e.getMessage());
			e.printStackTrace();
			return new WebPageResultDto(AppConstants.GET_NOTICE_LIST_ERROR, "查询列表失败", null);
		}

	}



	/**
	 * 获取催读列表
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getReminderRecord")
	@ResponseBody
	public WebPageResultDto getReminderRecord(HttpServletRequest request, HttpServletResponse response) throws Exception {


		String id       = request.getParameter("id");
		String pageNo      = request.getParameter("page");



		if (StringUtils.isEmpty(pageNo)) {
			pageNo = "1";
		}
		String pageSize = request.getParameter("limit");
		if (StringUtils.isEmpty(pageSize)) {
			pageSize = "5";
		}

		try {
			Page page = appNoticeReminderRecordManager.getReminderRecord(Integer.parseInt(id), Integer.parseInt(pageNo), Integer.parseInt(pageSize));

			WebPageResultDto dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", page.getItems());
			dto.setCount(page.getTotalCount());
			return dto;
		} catch (Exception e) {
			log.info("" + e.getMessage());
			e.printStackTrace();
			return new WebPageResultDto(AppConstants.GET_NOTICE_LIST_ERROR, "查询列表失败", null);
		}

	}

	/**
	 * 获取APP公告详情
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getOrgListByCity")
	@ResponseBody
	public AppResultDto getOrgListByCity(HttpServletRequest request, String city) {
		User user = (User) request.getSession().getAttribute("UserCache");
		try {
			String orgIds = getUserManageOrgIds(user);
			return appNoticeManager.getOrgListByCity(orgIds, city);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto(AppConstants.ADD_NOTICE_ERROR, "新增公告失败");
		}
	}


	/**
	 * 获取APP公告详情
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/redirectToEdit")
	@ResponseBody
	public ModelAndView redirectToEdit(HttpServletRequest request, HttpServletResponse response) throws Exception {

		User user = (User) request.getSession().getAttribute("UserCache");

//		String type = "1";
//		String id = request.getParameter("id");
//		if (StringUtil.isNotEmpty(request.getParameter("sourceType"))) {
//			type = request.getParameter("sourceType");
//		}
		//NoticeDto noticeDto = appNoticeManager.getDetailById(Integer.parseInt(id), Integer.parseInt(type));

		ModelAndView model = new ModelAndView();
//		noticeDto.setId(null);
//		model.addObject("noticeDto", noticeDto);
		model.addObject("editType", 2);
		model.setViewName("admin/notice/noticeAppPublish");
		return model;
	}


	/**
	 * 跳转到公告审核界面
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/redirectToSH")
	@ResponseBody
	public ModelAndView redirectToSH(HttpServletRequest request, HttpServletResponse response) throws Exception {

		User user = (User) request.getSession().getAttribute("UserCache");

//		String type = "1";
//		String id = request.getParameter("id");
//		if (StringUtil.isNotEmpty(request.getParameter("sourceType"))) {
//			type = request.getParameter("sourceType");
//		}
		//NoticeDto noticeDto = appNoticeManager.getDetailById(Integer.parseInt(id), Integer.parseInt(type));

		ModelAndView model = new ModelAndView();
//		noticeDto.setId(null);
//		model.addObject("noticeDto", noticeDto);
		model.addObject("editType", 2);
		model.setViewName("admin/notice/noticeAppPublishSH");
		return model;
	}

	/**
	 * 跳转到微信审核界面
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/redirectToWXApprovel")
	@ResponseBody
	public ModelAndView redirectToWXApprovel(HttpServletRequest request, HttpServletResponse response) throws Exception {

		User user = (User) request.getSession().getAttribute("UserCache");

//		String type = "1";
//		String id = request.getParameter("id");
//		if (StringUtil.isNotEmpty(request.getParameter("sourceType"))) {
//			type = request.getParameter("sourceType");
//		}
		//NoticeDto noticeDto = appNoticeManager.getDetailById(Integer.parseInt(id), Integer.parseInt(type));

		ModelAndView model = new ModelAndView();
//		noticeDto.setId(null);
//		model.addObject("noticeDto", noticeDto);
		model.addObject("editType", 2);
		model.setViewName("admin/notice/noticeWxPublishSH");
		return model;
	}


	/**
	 * 跳转到公告详情界面
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/redirectToNoticeDetail")
	@ResponseBody
	public ModelAndView redirectToNoticeDetail(HttpServletRequest request, HttpServletResponse response) throws Exception {

		User user = (User) request.getSession().getAttribute("UserCache");

//		String type = "1";
//		String id = request.getParameter("id");
//		if (StringUtil.isNotEmpty(request.getParameter("sourceType"))) {
//			type = request.getParameter("sourceType");
//		}
		//NoticeDto noticeDto = appNoticeManager.getDetailById(Integer.parseInt(id), Integer.parseInt(type));

		ModelAndView model = new ModelAndView();
//		noticeDto.setId(null);
//		model.addObject("noticeDto", noticeDto);
		model.addObject("editType", 2);
		model.setViewName("admin/notice/noticeAppDetail");
		return model;
	}

	/**
	 * 跳转到多级审核的JSP界面
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/redirectToMultilevelClassification")
	@ResponseBody
	public ModelAndView redirectToMultilevelClassification(HttpServletRequest request, HttpServletResponse response) throws Exception {

		User user = (User) request.getSession().getAttribute("UserCache");

//		String type = "1";
//		String id = request.getParameter("id");
//		if (StringUtil.isNotEmpty(request.getParameter("sourceType"))) {
//			type = request.getParameter("sourceType");
//		}
		//NoticeDto noticeDto = appNoticeManager.getDetailById(Integer.parseInt(id), Integer.parseInt(type));

		ModelAndView model = new ModelAndView();
//		noticeDto.setId(null);
//		model.addObject("noticeDto", noticeDto);
		model.addObject("editType", 2);
		model.setViewName("admin/notice/noticeMultilevelClassification");
		return model;
	}
	
}
