package com.palmnest.webapp.controller.notice;

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

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.bean.Page;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.core.util.PropertiesKit;
import com.palmnest.application.dto.output.NoticeDto;
import com.palmnest.application.dto.output.NoticeSumIndexDto;
import com.palmnest.model.TempSaverList;
import com.palmnest.model.User;
import com.palmnest.model.estateserve.WxPublicno;
import com.palmnest.model.notice.WxtemplateMessageTypeModel;
import com.palmnest.service.UserManager;
import com.palmnest.service.notice.*;
import com.palmnest.service.redis.BaseRedisService;
import com.palmnest.webapp.controller.BaseFormController;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedCaseInsensitiveMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

import java.text.SimpleDateFormat;
import java.util.*;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
@RequestMapping("/api/notice")
public class ApiNoticeController extends BaseFormController {

	@Autowired
	private AppNoticeManager             appNoticeManager;
	@Autowired
	private PhoneMessageManager          phoneMessageManager;
	@Autowired
	private EmailSendManager             emailSendManager;
	@Autowired
	private WxtemplateMessageManager     wxtemplateMessageManager;
	@Autowired
	private WxtemplateMessageTypeManager wxTypeManager;
	@Autowired
	private WxPubManager                 wxPubManager;
	@Autowired
	private BaseRedisService             baseRedisService;
	@Autowired
	private UserManager                  userManager;
	
	@Autowired
	private NoticeApprovalsetManager noticeApprovalsetManager;

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

	/**
	 * 通知公告首页脚标数量
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/indexTotal")
	@ResponseBody
	public AppResultDto indexTotal(HttpServletRequest request) {
		String userName = baseRedisService.get(request.getHeader("token"));
		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		User   user   = userManager.getUserByUsername2(userName);
		String orgIds = getUserManageOrgIds(user);
		try {
			Integer appNoticeTotal    = appNoticeManager.getTotal(orgIds);
			Integer wxMessageTotal    = wxtemplateMessageManager.getTotal(orgIds);
			Integer phoneMessageTotal = phoneMessageManager.getTotal(orgIds);
			Integer emailMessageTotal = emailSendManager.getTotal(orgIds);

			NoticeSumIndexDto dto = new NoticeSumIndexDto(appNoticeTotal, wxMessageTotal, phoneMessageTotal, emailMessageTotal);
			return AppResultUtil.createSuccesDto(dto);
		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createErrorDto(AppConstants.NOTICE_INDEX_ERROR, "公告审核首页脚标查询失败");
		}
	}

	/**
	 * @param request
	 * @return 查找banner图列表
	 */
	@RequestMapping(value = "/bannerList")
	@ResponseBody
	public AppResultDto bannerList(HttpServletRequest request) {
		String orgIds = getAppUserManageOrgIds(request);
		if (StringUtils.isEmpty(orgIds)) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}

		try {
			String positionType = "1,5";//展示位置 0-微信+app端/1-app端/2-微信/3-公众号/4-微信+公众号/5-app+公众号/6-微信+app+公众号
			List<NoticeDto> list = appNoticeManager.finByType(2, positionType, orgIds);
			if(!CollectionUtils.isEmpty(list)){
				for(NoticeDto dto : list){
					if(null == dto || StringUtils.isEmpty(dto.getCoverUrl())){
						continue;
					}
					String coverUrl = dto.getCoverUrl();
					if(StringUtils.isNotEmpty(coverUrl) && coverUrl.indexOf("http") < 0){
						coverUrl = "https:" + coverUrl;
						dto.setCoverUrl(coverUrl);
					}
				}
			}
			return AppResultUtil.createSuccesDto(list);
		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createErrorDto(AppConstants.GET_BANNER_DETAIL_ERROR, "查询banner列表失败");
		}
	}

	/**
	 * 获取列表
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getList")
	@ResponseBody
	public AppResultDto getList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String orgIds = getAppUserManageOrgIds(request);
		if (orgIds == "") {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		String type = request.getParameter("type");
		if (type.equals("APP_NIOTICE_AUDIT")) {
			return getAppList(request, response, orgIds);
		} else if (type.equals("SMS_MESSAGE_AUDIT")) {
			return getPhoneList(request, response, orgIds);
		} else if (type.equals("EMAIL_MESSAGE_AUDIT")) {
			return getEmailList(request, response, orgIds);
		} else if (type.equals("WECHAT_MESSAGE_AUDIT")) {
			return getWxList(request, response, orgIds);
		}
		return null;
	}

	/**
	 * 分页
	 * 获取APP首页新闻资讯列表
	 *
	 * @return
	 */
	@RequestMapping(value = "/noticeList")
	@ResponseBody
	public AppResultDto noticeList(HttpServletRequest request, HttpServletResponse response) {
		String userName = baseRedisService.get(request.getHeader("token"));
		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}

		User user = userManager.getUserByUsername2(userName);
		log.info("/api/notice/noticeList userName:"+userName+" user:"+ JsonUtils.toJson(user));
		try {
			String                  pageNo   = request.getParameter("pageNo");
			String                  pageSize = request.getParameter("pageSize");
			HashMap<String, Object> map      = new HashMap<String, Object>();
			if (StringUtils.isEmpty(pageNo)) {
				pageNo = "1";
			}
			if (StringUtils.isEmpty(pageSize)) {
				pageSize = "10";
			}
			//noticeType:1公告、2banner图  positionType:1-app端 2-微信
			map.put("noticeType", 1);
			//展示位置 展示位置 0-微信+app端/1-app端/2-微信/3-公众号/4-微信+公众号/5-app+公众号/6-微信+app+公众号
			map.put("positionTypes", "0,1,5,6");
			//查询审核通过的通告列表
			map.put("state", 1);
			if (user != null) {
				map.put("userType", user.getUserType());
			}

			String orgIds = getAppUserManageOrgIds(request);
			map.put("orgIds", orgIds);
			map.put("from", "app");
			Page page = appNoticeManager.getDataList(map, Integer.parseInt(pageNo), Integer.parseInt(pageSize));

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

				SimpleDateFormat sdf       = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
				SimpleDateFormat sdfResult = new SimpleDateFormat("M月d日 HH:mm");

				if (StringUtils.isNotEmpty((String) e.get("createTime"))) {
					Date date = sdf.parse((String) e.get("createTime"));
					temp.setCreateTime(sdfResult.format(date));
				}
				if (StringUtils.isNotEmpty((String) e.get("approval_time"))) {
					Date date = sdf.parse((String) e.get("approval_time"));
					temp.setApproval_time(sdfResult.format(date));
				}
				if (StringUtils.isNotEmpty((String) e.get("modifierTime"))) {
					Date date = sdf.parse((String) e.get("modifierTime"));
					temp.setModifyTime(sdfResult.format(date));
				}

				temp.setId((Integer) e.get("id"));
				temp.setTitle((String) e.get("title"));
				temp.setContent((String) e.get("content"));
				temp.setUrl_address((String) e.get("url_address"));
				temp.setState((Integer) e.get("state"));
				temp.setNoticeType((Integer) e.get("notice_type"));
				String coverUrl=e.get("cover_url") == null ? "" : e.get("cover_url").toString();
				if(StringUtils.isNotEmpty(coverUrl) && coverUrl.indexOf("http") < 0){
					coverUrl = "https:" + coverUrl;
				}
				temp.setCoverUrl(coverUrl);
				temp.setSummaryInfo((String) e.get("summary_info"));
				temp.setApproval_user((String) e.get("approval_user"));
				temp.setCreator((String) e.get("fullName"));
				temp.setModifier((String) e.get("modifier"));
				temp.setIsEnabled((String) e.get("isEnabled"));
				temp.setContentTxt((String) e.get("content_txt"));
				temp.setFullName((String) e.get("creator"));
				temp.setContentType((Integer) e.get("content_type"));
				String url = hostUrl + wxAppNoticeUrl.replace("@id", e.get("id") == null ? "" : e.get("id").toString());
				//当该条记录为公告的跳转链接时，url_path等于url_address
				if ((null != temp.getNoticeType() && 1 == temp.getNoticeType().intValue()) && (null != temp.getContentType() && 2 == temp.getContentType().intValue())) {
					if(StringUtils.isNotEmpty(temp.getUrl_address()) && temp.getUrl_address().indexOf("http") < 0){
						temp.setUrl_path("https:"+temp.getUrl_address());
					}else{
						temp.setUrl_path(temp.getUrl_address());
					}
					
				} else {
					temp.setUrl_path(url);
				}

				resultList.add(temp);
			}
			page.setItems(resultList);

			return AppResultUtil.createSuccesDto(AppConstants.SUCCESS_CODE, page);
		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createErrorDto(AppConstants.GET_BANNER_DETAIL_ERROR, "查询公告notice列表失败");
		}
	}

	/**
	 * 获取APP公告列表
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getAppList")
	@ResponseBody
	public AppResultDto getAppList(HttpServletRequest request, HttpServletResponse response, String orgIds) throws Exception {
		String userName = baseRedisService.get(request.getHeader("token"));
		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		User                    user         = userManager.getUserByUsername2(userName);
		String                  state        = request.getParameter("state");
		String                  positionType = request.getParameter("positionType");
		String                  pageNo       = request.getParameter("pageNo");
		String                  pageSize     = request.getParameter("pageSize");
		HashMap<String, Object> map          = new HashMap<String, Object>();
		if (StringUtils.isEmpty(pageNo)) {
			pageNo = "1";
		}
		if (StringUtils.isEmpty(pageSize)) {
			pageSize = "10";
		}
		if (!StringUtils.isEmpty(state)) {
			map.put("state", state);
		}
		if (!StringUtils.isEmpty(positionType)) {
			map.put("positionType", positionType);
		}
		if (!StringUtils.isEmpty(orgIds)) {
			map.put("orgIds", orgIds);
			map.put("orgId", orgIds);
		}
		if (user != null) {
			map.put("userType", user.getUserType());
		}
		
		//当前登录的人的角色id
		String roleIds       = request.getParameter("roleIds");
		if(StringUtils.isNotBlank(roleIds)){
			map.put("roleIds", roleIds);
		}else{
			roleIds=getRoleIds(user);
			map.put("roleIds", roleIds);
		}
		
		try {
			Page page = appNoticeManager.getDataList(map, Integer.parseInt(pageNo), Integer.parseInt(pageSize));

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

				SimpleDateFormat sdf       = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
				SimpleDateFormat sdfResult = new SimpleDateFormat("M月d日 HH:mm");

				if (StringUtils.isNotEmpty((String) e.get("createTime"))) {
					Date date = sdf.parse((String) e.get("createTime"));
					temp.setCreateTime(sdfResult.format(date));
				}
				if (StringUtils.isNotEmpty((String) e.get("approval_time"))) {
					Date date = sdf.parse((String) e.get("approval_time"));
					temp.setApproval_time(sdfResult.format(date));
				}
				if (StringUtils.isNotEmpty((String) e.get("modifierTime"))) {
					Date date = sdf.parse((String) e.get("modifierTime"));
					temp.setModifyTime(sdfResult.format(date));
				}

				temp.setId((Integer) e.get("id"));
				temp.setTitle((String) e.get("title"));
				temp.setContent((String) e.get("content"));
				temp.setUrl_address((String) e.get("url_address"));
				temp.setState((Integer) e.get("state"));
				temp.setNoticeType((Integer) e.get("notice_type"));
				temp.setCoverUrl((String) e.get("cover_url"));
				temp.setSummaryInfo((String) e.get("summary_info"));
				temp.setApproval_user((String) e.get("approval_user"));
				temp.setCreator((String) e.get("fullName"));
				temp.setModifier((String) e.get("modifier"));
				temp.setIsEnabled((String) e.get("isEnabled"));
				temp.setContentTxt((String) e.get("content_txt"));
				temp.setFullName((String) e.get("creator"));
				temp.setContentType((Integer) e.get("content_type"));
				if(null == e.get("isApproval")){
					temp.setIsApproval(0);
				}else{
					temp.setIsApproval(Integer.parseInt(e.get("isApproval").toString()));
				}
				if(null == e.get("isPublish")){
					temp.setIsPublish(1);
				}else{
					temp.setIsPublish(Integer.parseInt(e.get("isPublish").toString()));
				}
				if(null == e.get("approvalType")){
					temp.setApprovalType(0);
				}else{
					temp.setApprovalType(Integer.parseInt(e.get("approvalType").toString()));
				}
				temp.setRoleId(e.get("roleId") == null ? "" : e.get("roleId").toString());
				temp.setRoleName(e.get("roleName") == null ? "" : e.get("roleName").toString());
				String url = hostUrl + wxAppNoticeUrl.replace("@id", e.get("id") == null ? "" : e.get("id").toString()) + "&sourceType=1";
				url=url+"&approvalType="+temp.getApprovalType()+"&isApproval="+temp.getIsApproval();
				temp.setUrl_path(url);
			
				resultList.add(temp);
			}
			page.setItems(resultList);

			return AppResultUtil.createSuccesDto(AppConstants.SUCCESS_CODE, page);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto(AppConstants.RESULTCODE_ILLEGAL, e.getMessage());
		}
	}

	/**
	 * 获取短信消息列表
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getPhoneList")
	@ResponseBody
	public AppResultDto getPhoneList(HttpServletRequest request, HttpServletResponse response, String orgIds) throws Exception {
		String userName = baseRedisService.get(request.getHeader("token"));
		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		User                    user         = userManager.getUserByUsername2(userName);
		String     state    = request.getParameter("state");
		String     pageNo   = request.getParameter("pageNo");
		String     pageSize = request.getParameter("pageSize");
		if (StringUtils.isEmpty(pageNo)) {
			pageNo = "1";
		}
		if (StringUtils.isEmpty(pageSize)) {
			pageSize = "10";
		}
		HashMap<String, Object> map = new HashMap<String, Object>();
		if (!StringUtils.isEmpty(state)) {
			map.put("state", state);
		}
		if (!StringUtils.isEmpty(orgIds)) {
			map.put("orgIds", orgIds);
		}
		
		//当前登录的人的角色id
		String roleIds       = request.getParameter("roleIds");
		if(StringUtils.isNotBlank(roleIds)){
			map.put("roleIds", roleIds);
		}else{
			roleIds=getRoleIds(user);
			map.put("roleIds", roleIds);
		}
		
		try {
			Page page = phoneMessageManager.getDataList(map, Integer.parseInt(pageNo), Integer.parseInt(pageSize));

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

				SimpleDateFormat sdf       = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
				SimpleDateFormat sdfResult = new SimpleDateFormat("M月d日 HH:mm");
				if (StringUtils.isNotEmpty((String) e.get("createTime"))) {
					Date date = sdf.parse((String) e.get("createTime"));
					temp.setCreateTime(sdfResult.format(date));
				}
				if (StringUtils.isNotEmpty((String) e.get("approval_time"))) {
					Date date = sdf.parse((String) e.get("approval_time"));
					temp.setApproval_time(sdfResult.format(date));
				}
				if (StringUtils.isNotEmpty((String) e.get("modifierTime"))) {
					Date date = sdf.parse((String) e.get("modifierTime"));
					temp.setModifyTime(sdfResult.format(date));
				}
				if (StringUtils.isNotEmpty((String) e.get("send_time"))) {
					Date date = sdf.parse((String) e.get("send_time"));
					temp.setSend_time(sdfResult.format(date));
				}
				int stateType = Integer.parseInt(e.get("state") == null ? "3" : e.get("state").toString());
				temp.setId((Integer) e.get("id"));
				temp.setContent((String) e.get("content"));
				temp.setPhones((String) e.get("phones"));
				temp.setState((Integer) e.get("state"));
				temp.setPhones_quantity((Integer) e.get("phones_quantity"));
				temp.setPlatform_id((String) e.get("platform_id"));
				temp.setApproval_user((String) e.get("approval_user"));
				temp.setCreator((String) e.get("fullName"));
				temp.setModifier((String) e.get("modifier"));
				temp.setIsEnabled((String) e.get("isEnabled"));
				temp.setTotal((Integer) e.get("total"));
				temp.setFullName((String) e.get("creator"));
				temp.setMsgCost((Integer) e.get("phones_quantity"));
				if(null == e.get("isApproval")){
					temp.setIsApproval(0);
				}else{
					temp.setIsApproval(Integer.parseInt(e.get("isApproval").toString()));
				}
				if(null == e.get("isPublish")){
					temp.setIsPublish(1);
				}else{
					temp.setIsPublish(Integer.parseInt(e.get("isPublish").toString()));
				}
				if(null == e.get("approvalType")){
					temp.setApprovalType(0);
				}else{
					temp.setApprovalType(Integer.parseInt(e.get("approvalType").toString()));
				}
				temp.setRoleId(e.get("roleId") == null ? "" : e.get("roleId").toString());
				temp.setRoleName(e.get("roleName") == null ? "" : e.get("roleName").toString());
				//0审核界面 否则详情界面
				if (stateType == 0) {
					String url = hostUrl + wxMsgAuditUrl.replace("@id", e.get("id") == null ? "" : e.get("id").toString());
					url=url+"&approvalType="+temp.getApprovalType()+"&isApproval="+temp.getIsApproval();
					temp.setUrl_path(url);
				} else {
					String url = hostUrl + wxMsgUrl.replace("@id", e.get("id") == null ? "" : e.get("id").toString());
					url=url+"&approvalType="+temp.getApprovalType()+"&isApproval="+temp.getIsApproval();
					temp.setUrl_path(url);
				}
				resultList.add(temp);
			}
			page.setItems(resultList);

			return AppResultUtil.createSuccesDto(AppConstants.SUCCESS_CODE, page);
		} catch (Exception e) {
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto(AppConstants.RESULTCODE_ILLEGAL, e.getMessage());
		}

	}

	/**
	 * 获取邮件消息列表
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getEmailList")
	public AppResultDto getEmailList(HttpServletRequest request, HttpServletResponse response, String orgIds) throws Exception {
		String userName = baseRedisService.get(request.getHeader("token"));
		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		User                    user         = userManager.getUserByUsername2(userName);
		String     state    = request.getParameter("state");
		String     pageNo   = request.getParameter("pageNo");
		String     pageSize = request.getParameter("pageSize");
		if (StringUtils.isEmpty(pageNo)) {
			pageNo = "1";
		}
		if (StringUtils.isEmpty(pageSize)) {
			pageSize = "10";
		}
		HashMap<String, Object> map = new HashMap<String, Object>();
		if (!StringUtils.isEmpty(state)) {
			map.put("state", state);
		}
		if (!StringUtils.isEmpty(orgIds)) {
			map.put("orgIds", orgIds);
		}
		
		//当前登录的人的角色id
		String roleIds       = request.getParameter("roleIds");
		if(StringUtils.isNotBlank(roleIds)){
			map.put("roleIds", roleIds);
		}else{
			roleIds=getRoleIds(user);
			map.put("roleIds", roleIds);
		}
		
		try {
			Page page = emailSendManager.getDataList(map, Integer.parseInt(pageNo), Integer.parseInt(pageSize));

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

				SimpleDateFormat sdf       = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
				SimpleDateFormat sdfResult = new SimpleDateFormat("M月d日 HH:mm");
				if (StringUtils.isNotEmpty((String) e.get("createTime"))) {
					Date date = sdf.parse((String) e.get("createTime"));
					temp.setCreateTime(sdfResult.format(date));
				}
				if (StringUtils.isNotEmpty((String) e.get("approval_time"))) {
					Date date = sdf.parse((String) e.get("approval_time"));
					temp.setApproval_time(sdfResult.format(date));
				}
				if (StringUtils.isNotEmpty((String) e.get("modifierTime"))) {
					Date date = sdf.parse((String) e.get("modifierTime"));
					temp.setModifyTime(sdfResult.format(date));
				}
				if (StringUtils.isNotEmpty((String) e.get("send_time"))) {
					Date date = sdf.parse((String) e.get("send_time"));
					temp.setSend_time(sdfResult.format(date));
				}
				int stateType = Integer.parseInt(e.get("state") == null ? "3" : e.get("state").toString());

				temp.setId((Integer) e.get("id"));
				temp.setRecipient_email((String) e.get("recipient_email"));
				temp.setSsender_email((String) e.get("ssender_email"));
				temp.setState((Integer) e.get("state"));
				temp.setEmail_theme((String) e.get("email_theme"));
				temp.setEmail_centent((String) e.get("email_centent"));
				temp.setContentTxt((String) e.get("contentTxt"));
				temp.setEmailaccount_id((Integer) e.get("emailaccount_id"));
				temp.setAttach_ment((String) e.get("attach_ment"));
				temp.setApproval_user((String) e.get("approval_user"));
				temp.setCreator((String) e.get("fullName"));
				temp.setModifier((String) e.get("modifier"));
				temp.setIsEnabled((String) e.get("isEnabled"));
				temp.setTotal((Integer) e.get("total"));
				temp.setFullName((String) e.get("creator"));
				if (temp.getAttach_ment() != null && temp.getAttach_ment().length() != 0) {
					temp.setAttach_ment_count(temp.getAttach_ment().split(",").length);
				}
				
				if(null == e.get("isApproval")){
					temp.setIsApproval(0);
				}else{
					temp.setIsApproval(Integer.parseInt(e.get("isApproval").toString()));
				}
				if(null == e.get("isPublish")){
					temp.setIsPublish(1);
				}else{
					temp.setIsPublish(Integer.parseInt(e.get("isPublish").toString()));
				}
				if(null == e.get("approvalType")){
					temp.setApprovalType(0);
				}else{
					temp.setApprovalType(Integer.parseInt(e.get("approvalType").toString()));
				}
				temp.setRoleId(e.get("roleId") == null ? "" : e.get("roleId").toString());
				temp.setRoleName(e.get("roleName") == null ? "" : e.get("roleName").toString());
				//0审核界面 否则详情界面
				if (stateType == 0) {
					String url = hostUrl + wxEmailAuditUrl.replace("@id", e.get("id") == null ? "" : e.get("id").toString());
					url=url+"&approvalType="+temp.getApprovalType()+"&isApproval="+temp.getIsApproval();
					temp.setUrl_path(url);
				} else {
					String url = hostUrl + wxEmailUrl.replace("@id", e.get("id") == null ? "" : e.get("id").toString());
					url=url+"&approvalType="+temp.getApprovalType()+"&isApproval="+temp.getIsApproval();
					temp.setUrl_path(url);
				}
				resultList.add(temp);
			}
			page.setItems(resultList);

			return AppResultUtil.createSuccesDto(AppConstants.SUCCESS_CODE, page);
		} catch (Exception e) {
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto(AppConstants.RESULTCODE_ILLEGAL, e.getMessage());
		}

	}

	/**
	 * 获取微信模板消息列表
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getWxList")
	public AppResultDto getWxList(HttpServletRequest request, HttpServletResponse response, String orgIds) throws Exception {
		String userName = baseRedisService.get(request.getHeader("token"));
		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		User                    user         = userManager.getUserByUsername2(userName);
		String state    = request.getParameter("state");
		String pageNo   = request.getParameter("pageNo");
		String pageSize = request.getParameter("pageSize");
		if (StringUtils.isEmpty(pageNo)) {
			pageNo = "1";
		}
		if (StringUtils.isEmpty(pageSize)) {
			pageSize = "10";
		}
		HashMap<String, Object> map = new HashMap<String, Object>();
		if (!StringUtils.isEmpty(state)) {
			map.put("state", state);
		}
		if (!StringUtils.isEmpty(orgIds)) {
			map.put("orgIds", orgIds);
		}
		
		
		//当前登录的人的角色id
		//当前登录的人的角色id
		String roleIds       = request.getParameter("roleIds");
		if(StringUtils.isNotBlank(roleIds)){
			map.put("roleIds", roleIds);
		}else{
			roleIds=getRoleIds(user);
			map.put("roleIds", roleIds);
		}
		List<String> roleList = new ArrayList<>();
		if(StringUtils.isNotBlank(roleIds)){
			String [] roleArr=roleIds.split(",");
			if(null != roleArr && roleArr.length > 0 ){
				roleList = Arrays.asList(roleArr);
			}
		}
		
		try {
			Page page = wxtemplateMessageManager.getDataList(map, Integer.parseInt(pageNo), Integer.parseInt(pageSize));

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

				SimpleDateFormat sdf       = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
				SimpleDateFormat sdfResult = new SimpleDateFormat("M月d日 HH:mm");
				if (StringUtils.isNotEmpty((String) e.get("createTime"))) {
					Date date = sdf.parse((String) e.get("createTime"));
					temp.setCreateTime(sdfResult.format(date));
				}
				if (StringUtils.isNotEmpty((String) e.get("approval_time"))) {
					Date date = sdf.parse((String) e.get("approval_time"));
					temp.setApproval_time(sdfResult.format(date));
				}
				if (StringUtils.isNotEmpty((String) e.get("modifierTime"))) {
					Date date = sdf.parse((String) e.get("modifierTime"));
					temp.setModifyTime(sdfResult.format(date));
				}
				temp.setId((Integer) e.get("id"));
				temp.setWechat_template_id((Integer) e.get("wechat_template_id"));
				temp.setOpen_id((String) e.get("open_id"));
				temp.setTitle((String) e.get("title"));
				temp.setUrl((String) e.get("url"));
				Integer states=(Integer) e.get("state");
				temp.setState(states);
				temp.setApproval_user((String) e.get("approval_user"));
				temp.setCreator((String) e.get("fullName"));
				temp.setModifier((String) e.get("modifier"));
				temp.setIsEnabled((String) e.get("isEnabled"));
				temp.setTotal((Integer) e.get("total"));
				temp.setFullName((String) e.get("creator"));

				WxtemplateMessageTypeModel typeModel = wxTypeManager.get(temp.getWechat_template_id());
				if (wxPubManager.exists(typeModel.getWechat_account_id())) {
					WxPublicno wxPublicno = wxPubManager.get(typeModel.getWechat_account_id());
					if (null != wxPublicno) {
						temp.setName(wxPublicno.getName());
					}
				}
				temp.setIsApproval(0);
				temp.setRoleId("");
				temp.setRoleName("");
				temp.setIsPublish(0);
				
				Integer org=null;
				if(e.containsKey("orgId") && null != e.get("orgId") && StringUtils.isNotBlank(e.get("orgId").toString())){
					org=Integer.parseInt(e.get("orgId").toString());
					temp.setOrgId(org);
				}
				
				Integer approvalTypeId=null;
				if(null != e.get("approvalType") && StringUtils.isNotBlank(e.get("approvalType").toString())){
					approvalTypeId=Integer.parseInt(e.get("approvalType").toString());
				}
				if(null == approvalTypeId){
					approvalTypeId=0;
				}
				temp.setApprovalType(approvalTypeId);
				if(null != approvalTypeId && 0 != approvalTypeId){
					temp.setIsPublish(0);
					Map<String,Object> roleMap=noticeApprovalsetManager.getRoleIdByOrderId(org, CodeConstants.APPROVAL_TYPE_NOTICE,CodeConstants.ORDER_TYPE_TEMPLE, approvalTypeId, temp.getId());
					String roleId="";
					if(roleMap.containsKey("roleId") && null != roleMap.get("roleId") && StringUtils.isNotBlank(roleMap.get("roleId").toString())){
						roleId=roleMap.get("roleId").toString();
					}
					String roleName=roleMap == null ? "" : roleMap.get("roleName") == null ? "" : roleMap.get("roleName") .toString();
					temp.setRoleId(roleId);
					temp.setRoleName(roleName);
					//不为空则和当前登录的角色做比对,存在当前的角色中，订单状态为未审核，则代表有审核权限
					if(StringUtils.isNotBlank(roleId) && roleList.contains(roleId) && 0 == temp.getState()){
						temp.setIsApproval(1);
					}
				}else{
					if(0 == states.intValue()){
						temp.setIsPublish(1);
					}
				}
				
				
				String url = hostUrl + wxWechatUrl.replace("@id", e.get("id") == null ? "" : e.get("id").toString());
				url=url+"&approvalType="+temp.getApprovalType()+"&isApproval="+temp.getIsApproval();
				temp.setUrl_path(url);
				
				resultList.add(temp);
			}
			page.setItems(resultList);

			return AppResultUtil.createSuccesDto(AppConstants.SUCCESS_CODE, page);
		} catch (Exception e) {
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto(AppConstants.RESULTCODE_ILLEGAL, e.getMessage());
		}


	}

}
