package com.palmnest.webapp.controller.notice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.Constants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.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.StringUtil;
import com.palmnest.application.core.util.WeiXinHelper;
import com.palmnest.application.dto.AuditResultVo;
import com.palmnest.application.dto.DeptGroupDto;
import com.palmnest.application.dto.OrgDto;
import com.palmnest.application.dto.output.AuditDto;
import com.palmnest.application.dto.output.AuditInfoDto;
import com.palmnest.model.TempSaverList;
import com.palmnest.model.TemplateMessage;
import com.palmnest.model.User;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.estateserve.WxPublicno;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.model.notice.ApprovalModel;
import com.palmnest.model.notice.NoticeApprovalTypeModel;
import com.palmnest.model.notice.WxtemplateConfigPara;
import com.palmnest.model.notice.WxtemplateMessageConfigModel;
import com.palmnest.model.notice.WxtemplateMessageModel;
import com.palmnest.model.notice.WxtemplateMessageTypeModel;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.service.AppUserService;
import com.palmnest.service.OrganizationManager;
import com.palmnest.service.UserManager;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.estateserve.ScWxuserManager;
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.util.CollectionUtils;
import org.springframework.util.LinkedCaseInsensitiveMap;
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.util.WebUtils;

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

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


@Slf4j
@Controller
@RequestMapping("notice/wxtemplateMessage*")
public class WxtemplateMessageController extends BaseFormController {


	@Autowired
	private WxtemplateMessageManager       wxtemplateMessageManager;
	@Autowired
	private WxtemplateMessageConfigManager wxtemplateMessageConfigManager;
	@Autowired
	private WxtemplateConfigParaManager    wxtemplateConfigParaManager;
	@Autowired
	private WxPubManager                   wxPubManager;
	@Autowired
	private WxtemplateMessageTypeManager   wxTypeManager;
	@Autowired
	private AppNoticeManager               appNoticeManager;
	@Autowired
	private UserManager                    userManager;
	@Autowired
	private AppUserService                 appUserService;
	@Autowired
	private AppUserManager                 appUserManager;
	@Autowired
	private ScWxuserManager                scWxuserManager;
	@Autowired
	private OrganizationManager            organizationManager;
	@Autowired
	private NoticeApprovalsetManager noticeApprovalsetManager;
	@Autowired
	private NoticePublicnoService noticePublicnoService;
	
	@Autowired
	private NoticeSubGroupManager noticeSubGroupManager;

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

	/**
	 * 获取微信模板消息列表
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getList")
	public void getList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject json = new JSONObject();
		//获取当前登录用户所管辖项目
		User   user   = (User) request.getSession().getAttribute("UserCache");
		String orgIds = getUserManageOrgIds(user);//例如:1,25,2

		String state       = request.getParameter("state");
		String pageNo      = request.getParameter("page");
		String pageSize    = request.getParameter("limit");
		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 orgId       = request.getParameter("orgId");

		if (StringUtils.isNotBlank(orgId)) {
			orgIds = orgId;
		}
		if (StringUtils.isEmpty(pageNo)) {
			pageNo = "1";
		}
		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);
		}
		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);
		}
		String approvalType       = request.getParameter("approvalType");
		if (!StringUtils.isEmpty(approvalType)) {
			map.put("approvalType", approvalType);
		}
		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();
			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));
				}
				Integer id=(Integer) e.get("id");
				temp.setId(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("creator"));
				temp.setModifier((String) e.get("modifier"));
				temp.setIsEnabled((String) e.get("isEnabled"));
				temp.setTotal((Integer) e.get("total"));
				temp.setFullName((String) e.get("fullName"));
				temp.setStatus_str((String) e.get("status_str"));
				temp.setFail_str((String) e.get("fail_str"));
				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());
				}
				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, id);
					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 == states){
						temp.setIsApproval(1);
					}
				}else{
					if(0 == states.intValue()){
						temp.setIsPublish(1);
					}
				}
				try {
					WxtemplateMessageTypeModel typeModel  = wxTypeManager.get(temp.getWechat_template_id());
					WxPublicno                 wxPublicno = wxPubManager.get(typeModel.getWechat_account_id());
					temp.setName(wxPublicno.getName());
				} catch (Exception e1) {
					log.info(e1.getMessage());
				}

				resultList.add(temp);
			}


			json.put("code", "200");
			json.put("data", resultList);
			json.put("msg", "success");
			json.put("count", page.getTotalCount());
			StringUtil.charSet(json, request, response);
		} catch (Exception e) {
			json.put("code", "1");
			json.put("data", "");
			json.put("msg", "fail");
			StringUtil.charSet(json, request, response);
			log.error(e.getMessage());
			e.printStackTrace();
			throw new Exception(e);
		}


	}


	/**
	 * 获取微信模板消息列表
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getListExtra")
	public void getListExtra(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject json     = new JSONObject();
		String     state    = request.getParameter("state");
		String     pageNo   = request.getParameter("page");
		String     pageSize = request.getParameter("limit");
		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);
		}
		try {
			Page page = wxtemplateMessageManager.getDataListWithWxPub(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
			json.put("code", "200");
			json.put("data", page.getItems());
			json.put("msg", "success");
			json.put("count", page.getTotalCount());
			StringUtil.charSet(json, request, response);
		} catch (Exception e) {
			json.put("code", "1");
			json.put("data", "");
			json.put("msg", "fail");
			StringUtil.charSet(json, request, response);
			log.error(e.getMessage());
			e.printStackTrace();
			throw new Exception(e);
		}


	}

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

		//审核id
		String id = request.getParameter("id");
		List<AuditDto> auditList=new ArrayList<AuditDto>();
		try {
			//审核表
			WxtemplateMessageModel model = wxtemplateMessageManager.get(Integer.parseInt(id));
			//配置表
//			List<WxtemplateMessageConfigModel> configList = wxtemplateMessageConfigManager.getWxTemplConfigByTypeId(model.getWechat_template_id());
			List<WxtemplateConfigPara> configList = wxtemplateConfigParaManager.getWxTemplConfigByTypeId(Integer.parseInt(id));
			//公众号
			WxtemplateMessageTypeModel typeModel = wxTypeManager.get(model.getWechat_template_id());

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

			List<Map<String, Object>> userList = new ArrayList<Map<String, Object>>();
			//Page page2 = wxtemplateMessageManager.getWxPublicByWxTableId(Integer.parseInt(id));
			//TemplateLibrary templateLibrary = templateLibraryManager.get(model.getWechat_template_id());

			if (null != model && null != model.getReceive_type() && (2 == model.getReceive_type() || 3 == model.getReceive_type()) && StringUtil.isNotEmpty(model.getReceive_user_id())) {
				userList = wxtemplateMessageManager.getUserlistByUserIds(model.getReceive_user_id());
			}


			String  orgName = "";
			Integer orgId   = null;
			if (null != model && null != model.getOrgId()) {
				orgId = model.getOrgId();
				TbOrganization org = organizationManager.getOrganizationById(model.getOrgId());
				if (null != org) {
					orgName = org.getName();
				}
			}

			JSONObject resultData = new JSONObject();
			
			if(null != model && null != model.getApprovalType() && 0 != model.getApprovalType().intValue()){
				auditList=noticeApprovalsetManager.getAuditList(model.getOrgId(), CodeConstants.ORDER_TYPE_TEMPLE, model.getId());
			}else{
				if(null != model.getApproval_time()){
					AuditDto auditDto=new AuditDto();
					auditDto.setApprovalOpinion("");
					if(null !=model.getState() && 1 == model.getState().intValue()){
						auditDto.setApprovalResult(1);
					}else{
						auditDto.setApprovalResult(2);
					}
					auditDto.setApprovalTime(DateHelper.formatDate(model.getApproval_time(), DateHelper.DATE_TIME_STRING));
					auditDto.setApprovalUser(model.getApproval_user());
					auditList.add(auditDto);
				}
			}
			
			String approvalTypeName="";
			if(null != model.getApprovalType() && 0 != model.getApprovalType().intValue()){
				NoticeApprovalTypeModel approvalTypeModel=noticeApprovalsetManager.findById(model.getApprovalType());
				if(null != approvalTypeModel){
					approvalTypeName=approvalTypeModel.getName();
				}
			}
			resultData.put("auditList", auditList);
			resultData.put("data1", model);      //审核信息
			resultData.put("data2", configList);//配置信息
			resultData.put("data3", wxPublicno);//公众号信息
			resultData.put("data4", typeModel);//Type表,含有模板名字
			resultData.put("data5", userList);//当发送对象为2-项目部分用户、3-导入用户时;
			resultData.put("orgName", orgName);//项目名称
			resultData.put("orgId", orgId);//项目id
			resultData.put("approvalTypeName", approvalTypeName);
			resultData.put("deptGroupList", noticeSubGroupManager.getDeptGroupDto(2, model.getId()));
			json.put("code", "200");
			json.put("data", resultData);
			json.put("msg", "success");
			StringUtil.charSet(json, request, response);
		} catch (Exception e) {
			json.put("code", "1");
			json.put("data", "");
			json.put("msg", "fail");
			StringUtil.charSet(json, request, response);
			log.error(e.getMessage());
			e.printStackTrace();
			throw new Exception(e);
		}


	}

	/**
	 * 新增微信模板配置参数消息,是新增操作,没有修改
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/saveOrUpdate")
	@ResponseBody
	public AppResultDto saveOrUpdate(@ModelAttribute("wxtemplateMessageModel") WxtemplateMessageModel wxtemplateMessage, HttpServletRequest 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());
			}
			
			Integer id = null;

			//type表Id
			String wechat_template_id = request.getParameter("wechat_template_id");
			//String wechat_template_msg_id = request.getParameter("wechat_template_msg_id");
			String title   = request.getParameter("title");
			String url     = request.getParameter("url");
			String open_id = request.getParameter("open_id");
			String orgId   = request.getParameter("orgId");
			String deptGroupJson   = request.getParameter("deptGroupJson");//部门或分组

			Integer newMsgModelId = wxtemplateMessage.getId();
			
			Integer approvalType = 0;

			if (wxtemplateMessage.getId() != null) {
				//修改
				WxtemplateMessageModel model = wxtemplateMessageManager.get(wxtemplateMessage.getId());
				model.setModifier(user.getId().toString());//修改人
//				model.setTitle(title);//标题
//				model.setUrl(url);//url
				model.setModifyTime(new Date());//修改时间
				model.setWechat_template_id(Integer.parseInt(wechat_template_id));
				model.setOpen_id(open_id);
				model.setTitle(title);
				model.setUrl(url);
				model.setState(0);
				model.setCreateTime(new Date());
				model.setCreator(user.getId().toString());
				model.setIsEnabled("1");
				model.setOrgId(Integer.parseInt(orgId));
				model.setReceive_user_id(wxtemplateMessage.getReceive_user_id());
				model.setReceive_type(wxtemplateMessage.getReceive_type());
//				if(null == wxtemplateMessage.getApprovalType()){
//					model.setApprovalType(0);
//				}else{
//					model.setApprovalType(wxtemplateMessage.getApprovalType());
//				}
				approvalType = model.getApprovalType();
				wxtemplateMessageManager.saveOrUpdate(model);
				id = model.getId();
				List<WxtemplateConfigPara> configList = wxtemplateConfigParaManager.getWxTemplConfigByTypeId(wxtemplateMessage.getId());
				Map                        map        = WebUtils.getParametersStartingWith(request, "param");
				for (int i = 1; i <= map.size(); i++) {
					if (StringUtils.isNotEmpty(request.getParameter("key" + i))
							&& StringUtils.isNotEmpty(request.getParameter("value" + i))) {
						for (WxtemplateConfigPara wxtemplateConfigPara : configList) {
							if (wxtemplateConfigPara.getParam_key().equals(request.getParameter("key" + i))) {
								wxtemplateConfigPara.setValue(request.getParameter("value" + i));
								wxtemplateConfigParaManager.updateModel(wxtemplateConfigPara);
								continue;
							}
						}
					}
				}
			} else {
				//新增
				//1.创建新审核信息
				WxtemplateMessageModel model = new WxtemplateMessageModel();
				model.setWechat_template_id(Integer.parseInt(wechat_template_id));
				model.setOpen_id(open_id);
				model.setTitle(title);
				model.setUrl(url);
				model.setState(0);
				model.setCreateTime(new Date());
				model.setCreator(user.getId().toString());
				model.setIsEnabled("1");
				model.setOrgId(Integer.parseInt(orgId));
				model.setReceive_user_id(wxtemplateMessage.getReceive_user_id());
				model.setReceive_type(wxtemplateMessage.getReceive_type());
				if(null == wxtemplateMessage.getApprovalType()){
					model.setApprovalType(0);
				}else{
					model.setApprovalType(wxtemplateMessage.getApprovalType());
				}
				approvalType = model.getApprovalType();
				//2.获取审核表新增数据的id
				newMsgModelId = wxtemplateMessageManager.save(model).getId();
				id = newMsgModelId;
				//3.插入新数据
				List<WxtemplateConfigPara> templateParams = new ArrayList<WxtemplateConfigPara>();
				Map                        map            = WebUtils.getParametersStartingWith(request, "param");
				for (int i = 1; i <= map.size(); i++) {
					if (StringUtils.isNotEmpty(request.getParameter("key" + i))
							&& StringUtils.isNotEmpty(request.getParameter("value" + i))) {
						WxtemplateConfigPara param = new WxtemplateConfigPara();
						param.setName(request.getParameter("param" + i));
						param.setParam_key(request.getParameter("key" + i));
						param.setValue(request.getParameter("value" + i));
						param.setType_id(Integer.parseInt(wechat_template_id));
						param.setMessage_id(newMsgModelId);
						wxtemplateConfigParaManager.save(param);
					}
				}

			}
			
			if(null != wxtemplateMessage && null != wxtemplateMessage.getReceive_type() && 4 == wxtemplateMessage.getReceive_type().intValue() && null != id && StringUtils.isNotEmpty(deptGroupJson)){
				//发送方式:1-按邮箱发送；2-按部门/分组发送
				List<DeptGroupDto> dtoList=JSONObject.parseArray(deptGroupJson,DeptGroupDto.class);
				if(!CollectionUtils.isEmpty(dtoList)){
					//类型：1-公告;2-微信模板;3-短信;4-邮件;
					noticeSubGroupManager.saveByDeptGroup(2, id, dtoList, createBy);
					//保存完了之后把用户信息查出来，然后保存到相应的数据里面去
					AppResultDto dto=appNoticeManager.setUserInfo(orgId, dtoList, 3);
					if("200".equals(dto.getCode())){
						wxtemplateMessage=wxtemplateMessageManager.get(id);
						wxtemplateMessage.setReceive_user_id(dto.getMsg());
						wxtemplateMessageManager.saveOrUpdate(wxtemplateMessage);
					}
				}else{
					return AppResultUtil.createErrorDto("1", "保存邮件消息失败:未选择部门或分组");
				}
			}
			
			if(null == wxtemplateMessage.getId()){
				String     pathUrl = hostUrl + wxWechatUrl.replace("@id", newMsgModelId.toString())+"&isApproval=1&approvalType="+approvalType;
				if(null != approvalType && 0 != approvalType.intValue()){
					List<User> users=noticePublicnoService.getPushMsgUserById(approvalType,Integer.parseInt(orgId), CodeConstants.ORDER_TYPE_TEMPLE, id);
					if(!CollectionUtils.isEmpty(users)){
						appNoticeManager.pushMessage(Long.parseLong(id.toString()), CodeConstants.APP_NOTICE_PUSH_CODE, pathUrl, "您有新的待审核微信模板消息，请及时审核！", "有新微信模板消息待审核", users);
					}
				}else{
					//推送消息
					List<User> users   = userManager.findByFunction(Integer.parseInt(orgId), CodeConstants.AUDIT_NOTICE_PERMISSION);
					appNoticeManager.pushMessage(Long.parseLong(newMsgModelId.toString()), CodeConstants.WEIXIN_PUSH_CODE, pathUrl, "有新公告通知待审核", "有新微信消息待审核", users);
				}
			}
			return AppResultUtil.createCommonDto("200", "success", "success");
		} catch (Exception e) {
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto("1", "保存模板消息失败:"+e.getMessage());
		}

	}


	/**
	 * 新增微信模板配置参数消息
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/update")
	@ResponseBody
	public void update(@ModelAttribute("wxtemplateMessageModel") WxtemplateMessageModel wxtemplateMessage, HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject json = new JSONObject();
		try {

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

			//审核表的Id
			String msgId = request.getParameter("id");
			//1.获取审核信息
			WxtemplateMessageModel model = wxtemplateMessageManager.get(Integer.parseInt(msgId));
			//2.更新para表数据
			List<WxtemplateConfigPara> oldDataList = wxtemplateConfigParaManager.getWxTemplConfigByTypeId(Integer.parseInt(msgId));
			Map                        map         = WebUtils.getParametersStartingWith(request, "param");
			for (int i = 1; i <= map.size(); i++) {
				if (StringUtils.isNotEmpty(request.getParameter("key" + i))
						&& StringUtils.isNotEmpty(request.getParameter("value" + i))) {
					WxtemplateConfigPara oldData = oldDataList.get(i - 1);
					oldData.setName(request.getParameter("param" + i));
					oldData.setParam_key(request.getParameter("key" + i));
					oldData.setValue(request.getParameter("value" + i));
					oldData.setType_id(model.getWechat_template_id());
					oldData.setMessage_id(model.getId());
					wxtemplateConfigParaManager.updateModel(oldData);
				}
			}
			json.put("code", "200");
			json.put("msg", "success");
			StringUtil.charSet(json, request, response);

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

	}
	/**
	 * 发送部分用户
	 * @param wxSend
	 * @param userSize
	 * @param repeat
	 * @param repeatStr
	 * @param total
	 * @param failTotal
	 * @param tem
	 * @param token
	 * @throws KeyManagementException
	 * @throws NoSuchAlgorithmException
	 * @throws NoSuchProviderException
	 * @throws IOException
	 */
	private void sendPartUser(WxtemplateMessageModel wxSend,int userSize,int repeat,StringBuilder repeatStr,int total,int failTotal,TemplateMessage tem,String token) throws KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException, IOException{
		StringBuilder sucUserIds  = new StringBuilder("");
		StringBuilder failUserIds = new StringBuilder("");
		StringBuilder failStr     = new StringBuilder("");//失败原因
		List<AppUser> users       = new ArrayList<>();
		
		String receiveUserIds = wxSend.getReceive_user_id();
		users = appUserManager.getAppUserByIds(receiveUserIds);
		List<String> openIdList = new ArrayList<String>();
		if (null != users && users.size() > 0) {
			userSize = users.size();//选择了所少个用户
			for (AppUser appUser : users) {
				if(StringUtils.isNotEmpty(appUser.getBindOpenid())){
					if (openIdList.contains(appUser.getBindOpenid())) {
						repeat++;
						repeatStr.append(appUser.getBindOpenid() + "已存在;");
					} else {
						openIdList.add(appUser.getBindOpenid());
					}
				}else{
					Integer wxUserId = appUser.getWxUserId();
					if (null != wxUserId && scWxuserManager.exists(wxUserId)) {
						WxUser wxUser = scWxuserManager.get(wxUserId);
						if (null != wxUser && StringUtils.isNotBlank(wxUser.getOpenId())) {
//								openIdSet.add(wxUser.getOpenId());
							if (openIdList.contains(wxUser.getOpenId())) {
								repeat++;
								repeatStr.append(wxUser.getOpenId() + "已存在;");
							} else {
								openIdList.add(wxUser.getOpenId());
							}
						}
					}
				}
			}
		}
		log.info("openIdList:" + JSON.toJSONString(openIdList));
		if (null != openIdList && openIdList.size() > 0) {
			//循环发送
			for (String str : openIdList) {
				tem.setOpenId(str);
				String json2      = tem.toJSON();
				String jsonResult = HttpKit.post(Constants.TEMPLATE_URL.concat(token), json2);
				log.info("审核微信模板消息jsonResult:" + jsonResult);
				Map<String, Object> map = JSON.parseObject(jsonResult, Map.class);
				if (jsonResult != null) {
					if ("0".equals(map.get("errcode").toString())) {
						total++;//发送成功个数
						sucUserIds.append(str + ";");
					} else {
						failTotal++;//发送失败个数
						failStr.append(str + "审核失败原因:" + jsonResult + ";");
						failUserIds.append(str + ";");
					}
				}
			}
		}
	}
	/**
	 * 发送所有用户
	 * @param wxSend
	 * @param userSize
	 * @param repeat
	 * @param repeatStr
	 * @param total
	 * @param failTotal
	 * @param tem
	 * @param token
	 * @param wechatAccount
	 * @param failUserIds
	 * @param sucUserIds
	 * @param failStr
	 * @throws KeyManagementException
	 * @throws NoSuchAlgorithmException
	 * @throws NoSuchProviderException
	 * @throws IOException
	 */
	private void sendAllUser(WxtemplateMessageModel wxSend,int userSize,int repeat,StringBuilder repeatStr,int total,int failTotal,TemplateMessage tem,String token,WxPublicno  wechatAccount,StringBuilder failUserIds,StringBuilder sucUserIds,StringBuilder failStr) throws KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException, IOException{
		Integer orgId = wxSend.getOrgId();
		List<String>              openIdList  = new ArrayList<String>();
		List<Map<String, Object>> orgAllUsers = wxTypeManager.findByOrgIdAndDevelopId(orgId, wechatAccount.getDevelopId());
		log.info("orgAllUsers:" + JSON.toJSONString(orgAllUsers));
		if (null != orgAllUsers && orgAllUsers.size() > 0) {
			for (int i = 0; i < orgAllUsers.size(); i++) {
				Map<String, Object> mapUser = orgAllUsers.get(i);
				String              openId  = mapUser.get("openId") == null ? "" : mapUser.get("openId").toString();
				if (openIdList.contains(openId)) {
					repeat++;
					repeatStr.append(openId + "已存在;");
				} else {
					openIdList.add(openId);
				}
			}
		}

		log.info("openIdList:" + JSON.toJSONString(openIdList));
		if (null != openIdList && openIdList.size() > 0) {
			//循环发送
			for (String str : openIdList) {
				tem.setOpenId(str);
				String json2      = tem.toJSON();
				String jsonResult = HttpKit.post(Constants.TEMPLATE_URL.concat(token), json2);
				log.info("审核微信模板消息jsonResult:" + jsonResult);
				Map<String, Object> map = JSON.parseObject(jsonResult, Map.class);
				if (jsonResult != null) {
					if ("0".equals(map.get("errcode").toString())) {
						total++;//发送成功个数
						sucUserIds.append(str + ";");
					} else {
						failTotal++;//发送失败个数
						failStr.append(str + "审核失败原因:" + jsonResult + ";");
						failUserIds.append(str + ";");
					}
				}
			}
		}
	}
	/**
	 * 审核没有开启审核类型的单据   或最后一步审核
	 * @param id
	 * @param wxSend
	 * @param userName
	 * @param state
	 * @return
	 */
	private AppResultDto approvalNotApprovalTypeOrder(Integer id,WxtemplateMessageModel wxSend,String userName,Integer state,String pathUrl){
		
		//发送成功条数计数器
		int           total     = 0;
		int           failTotal = 0;
		int           userSize  = 0;
		int           repeat    = 0;//重复个数
		StringBuilder repeatStr = new StringBuilder();
		try{
			wxSend.setApproval_user(userName);
			wxSend.setApproval_time((new Date()));
			wxSend.setState(state);
//				wxSend.setSend_time(new Date());
			String     userId   = wxSend.getCreator();

			List<User> userList = new ArrayList<User>();
			User       user2    = userManager.get(Long.parseLong(userId));
			userList.add(user2);
			//审核通过
			if (wxSend.getState() == 1) {
//					发送微信
				//获取消息模板
				//1.获取模板所有配置信息
				List<WxtemplateConfigPara> wxTemplConfigByTypeId = wxtemplateConfigParaManager.getWxTemplConfigByTypeId(wxSend.getId());
				//2.获取推送消息的公众号信息
				WxtemplateMessageTypeModel typeModel     = wxTypeManager.get(wxSend.getWechat_template_id());
				WxPublicno                 wechatAccount = wxPubManager.get(typeModel.getWechat_account_id());
				//3.封装推送信息 tem对象
				TemplateMessage tem = new TemplateMessage();

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

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

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

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

			} else if (wxSend.getState() == 0) {
				log.info("wxSend:" + JSON.toJSONString(wxSend));
				wxtemplateMessageManager.updateModel(wxSend);
				return AppResultUtil.createSuccesDto("审核状态-未审核");
				
			} else if (wxSend.getState() == 2) {
				log.info("wxSend:" + JSON.toJSONString(wxSend));
				wxtemplateMessageManager.updateModel(wxSend);
				appNoticeManager.pushMessage(Long.parseLong(id.toString()), CodeConstants.WEIXIN_PUSH_CODE, pathUrl, "您发起的微信消息已被驳回", "未审核通过", userList);
				return AppResultUtil.createSuccesDto("审核状态-已驳回");
			}
		}catch(Exception e){
			e.printStackTrace();
			log.error("审核微信模板失败:"+e.getMessage());
			return AppResultUtil.createErrorDto("100", "审核微信模板失败:"+e.getMessage());
		}
		return AppResultUtil.createErrorDto("100", "审核微信模板失败");
	}
	
	
	
	
	/**
	 * 审核微信信息
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/approvalNew")
	@ResponseBody
	public AppResultDto approvalNew(HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			User user = (User) request.getSession().getAttribute("UserCache");
			String userName = StringUtils.isNotBlank(user.getFullName()) ? user.getFullName() : user.getUsername();
			//发送成功条数计数器
			if (user == null) {
				return AppResultUtil.createErrorDto("100", "token过期");
			}
			String id    = request.getParameter("id");
			String state = request.getParameter("state");
			String approvalOpinion     = request.getParameter("approvalOpinion");
			
			log.info("approvalNew-审核订单:id" + id + ";state:" + state+";approvalOpinion:"+approvalOpinion);
			log.info("approvalNew-操作人:" + userName);
			log.info("approvalNew-审核时间:" + new Date());
			if (StringUtils.isEmpty(id)) {// 更新状态
				return AppResultUtil.createErrorDto("100", "参数异常");
			}
			WxtemplateMessageModel wxSend = wxtemplateMessageManager.get(Integer.parseInt(id));
			if(null == wxSend){
				return AppResultUtil.createErrorDto("100", "参数异常");
			}
			
			//部门分组发送时，目标用户不能为空
			if(null != wxSend.getReceive_type() && 4 == wxSend.getReceive_type().intValue() && StringUtils.isEmpty(wxSend.getReceive_user_id())){
				return AppResultUtil.createErrorDto("100", "发送的用户不能为空，无法审核");
			}
			
			String pathUrl = hostUrl + wxWechatUrl.replace("@id", id.toString());
			
			int approvalResult=2;
			if(StringUtils.isNotBlank(state) && "1".equals(state)){
				approvalResult=1;
			}
			AuditResultVo auditResultVo = new AuditResultVo();
			int haveNext=0;
			if(null != wxSend.getApprovalType() && 0 != wxSend.getApprovalType().intValue()){
				AuditInfoDto dto=new AuditInfoDto(wxSend.getOrgId(),CodeConstants.ORDER_TYPE_TEMPLE,wxSend.getId(),
						wxSend.getApprovalType(),Integer.parseInt(user.getId().toString()), userName,
						approvalResult,approvalOpinion);
				auditResultVo=noticeApprovalsetManager.saveAuditInfo(dto);
				haveNext=auditResultVo.getHaveNext();
			}
			if(2 == approvalResult || 0 == haveNext){
				AppResultDto dto=approvalNotApprovalTypeOrder(Integer.parseInt(id), wxSend, userName, Integer.parseInt(state),pathUrl);
				if(null != auditResultVo && null != auditResultVo.getApprovalModel() && !"200".equals(dto.getCode())){
					ApprovalModel approvalModel=auditResultVo.getApprovalModel();
					approvalModel.setEnabled(0);
					approvalModel.setModifier(Integer.parseInt(user.getId().toString()));
					approvalModel.setModifTime(new Date());
					noticeApprovalsetManager.updateApproval(approvalModel);
				}
				return dto;
			}else{
				pathUrl=pathUrl+"&isApproval=1&approvalType="+wxSend.getApprovalType();
				//推送消息给下一级审核人
				List<User> users=noticePublicnoService.getPushMsgUserById(wxSend.getApprovalType(), wxSend.getOrgId(), CodeConstants.ORDER_TYPE_TEMPLE, wxSend.getId());
				if(!CollectionUtils.isEmpty(users)){
					appNoticeManager.pushMessage(Long.parseLong(wxSend.getId().toString()), CodeConstants.APP_NOTICE_PUSH_CODE, pathUrl, "您有新的待审核微信模板消息，请及时审核！", "有新微信模板消息待审核", users);
				}
			}
			return AppResultUtil.createSuccesDto();
			
		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "审核异常:"+e.getMessage());
		}
	}
	


	/**
	 * 审核微信信息
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/approval")
	@ResponseBody
	public void approval(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject json = new JSONObject();
		try {
			User user = (User) request.getSession().getAttribute("UserCache");

			//发送成功条数计数器
			int           total     = 0;
			int           failTotal = 0;
			int           userSize  = 0;
			int           repeat    = 0;//重复个数
			StringBuilder repeatStr = new StringBuilder();
			if (user.getFullName() == null) {

				json.put("code", "1");
				json.put("msg", "fail");
				json.put("data", "token已过期");
				StringUtil.charSet(json, request, response);
			}
			String id    = request.getParameter("id");
			String state = request.getParameter("state");
			log.info("审核订单:id" + id + ";state:" + state);
			log.info("操作人:" + user.getFullName());
			log.info("审核时间:" + new Date());
			if (StringUtils.isNotEmpty(id)) {// 更新状态
				//审核表-id ->获取模板   ,  公众号表-wxId
				WxtemplateMessageModel wxSend = wxtemplateMessageManager.get(Integer.parseInt(id));
				wxSend.setApproval_user(user.getFullName());
				wxSend.setApproval_time((new Date()));
				wxSend.setState(Integer.parseInt(state));
//				wxSend.setSend_time(new Date());
				String     userId   = wxSend.getCreator();
				List<User> userList = new ArrayList<User>();
				User       user2    = userManager.get(Long.parseLong(userId));
				userList.add(user2);
				String pathUrl = hostUrl + wxWechatUrl.replace("@id", id.toString());
				if (wxSend.getState() == 1) {
//					发送微信
					//获取消息模板
//					WxtemplateMessageConfigModel wechatTemplate = wxtemplateMessageConfigManager.get(Integer.parseInt(id));
					//1.获取模板所有配置信息
					List<WxtemplateConfigPara> wxTemplConfigByTypeId = wxtemplateConfigParaManager.getWxTemplConfigByTypeId(wxSend.getId());
					//2.获取推送消息的公众号信息
					WxtemplateMessageTypeModel typeModel     = wxTypeManager.get(wxSend.getWechat_template_id());
					WxPublicno                 wechatAccount = wxPubManager.get(typeModel.getWechat_account_id());
					//3.封装推送信息 tem对象
					TemplateMessage tem = new TemplateMessage();

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

					//4.推送信息操作
					try {
						String token = WeiXinHelper.getToken(wechatAccount.getAppId(), wechatAccount.getAppSecret());
						if (StringUtils.isEmpty(token)) {
							json.put("code", "1");
							json.put("msg", "fail");
							json.put("data", "公众号配置错误或IP未授权");
							StringUtil.charSet(json, request, response);
						}
						StringBuilder sucUserIds  = new StringBuilder("");
						StringBuilder failUserIds = new StringBuilder("");
						StringBuilder failStr     = new StringBuilder("");//失败原因
						List<AppUser> users       = new ArrayList<>();
						if (wxSend.getReceive_type() == 2 || wxSend.getReceive_type() == 3 || wxSend.getReceive_type() == 4) {
							// 项目部分用户
							if (StringUtils.isBlank(wxSend.getReceive_user_id())) return;
							String receiveUserIds = wxSend.getReceive_user_id();
							users = appUserManager.getAppUserByIds(receiveUserIds);
							List<String> openIdList = new ArrayList<String>();
							if (null != users && users.size() > 0) {
								userSize = users.size();//选择了所少个用户
								for (AppUser appUser : users) {
									if(StringUtils.isNotEmpty(appUser.getBindOpenid())){
										if (openIdList.contains(appUser.getBindOpenid())) {
											repeat++;
											repeatStr.append(appUser.getBindOpenid() + "已存在;");
										} else {
											openIdList.add(appUser.getBindOpenid());
										}
									}else{
										Integer wxUserId = appUser.getWxUserId();
										if (null != wxUserId && scWxuserManager.exists(wxUserId)) {
											WxUser wxUser = scWxuserManager.get(wxUserId);
											if (null != wxUser && StringUtils.isNotBlank(wxUser.getOpenId())) {
//												openIdSet.add(wxUser.getOpenId());
												if (openIdList.contains(wxUser.getOpenId())) {
													repeat++;
													repeatStr.append(wxUser.getOpenId() + "已存在;");
												} else {
													openIdList.add(wxUser.getOpenId());
												}
											}
										}
									}
									
								}
							}
							log.info("openIdList:" + JSON.toJSONString(openIdList));
							if (null != openIdList && openIdList.size() > 0) {
								//循环发送
								for (String str : openIdList) {
									tem.setOpenId(str);
									String json2      = tem.toJSON();
									String jsonResult = HttpKit.post(Constants.TEMPLATE_URL.concat(token), json2);
									log.info("审核微信模板消息jsonResult:" + jsonResult);
									Map<String, Object> map = JSON.parseObject(jsonResult, Map.class);
									if (jsonResult != null) {
										if ("0".equals(map.get("errcode").toString())) {
											total++;//发送成功个数
											sucUserIds.append(str + ";");
										} else {
											failTotal++;//发送失败个数
											failStr.append(str + "审核失败原因:" + jsonResult + ";");
											failUserIds.append(str + ";");
										}
									}
								}
							}
						}else {
							// 项目所有用户
							// users = WeiXinHelper.getUserList(token); //查询当前公众号所有用户
							Integer orgId = wxSend.getOrgId();
//							users = appUserManager.getAppUserByOrgId(orgId);
							List<String>              openIdList  = new ArrayList<String>();
							List<Map<String, Object>> orgAllUsers = wxTypeManager.findByOrgIdAndDevelopId(orgId, wechatAccount.getDevelopId());
							log.info("orgAllUsers:" + JSON.toJSONString(orgAllUsers));
							if (null != orgAllUsers && orgAllUsers.size() > 0) {
								for (int i = 0; i < orgAllUsers.size(); i++) {
									Map<String, Object> mapUser = orgAllUsers.get(i);
									String              openId  = mapUser.get("openId") == null ? "" : mapUser.get("openId").toString();
									if (openIdList.contains(openId)) {
										repeat++;
										repeatStr.append(openId + "已存在;");
									} else {
										openIdList.add(openId);
									}
								}
							}

							log.info("openIdList:" + JSON.toJSONString(openIdList));
							if (null != openIdList && openIdList.size() > 0) {
								//循环发送
								for (String str : openIdList) {
									tem.setOpenId(str);
									String json2      = tem.toJSON();
									String jsonResult = HttpKit.post(Constants.TEMPLATE_URL.concat(token), json2);
									log.info("审核微信模板消息jsonResult:" + jsonResult);
									Map<String, Object> map = JSON.parseObject(jsonResult, Map.class);
									if (jsonResult != null) {
										if ("0".equals(map.get("errcode").toString())) {
											total++;//发送成功个数
											sucUserIds.append(str + ";");
										} else {
											failTotal++;//发送失败个数
											failStr.append(str + "审核失败原因:" + jsonResult + ";");
											failUserIds.append(str + ";");
										}
									}
								}
							}

						}

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

						if (failTotal > 0) {
							String msg = "选中用户个数:" + userSize + ";成功个数:" + total + ";失败个数:" + failTotal + ";重复个数:" + repeat;
							wxSend.setTotal(total);
							wxSend.setState(0);
							wxSend.setStatus_str("发送失败:失败个数:" + failTotal + ";重复信息:" + repeatStr.toString());
							if (total > 0) {
								wxSend.setState(1);
								wxSend.setStatus_str("部分成功:" + msg + ";重复信息:" + repeatStr.toString());
							}
							log.info("wxSend:" + JSON.toJSONString(wxSend));
							wxtemplateMessageManager.updateModel(wxSend);
							json.put("code", "1");
							json.put("msg", msg);
							json.put("data", "模板消息发送失败,成功账号:" + sucUserIds.toString() + ";失败账号:" + failUserIds.toString() + ";重复信息:" + repeatStr.toString());
							StringUtil.charSet(json, request, response);
							if (1 == wxSend.getState()) {
								appNoticeManager.pushMessage(Long.parseLong(id), CodeConstants.WEIXIN_PUSH_CODE, pathUrl, "您发起的微信消息已审核通过", "已审核通过", userList);
							}
						} else {
							wxSend.setTotal(total);
							wxSend.setStatus_str("发送成功:成功个数:" + total + ";重复个数:" + repeat + ";重复信息:" + repeatStr.toString());
							log.info("wxSend:" + JSON.toJSONString(wxSend));
							wxtemplateMessageManager.updateModel(wxSend);
							json.put("code", "200");
							json.put("msg", "success");
							json.put("data", "审核状态-已通过,模板消息全部发送成功");
							StringUtil.charSet(json, request, response);
//							emailSendManager.sendMesseg(id, userId, "2", "审核通过");
							appNoticeManager.pushMessage(Long.parseLong(id), CodeConstants.WEIXIN_PUSH_CODE, pathUrl, "您发起的微信消息已审核通过", "已审核通过", userList);
						}
						//设置消息返回状态
//						wxSend.setTotal(total);
//						wxtemplateMessageManager.updateModel(wxSend);
					} catch (Exception e) {
						wxSend.setTotal(total);
						wxSend.setState(0);
						log.info("wxSend:" + JSON.toJSONString(wxSend));
						wxtemplateMessageManager.updateModel(wxSend);
						json.put("code", "1");
						json.put("msg", "fail");
						json.put("data", e.getMessage());
						e.printStackTrace();
						StringUtil.charSet(json, request, response);
					}

				} else if (wxSend.getState() == 0) {
					log.info("wxSend:" + JSON.toJSONString(wxSend));
					wxtemplateMessageManager.updateModel(wxSend);
					json.put("code", "200");
					json.put("msg", "success");
					json.put("data", "审核状态-未审核");
					StringUtil.charSet(json, request, response);
				} else if (wxSend.getState() == 2) {
					log.info("wxSend:" + JSON.toJSONString(wxSend));
					wxtemplateMessageManager.updateModel(wxSend);
					json.put("code", "200");
					json.put("msg", "success");
					json.put("data", "审核状态-已驳回");
					StringUtil.charSet(json, request, response);
//						emailSendManager.sendMesseg(id, userId, "2", "被驳回");
					appNoticeManager.pushMessage(Long.parseLong(id), CodeConstants.WEIXIN_PUSH_CODE, pathUrl, "您发起的微信消息已被驳回", "未审核通过", userList);
				}
			} else {
				json.put("code", "1");
				json.put("msg", "fail");
				json.put("data", "参数错误,该id没有审核信息");
			}
		} catch (Exception e) {
			json.put("code", "1");
			json.put("msg", "fail");
			json.put("data", "参数错误:" + e.getMessage());
			e.printStackTrace();
			StringUtil.charSet(json, request, response);
		}
	}


	/**
	 * 获取微信公众号列表
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getPublicList")
	@ResponseBody
	public void getPublicList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject   json   = new JSONObject();
		String       orgIds = request.getParameter("orgIds");
		User         user   = (User) request.getSession().getAttribute("UserCache");
		List<OrgDto> dtos   = appUserService.getUserOrgs(user.getId());
		try {
			if (StringUtils.isEmpty(orgIds) || "0".equals(orgIds)) {
				if (dtos != null && dtos.size() > 0) {
					orgIds = "";
					for (int i = 0; i < dtos.size(); i++) {
						OrgDto dto = dtos.get(i);
						orgIds = orgIds + dto.getId() + ";";
					}
				}
			}
			Page page = wxtemplateMessageManager.getPublicList(orgIds);
			json.put("code", "200");
			json.put("msg", "success");
			json.put("data", page.getItems());
			StringUtil.charSet(json, request, response);
		} catch (Exception e) {
			json.put("code", "1");
			json.put("msg", "fail");
			json.put("data", "");
			StringUtil.charSet(json, request, response);
			log.error(e.getMessage());
			e.printStackTrace();
			throw new Exception(e);
		}


	}


	/**
	 * 获取消息模板列表
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getTemplateList")
	public void getTemplateList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject json = new JSONObject();
		//公众号id
		String wechat_account_id = request.getParameter("id");
		try {

			ArrayList<WxtemplateMessageTypeModel> typeList = wxtemplateMessageManager.getWxtemplateMessageTypeModelList(Integer.parseInt(wechat_account_id));
			//只需获取所有模板名字,名字在Type表中

			json.put("code", "200");
			json.put("msg", "success");
			json.put("data", typeList);
			StringUtil.charSet(json, request, response);
		} catch (Exception e) {
			json.put("code", "1");
			json.put("message", "fail");
			StringUtil.charSet(json, request, response);
			e.printStackTrace();
			log.error(e.getMessage());
			throw new Exception(e);
		}


	}


	/**
	 * 获取对应所有配置
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getTemplateConfig")
	public void getTemplateConfig(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject json   = new JSONObject();
		String     typeId = request.getParameter("id");
		try {
			WxtemplateMessageTypeModel         typeModel  = wxTypeManager.get(Integer.parseInt(typeId));
			List<WxtemplateMessageConfigModel> configList = wxtemplateMessageConfigManager.getWxTemplConfigByTypeId(Integer.parseInt(typeId));

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

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


	}


	@RequestMapping(value = "/test")
	public void test(HttpServletRequest request,
					 HttpServletResponse response) {
		String id    = request.getParameter("id");
		String msgid = request.getParameter("msgid");
		try {

			//List<WxtemplateMessageConfigModel> wxTemplConfigByTypeId = wxtemplateMessageConfigManager.getWxTemplConfigByTypeId((Integer.parseInt(id)));

			//List<WxtemplateMessageConfigModel> findTemplateByTempIdAndTempMsgId = wxtemplateMessageConfigManager.findTemplateByTempIdAndTempMsgId(Integer.parseInt(id), Integer.parseInt(msgid));

			Page page2 = wxtemplateMessageConfigManager.findTemplateByTempId(Integer.parseInt(id));
			Page page3 = wxtemplateMessageConfigManager.findAll(Integer.parseInt(id));

			boolean empty2 = page2.getItems().isEmpty();
			boolean empty3 = page3.getItems().isEmpty();


			JSONObject json = new JSONObject();
			json.put("code", "200");
			json.put("msg", "success");
			json.put("data", empty2);
			StringUtil.charSet(json, request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}


//	/**
//	 * 跳转到界面
//	 * 
//	 * @param request
//	 * @param response
//	 */
//	@RequestMapping(value = "/noticeWxSend*")
//	public ModelAndView noticeWxSend(HttpServletRequest request,
//			HttpServletResponse response) {
//		return new ModelAndView("admin/notice/noticeWxSend");
//	}
//	
//	/**
//	 * 跳转到界面-发布
//	 * 
//	 * @param request
//	 * @param response
//	 */
//	@RequestMapping(value = "/noticeWxPublish*")
//	public ModelAndView noticeWxPublish(HttpServletRequest request,
//			HttpServletResponse response) {
//		return new ModelAndView("admin/notice/noticeWxPublish");
//	}
//	/**
//	 * 跳转到界面-审核
//	 * 
//	 * @param request
//	 * @param response
//	 */
//	@RequestMapping(value = "/noticeWxVerify*")
//	public ModelAndView noticeWxVerify(HttpServletRequest request,
//			HttpServletResponse response) {
//		return new ModelAndView("admin/notice/noticeWxVerify");
//	}

	/**
	 * 删除微信公告
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/deleteNotice")
	@ResponseBody
	public void deleteNotice(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");

		User user = (User) request.getSession().getAttribute("UserCache");
//		wxtemplateMessageManager.remove(Integer.parseInt(id));
//		wxtemplateConfigParaManager.deleteByMsgId(Integer.parseInt(id));//删除关联表信息
		if (wxtemplateMessageManager.exists(Integer.parseInt(id))) {
			WxtemplateMessageModel model = wxtemplateMessageManager.get(Integer.parseInt(id));
			model.setIsEnabled("0");
			model.setModifyTime(new Date());
			if (null != user) {
				model.setModifier(user.getId() + "");
			}
			wxtemplateMessageManager.updateModel(model);
		}
		JSONObject json = new JSONObject();
		json.put("code", "200");
		json.put("msg", "success");
		StringUtil.charSet(json, request, response);
	}
}
