package com.palmnest.service.wechat.impl;

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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.palmnest.application.Constants;
import com.palmnest.application.bean.Attachment;
import com.palmnest.application.bean.UserInfo;
import com.palmnest.application.core.util.*;
import com.palmnest.application.dto.AppUserBindInfoDto;
import com.palmnest.application.dto.Articles;
import com.palmnest.application.dto.output.TemplateMessage;
import com.palmnest.application.dto.output.wechat.CustomerServiceTextMessageVo;
import com.palmnest.application.dto.output.wechat.TextContentVo;
import com.palmnest.dao.estateserve.AppUserDao;
import com.palmnest.model.estateserve.WxPublicno;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.model.notice.WxtemplateMessageConfigModel;
import com.palmnest.model.notice.WxtemplateMessageTypeModel;
import com.palmnest.service.estateserve.PublicNoManager;
import com.palmnest.service.estateserve.ScWxuserManager;
import com.palmnest.service.notice.WxtemplateMessageConfigManager;
import com.palmnest.service.notice.WxtemplateMessageTypeManager;
import com.palmnest.service.redis.BaseRedisService;
import com.palmnest.service.wechat.WeChatAccessManager;
import com.palmnest.service.wechat.WeChatApiManager;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Serializable;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component("weChatApiManager")
public class WeChatApiManagerImpl implements WeChatApiManager {


	@Autowired
	private PublicNoManager                publicNoManager;
	@Autowired
	private WeChatAccessManager            weChatAccessManager;
	@Autowired
	private WxtemplateMessageConfigManager wxtemplateMessageConfigManager;
	@Autowired
	private ScWxuserManager                scWxuserManager;
	@Autowired
	private WxtemplateMessageTypeManager   wxtemplateMessageTypeManager;
	@Autowired
	private AppUserDao appuserDao;
	@Autowired
	private BaseRedisService baseRedisService;

	@Override
	public boolean checkSignature(String signature, String timestamp,
								  String nonce) throws Exception {
		return true;
	}

	@Override
	public String getAccessToken(String developId) throws Exception {
		//40001 失效  {"errcode":45009,"errmsg":"api freq out of limit"}
		//验证access_token 是否失效
		/*String access_token="";
//		String resutlJson=HttpKit.get(Constants.GETMENU_URL.concat(Constants.CacheMap.get(developId)));
		log.info("getAccessToken,resutlJson："+resutlJson);
		@SuppressWarnings("unchecked")
		Map<String,String> resultMap=JSONObject.parseObject(resutlJson, Map.class);
		if("40001".equals(resultMap.get("errcode"))){
			access_token=weChatAccessManager.getAccessToken(developId);
		}
		else{
//			if(Constants.CacheMap.get(developId)==null){
				access_token=weChatAccessManager.getAccessToken(developId);
			}
			else{
//				access_token=Constants.CacheMap.get(developId);
			}
		}*/
//		String access_token = Constants.CacheMap.get(developId);
		String access_token =baseRedisService.get(Constants.JSAPI_ACCESS_TOKEN+developId);
		if (StringUtils.isBlank(access_token)) {
			access_token = weChatAccessManager.getAccessToken(developId);
		}
		log.info("access_token:" + access_token);
		return access_token;
	}

	@Override
	public UserInfo getUserInfo(String developId, String openid) {

		String jsonStr;

		try {
			jsonStr = HttpKit.get(Constants.USER_INFO_URI.concat(getAccessToken(developId)).concat("&openid=" + openid).concat("&lang=zh_CN"));
			log.info("getUserInfo,jsonStr:" + jsonStr);

			if (jsonStr != null && jsonStr.trim().length() > 0) {

				JSONObject obj = JSONObject.parseObject(jsonStr);
				if (obj.get("errcode") != null) {
					return null;
				}
				//关注的用户，才可以取微信个人资料信息
				if ("1".equals(obj.get("subscribe").toString())) {
					UserInfo user = JSONObject.toJavaObject(obj, UserInfo.class);
					return user;
				}
			}
		} catch (KeyManagementException e) {
			log.error("wechatapiservice getUserInfo occur error.{}", e, e.getMessage());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchProviderException e) {
			log.error("wechatapiservice getUserInfo occur error.{}", e, e.getMessage());
		} catch (IOException e) {
			log.error("wechatapiservice getUserInfo occur error.{}", e, e.getMessage());
		} catch (Exception e) {
			log.error("wechatapiservice getUserInfo occur error.{}", e, e.getMessage());
		}
		return null;
	}

	@Override
	public boolean createMenu(String developId, String params) throws Exception {
		String jsonStr = HttpKit.post(Constants.CREATEMENU_URL.concat(getAccessToken(developId)), params);
		log.info(jsonStr);
		Map<String, Object> map = JSON.parseObject(jsonStr, Map.class);
		return "0".equals(map.get("errcode").toString());
	}

	@Override
	public String getMenuInfo(String developId) throws Exception {
		return HttpKit.get(Constants.GETMENU_URL.concat(getAccessToken(developId)));
	}

	@Override
	public boolean deleteMenu(String developId) throws Exception {
		String              jsonStr = HttpKit.get(Constants.DELEMENU_URL.concat(getAccessToken(developId)));
		Map<String, Object> map     = JSON.parseObject(jsonStr, Map.class);
		return "0".equals(map.get("errcode").toString());
	}

	/**
	 * 网页授权获取用户信息  https://api.weixin.qq.com/sns/oauth2/access_token
	 * code 是 https://open.weixin.qq.com/connect/oauth2/authorize scope=snsapi_base 微信返回的
	 * state 也是上面参数转过来的 用来查询服务号 信息
	 * 这里代理code 是随机的 用来访问用户我信息(相当于访问我的信息的一个临时token
	 * 返回参数:{"access_token":"ACCESS_TOKEN","expires_in":7200,"refresh_token":"REFRESH_TOKEN","openid":"OPENID","scope":"SCOPE"}
	 */
	@Override
	public Map<String, String> oauth2(String code, String state)
			throws Exception {

		Map<String, String> retMap = new HashMap<String, String>();
		if (StringUtils.isNotEmpty(state)) {
			WxPublicno wxPublicno = publicNoManager.getWxPublicnoById(Integer.parseInt(state));
			if (wxPublicno != null) {
				String grant_type = "authorization_code";
				String URL        = Constants.OATH2_URL + "?appid=" + wxPublicno.getAppId() + "&secret=" + wxPublicno.getAppSecret() + "&code=" + code + "&grant_type=" + grant_type;
				String jsonStr    = HttpKit.get(URL);
				retMap.put("developid", wxPublicno.getDevelopId());
				retMap.put("jsonStr", jsonStr);
			} else {
				//如果错误 可能是个人的code id和提供的 微信服务号信息不对
				log.warn("WeChatApiManagerImpl oauth2() state was error." + state);
			}
		}

		return retMap;
	}

	@Override
	public Attachment getMedia(String developId, String mediaId) throws Exception {
		String url = Constants.GET_MEDIA_URL + getAccessToken(developId) + "&media_id=" + mediaId;
		return HttpKit.download(url);
	}

	@Override
	public <T extends Serializable> String sendMsg(T msg, String touser,
												   String msgtype, String developId) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("touser", touser);
		map.put("msgtype", msgtype);
		map.put(msgtype, msg);

		String sendMsg = JSONObject.toJSONString(map).replace("picUrl", "picurl");
		log.info(DateUtils.getDate("yyyy-MM-dd HH:ss:mm") + " sendMsg:" + sendMsg);
		String result = HttpKit.post(Constants.MESSAGE_URL.concat(getAccessToken(developId)), sendMsg);

		Map<String, Object> resultMap = JSON.parseObject(result, Map.class);
		Integer             errcode   = (Integer) resultMap.get("errcode");
		//access_token超时,重新初始化
		if (errcode.intValue() == 42001) {
			//重新再发送一遍
			log.info("sendMsg again.");
			result = HttpKit.post(Constants.MESSAGE_URL.concat(weChatAccessManager.getAccessToken(developId)), sendMsg);
		}
		return result;
	}

	@Override
	public String sendTemplateMsg(String developId, String jsonMsg)
			throws Exception {
		return HttpKit.post(Constants.TEMPLATE_URL.concat(getAccessToken(developId)), jsonMsg);
	}

	@Override
	public String sendTemplateMsg01(Map<String, String> paramMap) {

		StringBuffer jsonStr = new StringBuffer("{");
		jsonStr.append("\"touser\":\"" + paramMap.get("openId") + "\",");
		jsonStr.append("\"template_id\":\"" + paramMap.get("templateId") + "\",");
		jsonStr.append("\"url\":\"" + paramMap.get("url") + "\",");
		jsonStr.append("\"data\":{ \"first\": {\"value\":\"" + paramMap.get("title") + "\",\"color\":\"#173177\"},");
		jsonStr.append("\"keyword1\":{\"value\":\"" + paramMap.get("orderNo") + "\", \"color\":\"#173177\" },");
		jsonStr.append("\"keyword2\":{\"value\":\"" + paramMap.get("vistorName") + "\", \"color\":\"#173177\" },");
		jsonStr.append("\"keyword3\":{\"value\":\"" + paramMap.get("address") + "\", \"color\":\"#173177\" },");
		jsonStr.append("\"keyword4\":{\"value\":\"" + paramMap.get("remak") + "\", \"color\":\"#173177\" },");
		jsonStr.append("\"keyword5\":{\"value\":\"" + paramMap.get("startTime") + "\", \"color\":\"#173177\" },");
		jsonStr.append("\"remark\":{\"value\":\"查看详情，请点击这里，请及时处理！\", \"color\":\"#173177\" }");
		jsonStr.append(" } }");

		try {
			String retMsg = sendTemplateMsg(paramMap.get("developId"), jsonStr.toString());
			log.info("sendTemplateMsg retMsg:" + retMsg);
		} catch (Exception e) {
			log.error("sendTemplateMsg occur error.{}", e, e.getCause());
		}
		return null;
	}

	@Override
	public String sendTemplateMsg02(Map<String, String> paramMap) {
		StringBuffer jsonStr = new StringBuffer("{");
		jsonStr.append("\"touser\":\"" + paramMap.get("openId") + "\",");
		jsonStr.append("\"template_id\":\"" + paramMap.get("templateId") + "\",");
		if (StringUtils.isNotBlank(paramMap.get("url"))) {
			jsonStr.append("\"url\":\"" + paramMap.get("url") + "\",");
		} else {
			jsonStr.append("\"url\":\"\",");
		}
		jsonStr.append("\"data\":{ \"first\": {\"value\":\"" + paramMap.get("title") + "\",\"color\":\"#000000\"},");
		jsonStr.append("\"keyword1\":{\"value\":\"" + paramMap.get("type") + "\", \"color\":\"#000000\" },");
		jsonStr.append("\"keyword2\":{\"value\":\"" + paramMap.get("result") + "\", \"color\":\"#000000\" },");
		jsonStr.append("\"keyword3\":{\"value\":\"" + paramMap.get("suggestion") + "\", \"color\":\"#000000\" },");
		jsonStr.append("\"remark\":{\"value\":\"" + paramMap.get("remark") + "\", \"color\":\"#173177\" }");
		jsonStr.append(" } }");
		try {
			String retMsg = sendTemplateMsg(paramMap.get("developId"), jsonStr.toString());
			log.info("sendTemplateMsg retMsg:" + retMsg);
			return retMsg;
		} catch (Exception e) {
			log.error("sendTemplateMsg occur error.{}", e, e.getCause());
		}
		return null;
	}

	@Override
	public String sendTemplateMsg03(Map<String, String> paramMap) {
		StringBuffer jsonStr = new StringBuffer("{");
		/*jsonStr.append("\"touser\":\""+paramMap.get("openId")+"\",");
		jsonStr.append("\"template_id\":\""+paramMap.get("templateId")+"\",");
		jsonStr.append("\"url\":\""+paramMap.get("url")+"\",");
		jsonStr.append("\"data\":{ \"first\": {\"value\":\""+paramMap.get("title")+"\",\"color\":\"#173177\"},");
		jsonStr.append("\"OrderSn\":{\"value\":\""+paramMap.get("orderNum")+"\", \"color\":\"#000000\" },");
		jsonStr.append("\"OrderStatus\":{\"value\":\""+paramMap.get("orderStateDesc")+"\", \"color\":\"#000000\" },");
		jsonStr.append("\"remark\":{\"value\":\""+paramMap.get("remark")+"\", \"color\":\"#000000\" }");
		jsonStr.append(" } }");*/
		jsonStr.append("\"touser\":\"" + paramMap.get("openId") + "\",");
		jsonStr.append("\"template_id\":\"" + paramMap.get("templateId") + "\",");
		jsonStr.append("\"url\":\"" + paramMap.get("url") + "\",");
		jsonStr.append("\"data\":{ \"first\": {\"value\":\"" + paramMap.get("title") + "\",\"color\":\"#173177\"},");
		jsonStr.append("\"keyword1\":{\"value\":\"" + paramMap.get("orderNum") + "\", \"color\":\"#000000\" },");
		jsonStr.append("\"keyword2\":{\"value\":\"" + paramMap.get("orderStateDesc") + "\", \"color\":\"#000000\" },");
		jsonStr.append("\"remark\":{\"value\":\"" + paramMap.get("remark") + "\", \"color\":\"#000000\" }");
		jsonStr.append(" } }");
		try {
			log.info(jsonStr.toString());
			String retMsg = sendTemplateMsg(paramMap.get("developId"), jsonStr.toString());
			log.info("sendTemplateMsg03 retMsg:" + retMsg);
			return retMsg;
		} catch (Exception e) {
			log.error("sendTemplateMsg occur error.{}", e, e.getCause());
		}
		return null;
	}

	@Override
	public String sendTemplateMsg04(Map<String, String> paramMap) {
		StringBuffer jsonStr = new StringBuffer("{");
		jsonStr.append("\"touser\":\"" + paramMap.get("openId") + "\",");
		jsonStr.append("\"template_id\":\"" + paramMap.get("templateId") + "\",");
		jsonStr.append("\"url\":\"" + paramMap.get("url") + "\",");
		jsonStr.append("\"data\":{ \"first\": {\"value\":\"\",\"color\":\"#173177\"},");
		jsonStr.append("\"keyword1\":{\"value\":\"" + paramMap.get("title") + "\", \"color\":\"#000000\" },");
		jsonStr.append("\"keyword2\":{\"value\":\"" + paramMap.get("bgTime") + "\", \"color\":\"#000000\" },");
		jsonStr.append("\"keyword3\":{\"value\":\"" + paramMap.get("introduction") + "\", \"color\":\"#000000\" },");
		jsonStr.append("\"remark\":{\"value\":\"\", \"color\":\"#000000\" }");
		jsonStr.append(" } }");
		try {
			String retMsg = sendTemplateMsg(paramMap.get("developId"), jsonStr.toString());
			log.info("sendTemplateMsg retMsg:" + retMsg);
		} catch (Exception e) {
			log.error("sendTemplateMsg occur error.{}", e, e.getCause());
		}
		return null;
	}

	@Override
	public String sendTemplateMsg05(Map<String, String> paramMap) {
		StringBuffer jsonStr = new StringBuffer("{");
		/*jsonStr.append("\"touser\":\""+paramMap.get("openId")+"\",");
		jsonStr.append("\"template_id\":\""+paramMap.get("templateId")+"\",");
		jsonStr.append("\"url\":\""+paramMap.get("url")+"\",");
		jsonStr.append("\"data\":{ \"first\": {\"value\":\"\",\"color\":\"#173177\"},");
		jsonStr.append("\"keyword1\":{\"value\":\""+paramMap.get("nickName")+"\", \"color\":\"#000000\" },");
		jsonStr.append("\"keyword2\":{\"value\":\""+paramMap.get("title")+"\", \"color\":\"#000000\" },");
		jsonStr.append("\"keyword3\":{\"value\":\""+paramMap.get("bgTime")+"\", \"color\":\"#000000\" },");
		jsonStr.append("\"keyword4\":{\"value\":\""+paramMap.get("address")+"\", \"color\":\"#000000\" },");
		jsonStr.append("\"remark\":{\"value\":\""+paramMap.get("introduction")+"\", \"color\":\"#000000\" }");
		jsonStr.append(" } }");*/
		jsonStr.append("\"touser\":\"" + paramMap.get("openId") + "\",");
		jsonStr.append("\"template_id\":\"" + paramMap.get("templateId") + "\",");
		jsonStr.append("\"url\":\"" + paramMap.get("url") + "\",");
		jsonStr.append("\"data\":{ \"first\": {\"value\":\"用户名：" + paramMap.get("nickName") + "\",\"color\":\"#000000\"},");
		jsonStr.append("\"keyword1\":{\"value\":\"" + paramMap.get("title") + "\", \"color\":\"#000000\" },");
		jsonStr.append("\"keyword2\":{\"value\":\"" + paramMap.get("bgTime") + "\", \"color\":\"#000000\" },");
		jsonStr.append("\"keyword3\":{\"value\":\"" + paramMap.get("address") + "\", \"color\":\"#000000\" },");
		jsonStr.append("\"remark\":{\"value\":\"" + paramMap.get("introduction") + "\", \"color\":\"#000000\" }");
		jsonStr.append(" } }");
		try {
			String retMsg = sendTemplateMsg(paramMap.get("developId"), jsonStr.toString());
			log.info("sendTemplateMsg retMsg:" + retMsg);
		} catch (Exception e) {
			log.error("sendTemplateMsg occur error.{}", e, e.getCause());
		}
		return null;
	}

	@Override
	public Map<String, String> dealGetMediaPic(String developId,
											   String imgServerIds) {
		Map<String, String> retMap = new HashMap<String, String>();
		if (StringUtils.isNotEmpty(imgServerIds)) {
			String[]     pics            = imgServerIds.split(";");
			StringBuffer fullPathStr     = new StringBuffer();
			StringBuffer relativePathStr = new StringBuffer();
			for (String mediaId : pics) {
				try {
					Attachment attachment = getMedia(developId, mediaId);
					if (attachment != null) {
						String relativePath = FileUploadUtils.uploadFile(attachment.getFileStream(), attachment.getSuffix());
						String fullPath     = FileUploadUtils.getVisitPrefix() + relativePath;
						relativePathStr.append(relativePath + ";");
						fullPathStr.append(fullPath + ";");
					} else {
						//更新AccessToken
						weChatAccessManager.updateAccessToken();
						attachment = getMedia(developId, mediaId);
						String relativePath = FileUploadUtils.uploadFile(attachment.getFileStream(), attachment.getSuffix());
						String fullPath     = FileUploadUtils.getVisitPrefix() + relativePath;
						relativePathStr.append(relativePath + ";");
						fullPathStr.append(fullPath + ";");
					}
				} catch (Exception e) {
					log.error("dealGetMediaPic occur error.{}", e.getCause(), e.getMessage());
					log.error(LogExceptionStackUtil.LogExceptionStack(e));
				}
			}
			log.info("relativePathStr:" + relativePathStr.toString());
			log.info("fullPathStr:" + fullPathStr.toString());
			retMap.put("relativePathStr", relativePathStr.toString());
			retMap.put("fullPathStr", fullPathStr.toString());
		}
		return retMap;
	}

	@Override
	public String sendTemplateMsg06(Map<String, String> paramMap) {
//		StringBuffer jsonStr=new StringBuffer("{");
//		jsonStr.append("\"touser\":\""+paramMap.get("openId")+"\",");
//		jsonStr.append("\"template_id\":\""+paramMap.get("templateId")+"\",");
//		jsonStr.append("\"url\":\""+paramMap.get("url")+"\",");
//		jsonStr.append("\"data\":{ \"first\": {\"value\":\""+paramMap.get("title")+"\",\"color\":\"#173177\"},");
//		jsonStr.append("\"orderMoneySum\":{\"value\":\""+paramMap.get("price")+"\", \"color\":\"#000000\" },");
//		jsonStr.append("\"orderProductName\":{\"value\":\""+paramMap.get("productName")+"\", \"color\":\"#000000\" },");
//		jsonStr.append("\"Remark\":{\"value\":\""+paramMap.get("remark")+"\", \"color\":\"#000000\" }");
//		jsonStr.append(" } }");
		StringBuffer jsonStr = new StringBuffer("{");
		jsonStr.append("\"touser\":\"" + paramMap.get("openId") + "\",");
		jsonStr.append("\"template_id\":\"" + paramMap.get("templateId") + "\",");
		jsonStr.append("\"url\":\"" + paramMap.get("url") + "\",");
		jsonStr.append("\"data\":{ \"first\": {\"value\":\"" + paramMap.get("title") + "\",\"color\":\"#173177\"},");
		jsonStr.append("\"keyword1\":{\"value\":\"" + paramMap.get("orderNo") + "\", \"color\":\"#000000\" },");
		jsonStr.append("\"keyword2\":{\"value\":\"" + paramMap.get("productName") + "\", \"color\":\"#000000\" },");
		jsonStr.append("\"keyword3\":{\"value\":\"" + paramMap.get("price") + "\", \"color\":\"#000000\" },");
		jsonStr.append("\"Remark\":{\"value\":\"" + paramMap.get("remark") + "\", \"color\":\"#000000\" }");
		jsonStr.append(" } }");
		try {
			String retMsg = sendTemplateMsg(paramMap.get("developId"), jsonStr.toString());
			log.info("sendTemplateMsg retMsg:" + retMsg);
		} catch (Exception e) {
			log.error("sendTemplateMsg occur error.{}", e, e.getCause());
		}
		return null;
	}

	@Override
	public String sendTemplateMsg07(Map<String, String> paramMap) {
		StringBuffer jsonStr = new StringBuffer("{");
//		jsonStr.append("\"touser\":\""+paramMap.get("openId")+"\",");
//		jsonStr.append("\"template_id\":\""+paramMap.get("templateId")+"\",");
//		jsonStr.append("\"url\":\""+paramMap.get("url")+"\",");
//		jsonStr.append("\"data\":{ \"first\": {\"value\":\""+paramMap.get("title")+"\",\"color\":\"#173177\"},");
//		jsonStr.append("\"accountType\":{\"value\":\"充值号码\", \"color\":\"#000000\" },");
//		jsonStr.append("\"account\":{\"value\":\""+paramMap.get("mobile")+"\", \"color\":\"#000000\" },");
//		jsonStr.append("\"amount\":{\"value\":\""+paramMap.get("price")+"\", \"color\":\"#000000\" },");
//		jsonStr.append("\"result\":{\"value\":\""+paramMap.get("statusName")+"\", \"color\":\"#000000\" },");
//		jsonStr.append("\"remark\":{\"value\":\""+paramMap.get("remark")+"\", \"color\":\"#000000\" }");
//		jsonStr.append(" } }");
		jsonStr.append("\"touser\":\"" + paramMap.get("openId") + "\",");
		jsonStr.append("\"template_id\":\"" + paramMap.get("templateId") + "\",");
		jsonStr.append("\"url\":\"" + paramMap.get("url") + "\",");
		jsonStr.append("\"data\":{ \"first\": {\"value\":\"" + paramMap.get("title") + "\",\"color\":\"#173177\"},");
		jsonStr.append("\"keyword1\":{\"value\":\"" + paramMap.get("statusName") + "\", \"color\":\"#000000\" },");
		jsonStr.append("\"keyword2\":{\"value\":\"" + paramMap.get("price") + "\", \"color\":\"#000000\" },");
		jsonStr.append("\"keyword3\":{\"value\":\"" + paramMap.get("createTime") + "\", \"color\":\"#000000\" },");
		jsonStr.append("\"remark\":{\"value\":\"" + paramMap.get("remark") + "\", \"color\":\"#000000\" }");
		jsonStr.append(" } }");
		try {
			String retMsg = sendTemplateMsg(paramMap.get("developId"), jsonStr.toString());
			log.info("sendTemplateMsg retMsg:" + retMsg);
		} catch (Exception e) {
			log.error("sendTemplateMsg occur error.{}", e, e.getCause());
		}
		return null;
	}

	@Override
	public String sendTemplateMsg08(Map<String, String> paramMap) {
		StringBuffer jsonStr = new StringBuffer("{");
		jsonStr.append("\"touser\":\"" + paramMap.get("openId") + "\",");
		jsonStr.append("\"template_id\":\"" + paramMap.get("templateId") + "\",");
		jsonStr.append("\"url\":\"" + paramMap.get("url") + "\",");
		jsonStr.append("\"data\":{ \"first\": {\"value\":\"" + paramMap.get("title") + "\",\"color\":\"#173177\"},");
		jsonStr.append("\"reason\":{\"value\":\"" + paramMap.get("reason") + "\", \"color\":\"#000000\" },");
		jsonStr.append("\"refund\":{\"value\":\"" + paramMap.get("price") + "\", \"color\":\"#000000\" },");
		jsonStr.append("\"remark\":{\"value\":\"" + paramMap.get("remark") + "\", \"color\":\"#000000\" }");
		jsonStr.append(" } }");
		try {
			String retMsg = sendTemplateMsg(paramMap.get("developId"), jsonStr.toString());
			log.info("sendTemplateMsg retMsg:" + retMsg);
		} catch (Exception e) {
			log.error("sendTemplateMsg occur error.{}", e, e.getCause());
		}
		return null;
	}

	@Override
	public String sendTemplateMsg09(Map<String, String> paramMap) {
		StringBuffer jsonStr = new StringBuffer("{");
		/*jsonStr.append("\"touser\":\""+paramMap.get("openId")+"\",");
		jsonStr.append("\"template_id\":\""+paramMap.get("templateId")+"\",");
		jsonStr.append("\"url\":\""+paramMap.get("url")+"\",");
		jsonStr.append("\"data\":{ \"first\": {\"value\":\""+paramMap.get("title")+"\",\"color\":\"#173177\"},");
		jsonStr.append("\"keyword1\":{\"value\":\""+paramMap.get("name")+"\", \"color\":\"#000000\" },");
		jsonStr.append("\"keyword2\":{\"value\":\"本部\", \"color\":\"#000000\" },");
		jsonStr.append("\"remark\":{\"value\":\""+paramMap.get("remark")+"\", \"color\":\"#000000\" }");
		jsonStr.append(" } }");*/
		jsonStr.append("\"touser\":\"" + paramMap.get("openId") + "\",");
		jsonStr.append("\"template_id\":\"" + paramMap.get("templateId") + "\",");
		jsonStr.append("\"url\":\"" + paramMap.get("url") + "\",");
		jsonStr.append("\"data\":{ \"first\": {\"value\":\"" + paramMap.get("title") + "\",\"color\":\"#173177\"},");
		jsonStr.append("\"keyword1\":{\"value\":\"" + paramMap.get("type") + "\", \"color\":\"#000000\" },");
		jsonStr.append("\"keyword2\":{\"value\":\"" + paramMap.get("content") + "\", \"color\":\"#000000\" },");
		jsonStr.append("\"keyword3\":{\"value\":\"" + paramMap.get("time") + "\", \"color\":\"#000000\" },");
		jsonStr.append("\"remark\":{\"value\":\"" + paramMap.get("remark") + "\", \"color\":\"#000000\" }");
		jsonStr.append(" } }");
		try {
			String retMsg = sendTemplateMsg(paramMap.get("developId"), jsonStr.toString());
			log.info("sendTemplateMsg retMsg:" + retMsg);
			return retMsg;
		} catch (Exception e) {
			log.error("sendTemplateMsg occur error.{}", e, e.getCause());
		}
		return null;
	}

	/**
	 * 发送模板消息
	 *
	 * @param accessToken
	 * @param data
	 * @return 状态
	 */
	@Override
	public String sendTemplateWithOpenId(String developId, String templateId, String url, int wxUserId, Map<String, String> params) {

		//根据模板ID 查找模板配置id 根据模板配置id查找模板参数
		//根据微信用户id 查找openId 和 developId
		TemplateMessage tem = new TemplateMessage();
		tem.setTemplateId(templateId);
		tem.setTopColor("#00DD00");
		tem.setUrl(url);
		boolean flag         = false;
		String  errorMessage = "";
		try {
			WxUser                             user        = scWxuserManager.get(wxUserId);
			WxtemplateMessageTypeModel         messageType = wxtemplateMessageTypeManager.findBy(templateId);
			List<WxtemplateMessageConfigModel> paras       = wxtemplateMessageConfigManager.findTemplateByTempIdDefault(messageType.getId());
			for (WxtemplateMessageConfigModel para : paras) {
				if (params.get(para.getParam_key()) != null) {
					para.setValue(params.get(para.getParam_key()));
				}
			}
			tem.setTemplateParamList(paras);

			tem.setOpenId(user.getOpenId());
			//发布消息（设置参数，组建json）
			JSONObject jsonResult = JSON.parseObject(sendTemplateMsg(developId, tem.toJSON()));
			if (jsonResult != null) {
				int errorCode = jsonResult.getInteger("errcode");
				if (errorCode == 0) {
					flag = true;
				} else {
					errorMessage += jsonResult.getString("errmsg");
					System.out.println("模板消息发送失败:" + errorCode + "," + errorMessage);
					flag = false;
				}
			}

		} catch (Exception e) {
			errorMessage = "模板消息发送失败";
			e.printStackTrace();
		}
		return "模板消息发送成功";
	}

	@Override
	public String sendTemplateMsg10(Map<String, String> paramMap) {
		StringBuffer jsonStr = new StringBuffer("{");
		jsonStr.append("\"touser\":\"" + paramMap.get("openId") + "\",");
		jsonStr.append("\"template_id\":\"" + paramMap.get("templateId") + "\",");
		jsonStr.append("\"url\":\"" + paramMap.get("url") + "\",");
		jsonStr.append("\"data\":{ \"first\": {\"value\":\"" + paramMap.get("title") + "\",\"color\":\"#173177\"},");
		jsonStr.append("\"keyword1\":{\"value\":\"" + paramMap.get("room") + "\", \"color\":\"#000000\" },");
		jsonStr.append("\"keyword2\":{\"value\":\"" + paramMap.get("virName") + "\", \"color\":\"#000000\" },");
		jsonStr.append("\"keyword3\":{\"value\":\"" + paramMap.get("time") + "\", \"color\":\"#000000\" },");
//		jsonStr.append("\"keyword4\":{\"value\":\""+paramMap.get("reading")+"\", \"color\":\"#000000\" },");
		jsonStr.append("\"remark\":{\"value\":\"" + paramMap.get("remark") + "\", \"color\":\"#000000\" }");
		jsonStr.append(" } }");
		try {
			String retMsg = sendTemplateMsg(paramMap.get("developId"), jsonStr.toString());
			log.info("sendTemplateMsg retMsg:" + retMsg);
			return retMsg;
		} catch (Exception e) {
			log.error("sendTemplateMsg occur error.{}", e, e.getCause());
		}
		return null;
	}

	@Override
	public String sendTemplateMsg11(Map<String, String> paramMap) {
		StringBuffer jsonStr = new StringBuffer("{");
		jsonStr.append("\"touser\":\"" + paramMap.get("openId") + "\",");
		jsonStr.append("\"template_id\":\"" + paramMap.get("templateId") + "\",");
		jsonStr.append("\"url\":\"" + paramMap.get("url") + "\",");
		jsonStr.append("\"data\":{ \"first\": {\"value\":\"" + paramMap.get("title") + "\",\"color\":\"#173177\"},");
		jsonStr.append("\"keyword1\":{\"value\":\"" + paramMap.get("keyword1") + "\", \"color\":\"#173177\" },");
		jsonStr.append("\"keyword2\":{\"value\":\"" + paramMap.get("keyword2") + "\", \"color\":\"#173177\" },");
		jsonStr.append("\"keyword3\":{\"value\":\"" + paramMap.get("keyword3") + "\", \"color\":\"#173177\" },");
		jsonStr.append("\"keyword4\":{\"value\":\"" + paramMap.get("keyword4") + "\", \"color\":\"#173177\" },");
		jsonStr.append("\"keyword5\":{\"value\":\"" + paramMap.get("keyword5") + "\", \"color\":\"#173177\" },");
		jsonStr.append("\"remark\":{\"value\":\"" + paramMap.get("remark") + "\", \"color\":\"#000000\" }");
		jsonStr.append(" } }");
		try {
			String retMsg = sendTemplateMsg(paramMap.get("developId"), jsonStr.toString());
			log.info("sendTemplateMsg retMsg:" + retMsg);
		} catch (Exception e) {
			log.error("sendTemplateMsg occur error.{}", e, e.getCause());
		}
		return null;
	}

	@Override
	public String sendServiceMsg(String developId, String jsonMsg) throws Exception {
		return HttpKit.post(Constants.SERVICE_URL.concat(getAccessToken(developId)), jsonMsg);
	}
/**
 * 2021-06-03备份lmz
 */
//	@Override
//	public String sendServiceWithOpenId(String developId, int wxUserId, String content) {
//
//		CustomerServiceTextMessageVo vo   = new CustomerServiceTextMessageVo();
//		WxUser                       user = scWxuserManager.get(wxUserId);
//		//动态推送给绑定的微信用户
//		developId = user.getDevelopId();
//		log.info("客服消息发送developId" + developId);
//		log.info("客服消息发送wxUserId" + wxUserId);
//		log.info("客服消息发送content" + content);
//		System.out.println("developId:" + developId);
//		System.out.println("wxUserId:" + wxUserId);
//		System.out.println("content:" + content);
//
//		vo.setTouser(user.getOpenId());
//		vo.setMsgtype("text");
//		TextContentVo textContentVo = new TextContentVo();
////		textContentVo.setContent("测试客服消息，<a href='http://www.baidu.com'>点击这里跳转百度</a>");
//		textContentVo.setContent(content);
//		vo.setText(textContentVo);
//		String json = JSONObject.toJSONString(vo);
//		log.info("客服消息发送json" + json);
//		System.out.println(json);
//		//发布消息（设置参数，组建json）
//		String errorMessage = null;
//		try {
//			JSONObject jsonResult = JSON.parseObject(sendServiceMsg(developId, json));
//			if (jsonResult != null) {
//				int errorCode = jsonResult.getInteger("errcode");
//				if (errorCode == 0) {
//				} else {
//					errorMessage = jsonResult.getString("errmsg");
//					log.info("客服消息发送失败:" + errorCode + "," + errorMessage);
//					System.out.println("客服消息发送失败:" + errorCode + "," + errorMessage);
//				}
//			}
//
//		} catch (Exception e) {
//			errorMessage = "客服消息发送失败";
//			e.printStackTrace();
//			log.info("客服消息发送失败:" + e.getMessage());
//		}
//		return "客服消息发送成功";
//	}
	
	
	@Override
	public String sendServiceWithOpenId(String developId, int wxUserId, String content) {
		log.info("客服消息发送-------------------------------------------------1x");
		CustomerServiceTextMessageVo vo   = new CustomerServiceTextMessageVo();
		WxUser                       user = scWxuserManager.get(wxUserId);
		if(null == user){
			return "";
		}
		String openid=user.getOpenId();
		developId = user.getDevelopId();
		log.info("客服消息发送wxuser-----developId:" + developId+";openid:"+openid);
		if(null != user.getOrganizationId() && StringUtils.isNotBlank(user.getOpenId())){
			AppUserBindInfoDto userBind=appuserDao.getByOrgIdAndOpenId(user.getOrganizationId(), user.getOpenId());
			log.info("客服消息发送-----userBind:" +JsonUtils.toJson(userBind));
			if(null != userBind && StringUtils.isNotBlank(userBind.getBindOpenid())){
				openid=userBind.getBindOpenid();
			}
			if(null != userBind && StringUtils.isNotBlank(userBind.getBindDevelopid())){
				developId=userBind.getBindDevelopid();
			}
		}
		//动态推送给绑定的微信用户
		log.info("最终客服消息发送-----developId:" + developId+";openid:"+openid);
		log.info("客服消息发送developId" + developId);
		log.info("客服消息发送wxUserId" + wxUserId);
		log.info("客服消息发送content" + content);
		vo.setTouser(openid);
		vo.setMsgtype("text");
		TextContentVo textContentVo = new TextContentVo();
//		textContentVo.setContent("测试客服消息，<a href='http://www.baidu.com'>点击这里跳转百度</a>");
		textContentVo.setContent(content);
		vo.setText(textContentVo);
		String json = JSONObject.toJSONString(vo);
		log.info("客服消息发送json" + json);
		System.out.println(json);
		//发布消息（设置参数，组建json）
		String errorMessage = null;
		try {
			boolean isUseWxTemp = false;
			String sWxMsgTempId = "";
			WxPublicno pubVo=publicNoManager.getByDevelopId(developId);
			if(null != pubVo && null != pubVo.getIsOpenTemplate() && 1 == pubVo.getIsOpenTemplate().intValue()){
	            //开启模板消息推送
	            sWxMsgTempId = pubVo.getTemplateId();
	            if(StringUtils.isNotBlank(sWxMsgTempId))
	            {
	                isUseWxTemp = true;
	            }
	        }
			// 根据判断是否转为模板消息.
			log.info("=======isUseWxTemp：" + isUseWxTemp + "   sWxMsgTempId:" + sWxMsgTempId);
			if(isUseWxTemp)
			{//模板消息发送
				//检测内容中是否包含超链接， 模板消息文本中不能发送超链接
				String url = "";
				int idxS = -1;
				int idxEnd = -1;

				idxS = content.indexOf("<a href=");
				if(idxS != -1)
				{
					idxEnd = content.replace("\">","'>").indexOf("'>");
					url = content.substring(idxS + 9, idxEnd);
					content = content.substring(0, idxS);
				}
				 sendTemplateMsg12(openid,sWxMsgTempId,url,content,developId,"");
			}else {
				//客服消息发送
				JSONObject jsonResult = JSON.parseObject(sendServiceMsg(developId, json));
				if (jsonResult != null) {
					int errorCode = jsonResult.getInteger("errcode");
					if (errorCode == 0) {
					} else {
						errorMessage = jsonResult.getString("errmsg");
						log.info("客服消息发送失败:" + errorCode + "," + errorMessage);
						System.out.println("客服消息发送失败:" + errorCode + "," + errorMessage);
					}
				}
			}

		} catch (Exception e) {
			errorMessage = "客服消息发送失败";
			e.printStackTrace();
			log.info("客服消息发送失败1x:" + e.getMessage());
		}
		return "客服消息发送成功";
	}

	
	/**
	 * 暂时没人使用
	 */
	@Override
	public String sendCustomWithOpenId(String developId, int wxUserId,
									   List<Articles> list) {
		log.info("客服消息发送-------------------------------------------------2");
		log.info("客服消息发送developId" + developId);
		log.info("客服消息发送wxUserId" + wxUserId);
		log.info("客服消息发送content" + JSONArray.fromObject(list));
		System.out.println("developId:" + developId);
		System.out.println("wxUserId:" + wxUserId);
		System.out.println("content:" + JSONArray.fromObject(list));
		KfnewsDto news = new KfnewsDto();
		news.setArticles(list);
		BaseNewsDto dto  = new BaseNewsDto();
		WxUser      user = scWxuserManager.get(wxUserId);
		dto.setMsgtype("news");
		dto.setTouser(user.getOpenId());
		dto.setNews(news);
//		//对象转json 方式1
//		String jsonkfbean = net.sf.json.JSONObject.fromObject(dto).toString();
//		System.out.println(jsonkfbean);
		//方式2
		Gson   gson = new Gson();
		String json = gson.toJson(dto);
		System.out.println(json);
		String errorMessage = null;
		try {
			JSONObject jsonResult = JSON.parseObject(sendServiceMsg(developId, json));
			if (jsonResult != null) {
				int errorCode = jsonResult.getInteger("errcode");
				if (errorCode == 0) {
					return "客服消息发送成功";
				} else {
					errorMessage = jsonResult.getString("errmsg");
					log.info("客服消息发送失败:" + errorCode + "," + errorMessage);
					System.out.println("客服消息发送失败:" + errorCode + "," + errorMessage);
				}
			}
		} catch (Exception e) {
			errorMessage = "客服消息发送失败";
			e.printStackTrace();
			log.info("客服消息发送失败:" + e.getMessage());
		}
		System.out.println(errorMessage);
		return errorMessage;
	}

	/**
	 * AppWeiXinPayController有用到
	 */
	@Override
	public String sendCustomMsgWithOpenId(String openId, String content) {
		log.info("客服消息发送-------------------------------------------------3");
		log.info("客服消息发送openId" + openId);
		log.info("客服消息发送content" + content);
		System.out.println("openId:" + openId);
		System.out.println("content:" + content);
		CustomerServiceTextMessageVo vo = new CustomerServiceTextMessageVo();
		vo.setTouser(openId);
		vo.setMsgtype("text");
		TextContentVo textContentVo = new TextContentVo();
//		textContentVo.setContent("测试客服消息，<a href='http://www.baidu.com'>点击这里跳转百度</a>");
		textContentVo.setContent(content);
		vo.setText(textContentVo);
		String json = JSONObject.toJSONString(vo);
		log.info("客服消息发送json" + json);
		System.out.println(json);
		//发布消息（设置参数，组建json）
		String errorMessage = null;
		WxUser wxUser       = scWxuserManager.getScWxuserByOpenId(openId);
		try {
			if (wxUser != null) {
				String     developId  = wxUser.getDevelopId();
				JSONObject jsonResult = JSON.parseObject(sendServiceMsg(developId, json));
				if (jsonResult != null) {
					int errorCode = jsonResult.getInteger("errcode");
					if (errorCode == 0) {
					} else {
						errorMessage = jsonResult.getString("errmsg");
						log.info("客服消息发送失败:" + errorCode + "," + errorMessage);
						return "客服消息发送失败:" + errorCode + "," + errorMessage;
					}
				}
			} else {
				return "openId不存在";
			}
			return "success";

		} catch (Exception e) {
			errorMessage = "客服消息发送失败";
			e.printStackTrace();
			log.info("客服消息发送失败:" + e.getMessage());
			return errorMessage;
		}
	}

	@Override
	public String sendTemplateMsg12(String openId,String sWxMsgTempId,String url,String content,String developId,String currentDateStr) {
		String res="fail";
		if(!StringUtil.isNotEmpty(currentDateStr)){
			currentDateStr=DateHelper.formatDate(new Date(), DateHelper.DATE_TIME_STRING);
		}
		StringBuffer jsonStr = new StringBuffer("{");
		jsonStr.append("\"touser\":\"" + openId + "\",");
		jsonStr.append("\"template_id\":\"" + sWxMsgTempId + "\",");
		jsonStr.append("\"url\":\"" + url  + "\",");
		jsonStr.append("\"data\":{ \"first\": {\"value\":\"" + "平台消息通知" + "\",\"color\":\"#173177\"},");
		jsonStr.append("\"keyword1\":{\"value\":\"" + "平台消息通知提醒" + "\", \"color\":\"#eb280c\" },");   //标题
		jsonStr.append("\"keyword2\":{\"value\":\"" + currentDateStr + "\", \"color\":\"#173177\" },");  //发布时间
		jsonStr.append("\"keyword3\":{\"value\":\"" + content + "\", \"color\":\"#1265b1\" },");  //内容
		jsonStr.append("\"remark\":{\"value\":\"" + "" + "\", \"color\":\"#000000\" }");          //备注
		jsonStr.append(" } }");
		try {
			String retMsg = sendTemplateMsg(developId, jsonStr.toString());
			log.info("sendTemplateMsg retMsg:" + retMsg);
			JSONObject jsonResult = JSON.parseObject(retMsg);
			if (jsonResult != null) {
				int errorCode = jsonResult.getInteger("errcode");
				if (errorCode == 0) {
					res="success";
				}
			}
		} catch (Exception e) {
			log.error("sendTemplateMsg occur error.{}",e.getMessage());
			e.printStackTrace();
		}
		return res;
	}
}
