package com.bs.web.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.bs.system.domain.SysConfig;
import com.bs.system.mapper.SysConfigMapper;
import com.bs.system.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.bs.web.utils.SignUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 *
 * <br>
 * 名称： WeiXinUtil <br>
 * 描述： 微信工具类
 *
 * @author Tjw
 * @date 2019年8月7日 下午3:21:16
 */
@Slf4j
@Component
public class WeiXinUtil {
	// 日期格式
	private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	// 微信小程序appid
	private static String appid="wx750df5fec24d61c1" ;
	// 微信小程序appsecret
	private static String appsecret="fda079d4713bc3bdd5810ebb54dc7507";

	// 微信公众号appid
	private static String gzhappid="wxe8539d3b62c9a06c";
	// 微信公众号appsecret
	private static String gzhappsecret="84f607283501d0177ca7595f709c20ca";

	// 微信开放号appid
	private static String openAppid = "";
	// 微信开放号appsecret
	private static String openAppsecret = "";
	// 微信开放号授权回调域
	private static String openUrl = "";
	@Autowired
	private ISysConfigService sysConfigService;
	@Resource
	private SysConfigMapper sysConfigMapper;


	/**
	 *
	 * <br>
	 * 描述：设置参数值
	 *
	 * @date: 2019年8月24日 上午9:58:01
	 * @author Tjw
	 */
	private  void setConfigParam() {
		String cf_weixinUtil_appid = getSysConfig("cf_weixinUtil_appid");
		String cf_weixinUtil_appsecret = getSysConfig("cf_weixinUtil_appsecret");
/*		SysConfig config9 = getSysConfig("cf_weixinUtil_open_appid");
		String cf_weixinUtil_open_appid = config9.getConfigValue();
		SysConfig config10 = getSysConfig("cf_weixinUtil_open_appsecret");
		String cf_weixinUtil_open_appsecret = config10.getConfigValue();
		SysConfig config11 = getSysConfig("cf_weixinUtil_open_url");
		String cf_weixinUtil_open_url = config11.getConfigValue();*/

		appid = cf_weixinUtil_appid; // 微信公众号appid/**/
		appsecret = cf_weixinUtil_appsecret; // 微信公众号appsecret
		/*openAppid = cf_weixinUtil_open_appid; // 微信开放号appid
		openAppsecret = cf_weixinUtil_open_appsecret; // 微信开放号appsecret
		openUrl = cf_weixinUtil_open_url; // 微信开放号授权回调域*/
	}

	/**
	 *
	 * <br>
	 * 描述：获取openid(小程序)
	 *
	 * @param code
	 * @return
	 * @date: 2019年8月10日 下午3:25:24
	 * @author Tjw
	 */
	public  JSONObject getXCXOpenId(String code) {
		/*String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + appsecret
				+ "&code=" + code + "&grant_type=authorization_code";*/
		String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + appsecret
				+ "&js_code=" + code + "&grant_type=authorization_code";
		try {
			log.info("获取openid请求url：" + url);
			HttpResponse response = HttpRequest.get(url)
					.timeout(5 * 60 * 1000)
					.execute();
			String values = response.body();
			log.info("获取openid返回数据：" +values);
			JSONObject jsonObject = JSON.parseObject(values);
			String openId = jsonObject.getString("openid");
			String session_key = jsonObject.getString("session_key");
			String unionid = jsonObject.getString("unionid");
			openId = openId == null ? "" : openId;
			session_key = session_key == null ? "" : session_key;
			unionid = unionid == null ? "" : unionid;
			JSONObject jo = new JSONObject();
			jo.put("unionid",unionid);
			jo.put("openId",openId);
			jo.put("session_key",session_key);
			return jo;
		} catch (Exception e) {
			log.error("openId获取异常", e);
			JSONObject jo = new JSONObject();
			jo.put("msg","openId获取异常");
			jo.put("code","501");
			return jo;
		}
	}

	/**
	 *
	 * <br>
	 * 描述：获取公众号openid
	 *
	 * @param code
	 * @return
	 * @date: 2019年8月10日 下午3:25:24
	 * @author Tjw
	 */
	public  JSONObject getGZHOpenId(String code) {
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + gzhappid + "&secret=" + gzhappsecret
				+ "&code=" + code + "&grant_type=authorization_code";
		try {
			log.info("获取openid请求url：" + url);
			HttpResponse response = HttpRequest.get(url)
					.timeout(5 * 60 * 1000)
					.execute();
			String values = response.body();
			log.info("获取openid返回数据：" +values);
			JSONObject jsonObject = JSON.parseObject(values);
			String openId = jsonObject.getString("openid");
			String access_token = jsonObject.getString("access_token");
			String unionid = jsonObject.getString("unionid");
			String refresh_token = jsonObject.getString("refresh_token");
			openId = openId == null ? "" : openId;
			access_token = access_token == null ? "" : access_token;
			unionid = unionid == null ? "" : unionid;
			refresh_token = refresh_token == null ? "" : refresh_token;
			JSONObject jo = new JSONObject();
			jo.put("unionid",unionid);
			jo.put("openId",openId);
			jo.put("accessToken",access_token);
			jo.put("refreshToken",refresh_token);
			return jo;
		} catch (Exception e) {
			log.error("openId获取异常", e);
			JSONObject jo = new JSONObject();
			jo.put("msg","openId获取异常");
			jo.put("code","501");
			return jo;
		}
	}

	/**
	 * 描述：刷新access_token
	 */
	public  JSONObject getRefreshToken(String refreshToken) {
		String url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + gzhappid + "&grant_type=authorization_code"
				+ "&refresh_token=" + refreshToken;
		try {
			log.info("获取刷新access_token请求url：" + url);
			HttpResponse response = HttpRequest.get(url)
					.timeout(5 * 60 * 1000)
					.execute();
			String values = response.body();
			log.info("获取刷新access_token返回数据：" +values);
			JSONObject jsonObject = JSON.parseObject(values);
			String openId = jsonObject.getString("openid");
			String access_token = jsonObject.getString("access_token");
			String unionid = jsonObject.getString("unionid");
			String refresh_token_new = jsonObject.getString("refresh_token");
			openId = openId == null ? "" : openId;
			access_token = access_token == null ? "" : access_token;
			unionid = unionid == null ? "" : unionid;
			refresh_token_new = refresh_token_new == null ? "" : refresh_token_new;
			JSONObject jo = new JSONObject();
			jo.put("unionid",unionid);
			jo.put("openId",openId);
			jo.put("accessToken",access_token);
			jo.put("refreshToken",refresh_token_new);
			return jo;
		} catch (Exception e) {
			log.error("openId获取异常", e);
			JSONObject jo = new JSONObject();
			jo.put("msg","openId获取异常");
			jo.put("code","501");
			return jo;
		}
	}


	/**
	 * 描述：刷新access_token
	 */
	public  Map<String, String> getConfig(String url) {
		Map<String, String> sign = new HashMap<>();
		try {
			String titcket = getTitcket();
			sign = SignUtil.sign(titcket, url);
		} catch (Exception e) {
			e.printStackTrace();
		}
		sign.put("appId", gzhappid);
		return sign;
	}

//	/**
//	 * 描述：获取access_token
//	 */
//	public  JSONObject getAccessTokenByConfig() {
//		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=authorization_code"
//				+ "&appid=" + gzhappid + "&secret=" + openAppsecret;
//		try {
//			log.info("获取刷新access_token请求url：" + url);
//			HttpResponse response = HttpRequest.get(url)
//					.timeout(5 * 60 * 1000)
//					.execute();
//			String values = response.body();
//			log.info("获取刷新access_token返回数据：" +values);
//			JSONObject jsonObject = JSON.parseObject(values);
//			String access_token = jsonObject.getString("access_token");
//			access_token = access_token == null ? "" : access_token;
//			JSONObject jo = new JSONObject();
//			jo.put("accessToken",access_token);
//			return jo;
//		} catch (Exception e) {
//			log.error("openId获取异常", e);
//			JSONObject jo = new JSONObject();
//			jo.put("msg","openId获取异常");
//			jo.put("code","501");
//			return jo;
//		}
//	}

//	/**
//	 * 描述：获取ticket
//	 */
//	public  JSONObject getTicket() {
//		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=authorization_code"
//				+ "&appid=" + gzhappid + "&secret=" + openAppsecret;
////		https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
//		try {
//			log.info("获取刷新access_token请求url：" + url);
//			HttpResponse response = HttpRequest.get(url)
//					.timeout(5 * 60 * 1000)
//					.execute();
//			String values = response.body();
//			log.info("获取刷新access_token返回数据：" +values);
//			JSONObject jsonObject = JSON.parseObject(values);
//			String access_token = jsonObject.getString("access_token");
//			access_token = access_token == null ? "" : access_token;
//			JSONObject jo = new JSONObject();
//			jo.put("accessToken",access_token);
//			return jo;
//		} catch (Exception e) {
//			log.error("openId获取异常", e);
//			JSONObject jo = new JSONObject();
//			jo.put("msg","openId获取异常");
//			jo.put("code","501");
//			return jo;
//		}
//	}

	/**
	 * 描述：拉取用户信息
	 */
	public  JSONObject getUserInfoBySnsapi(String accessToken,String openid) {
		String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openid
				+ "&lang=zh_CN";
		try {
			log.info("获取用户信息请求url：" + url);
			HttpResponse response = HttpRequest.get(url)
					.timeout(5 * 60 * 1000)
					.execute();
			String values = response.body();
			log.info("获取用户信息返回数据：" +values);
			JSONObject jsonObject = JSON.parseObject(values);
			String openId = jsonObject.getString("openid");
			String unionid = jsonObject.getString("unionid");
			String nickname = jsonObject.getString("nickname");
			String sex = jsonObject.getString("sex");
			String province = jsonObject.getString("province");
			String city = jsonObject.getString("city");
			String country = jsonObject.getString("country");
			String headimgurl = jsonObject.getString("headimgurl");
			String privilege = jsonObject.getString("privilege");
			openId = openId == null ? "" : openId;
			unionid = unionid == null ? "" : unionid;
			nickname = nickname == null ? "" : nickname;
			sex = sex == null ? "" : sex;
			province = province == null ? "" : province;
			city = city == null ? "" : city;
			country = country == null ? "" : country;
			headimgurl = headimgurl == null ? "" : headimgurl;
			privilege = privilege == null ? "" : privilege;
			JSONObject jo = new JSONObject();
			jo.put("unionid",unionid);
			jo.put("openid",openId);
			jo.put("nickname",nickname);
			jo.put("sex",sex);
			jo.put("province",province);
			jo.put("city",city);
			jo.put("country",country);
			jo.put("headimgurl",headimgurl);
			jo.put("privilege",privilege);
			return jo;
		} catch (Exception e) {
			log.error("openId获取异常", e);
			JSONObject jo = new JSONObject();
			jo.put("msg","openId获取异常");
			jo.put("code","501");
			return jo;
		}
	}


	/**
	 *
	 * <br>
	 * 描述：获取openid
	 *
	 * @param code
	 * @return
	 * @date: 2019年8月10日 下午3:25:24
	 * @author Tjw
	 */
	public  String getPcOpenId(String code,HttpServletRequest request) {
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + openAppid + "&secret=" + openAppsecret
				+ "&code=" + code + "&grant_type=authorization_code";
		try {
			log.info("获取openid请求url：" + url);
			HttpResponse response = HttpRequest.get(url)
					.timeout(5 * 60 * 1000)
					.execute();
			String values = response.body();
			log.info("获取openid返回数据：" + values);
			JSONObject jsonObject = JSON.parseObject(values);
			String openId = jsonObject.getString("openid");
			String access_token = jsonObject.getString("access_token");
			String unionid = jsonObject.getString("unionid");
			openId = openId == null ? "" : openId;
			access_token = access_token == null ? "" : access_token;
			unionid = unionid == null ? "" : unionid;
			request.getSession().setAttribute("openId", openId);
			request.getSession().setAttribute("access_token", access_token);
			request.getSession().setAttribute("unionid", unionid);
			return openId;
		} catch (Exception e) {
			log.error("openId获取异常", e);
			return "openId获取异常";
		}
	}

	/**
	 *
	 * <br>
	 * 描述：获得code
	 *
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 * @date: 2019年8月10日 下午3:26:00
	 * @author Tjw
	 */
	public  String getCode(HttpServletRequest request) throws UnsupportedEncodingException {
		String authorize = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
		String url = authorize.replace("APPID", appid)
				.replace("REDIRECT_URI", URLEncoder.encode(request.getRequestURL().toString(), "utf-8"))
				.replace("SCOPE", "snsapi_userinfo");
		String queryString = request.getQueryString();
		if (StringUtils.isNotEmpty(queryString)) {
			url = url.replace("STATE", request.getQueryString());
		}
		log.info("获得code的url：" + url);
		return url;
	}

	/**
	 *
	 * <br>
	 * 描述：绑定微信时PC端商户获得微信开放号code
	 *
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 * @date: 2020年3月26日 下午3:26:00
	 * @author Tjw
	 */
	public  String getBindPcCode(HttpServletRequest request) throws UnsupportedEncodingException {
		String authorize = "https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
		String url = authorize.replace("APPID", openAppid)
				.replace("REDIRECT_URI", URLEncoder.encode(openUrl + "/merchant/index/bindWeixin", "utf-8"))
				.replace("SCOPE", "snsapi_login");
		String queryString = request.getQueryString();
		if (StringUtils.isNotEmpty(queryString)) {
			url = url.replace("STATE", request.getQueryString());
		}
		log.info("获得PC端code的url：" + url);
		return url;
	}

	/**
	 *
	 * <br>
	 * 描述：绑定微信时PC端服务商获得微信开放号code
	 *
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 * @date: 2020年3月26日 下午3:26:00
	 * @author Tjw
	 */
	public  String getBindPcLedgerCode(HttpServletRequest request) throws UnsupportedEncodingException {
		String authorize = "https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
		String url = authorize.replace("APPID", openAppid)
				.replace("REDIRECT_URI", URLEncoder.encode(openUrl + "/ledger/index/bindWeixin", "utf-8"))
				.replace("SCOPE", "snsapi_login");
		String queryString = request.getQueryString();
		if (StringUtils.isNotEmpty(queryString)) {
			url = url.replace("STATE", request.getQueryString());
		}
		log.info("获得PC端code的url：" + url);
		return url;
	}

	/**
	 *
	 * <br>
	 * 描述：微信登录时PC端获得微信开放号code
	 *
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 * @date: 2020年3月26日 下午3:26:00
	 * @author Tjw
	 */
	public  String getLoginPcCode(HttpServletRequest request) throws UnsupportedEncodingException {
		String authorize = "https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
		String url = authorize.replace("APPID", openAppid)
				.replace("REDIRECT_URI", URLEncoder.encode(openUrl + "/merchant/login/loginWeixin", "utf-8"))
				.replace("SCOPE", "snsapi_login");
		String queryString = request.getQueryString();
		if (StringUtils.isNotEmpty(queryString)) {
			url = url.replace("STATE", request.getQueryString());
		}
		log.info("获得PC端code的url：" + url);
		return url;
	}

	/**
	 * 获取access_token
	 * <br>描述：
	 * @return
	 * @date: 2020年4月10日 下午5:38:17
	 * @author tanjunwei
	 */
	public  String getAccessToken() {
		String access_token = getAccess_token(gzhappid, gzhappsecret);
		return access_token;
	}



	// xml事件推送
	public  String sendImageText(HttpServletResponse httpServletResponse, String toUserName, String fromUserName,
			List<String> Title, List<String> Description, List<String> PicUrl, List<String> Url) {
		StringBuffer content = new StringBuffer();
		content.append("<xml><ToUserName><![CDATA[");
		content.append(toUserName);
		content.append("]]></ToUserName><FromUserName><![CDATA[");
		content.append(fromUserName);
		content.append(
				"]]></FromUserName><CreateTime>12345678</CreateTime><MsgType><![CDATA[news]]></MsgType><ArticleCount>"
						+ Title.size() + "</ArticleCount><Articles>");
		for (int i = 0; i < Url.size(); i++) {
			content.append("<item>");

			content.append("<Title><![CDATA[");
			content.append(Title.get(i));
			content.append("]]></Title>");

			content.append("<Description><![CDATA[");
			content.append(Description.get(i));
			content.append("]]></Description>");

			content.append("<PicUrl><![CDATA[");
			content.append(PicUrl.get(i));
			content.append("]]></PicUrl>");

			content.append("<Url><![CDATA[");
			content.append(Url.get(i));
			content.append("]]></Url>");
			content.append("</item>");
		}
		content.append("</Articles>");
		content.append("</xml>");

		return content.toString();

	}

	public  String sendtextContent(String ToUserName, String FromUserName, String Content) {
		StringBuffer buffer = new StringBuffer();
		log.info(FromUserName + "   " + ToUserName);
		buffer.append("<xml><ToUserName><![CDATA[");
		buffer.append(ToUserName);
		buffer.append("]]></ToUserName><FromUserName><![CDATA[");
		buffer.append(FromUserName);
		buffer.append(
				"]]></FromUserName><CreateTime>12345678</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[");
		buffer.append(Content);
		buffer.append("]]></Content></xml>");

		return buffer.toString();
	}

	// 获取Access_token
	public synchronized String getAccess_token(String appid, String appsecret)  {
		String access_token = getSysConfig("access_token");
		if (StringUtils.isNotEmpty(access_token)){
			JSONObject jo = JSONObject.parseObject(access_token);
			jo.getString("expirettime");
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = null;
			try {
				date = format.parse(jo.getString("expirettime"));
			} catch (ParseException e) {
				throw new RuntimeException(e);
			}
			if(Long.valueOf(date.getTime()).compareTo(new Date().getTime()) >= 0) {
				return jo.getString("accessToken");
			}else{
				SysConfig config = new SysConfig();
				config.setConfigKey("access_token");
				List<SysConfig> sysConfigs = sysConfigService.selectConfigList(config);
				SysConfig sysConfig = new SysConfig();
				if (null != sysConfigs && sysConfigs.size() > 0) {
					sysConfig = sysConfigs.get(0);
				} else {
					sysConfig.setConfigKey("access_token");
					sysConfig.setConfigName("微信公众号的access_token");
					sysConfig.setRemark("微信公众号的access_token，存的是Json 对象，有三个字段：accessToken:accessToken，expirettime:过期时间戳，createtime：创建时间戳");
					sysConfig.setConfigType("Y");
				}
				String url = "https://api.weixin.qq.com/cgi-bin/stable_token";
				log.info("获取Access_token请求url：" + url);
				JSONObject sendObject = new JSONObject();
				sendObject.put("grant_type","client_credential");
				sendObject.put("appid",appid);
				sendObject.put("secret",appsecret);
				sendObject.put("force_refresh",false);
				String data = httpPost(url,sendObject);
				log.info("获取Access_token返回数据：" + data);
				if (StringUtils.isNotEmpty(data)) {
					JSONObject jsonObject = JSONObject.parseObject(data);
					Long createtime = System.currentTimeMillis();
					Long expirettime = System.currentTimeMillis() + (jsonObject.getInteger("expires_in") - 200) * 1000;
					JSONObject jo1 = new JSONObject();
					jo1.put("accessToken",jsonObject.getString("access_token"));
					jo1.put("expirettime",new Date(expirettime));
					jo1.put("createtime",new Date(createtime));
					sysConfig.setConfigValue(jo1.toJSONString());
					sysConfigService.updateConfig(sysConfig);
					return jsonObject.getString("access_token");
				}
			}
		} else {
			String url = "https://api.weixin.qq.com/cgi-bin/stable_token";
			log.info("获取Access_token请求url：" + url);
			JSONObject sendObject = new JSONObject();
			sendObject.put("grant_type","client_credential");
			sendObject.put("appid",appid);
			sendObject.put("secret",appsecret);
			sendObject.put("force_refresh",false);
			String data = httpPost(url,sendObject);
			log.info("获取Access_token返回数据：" + data);
			if (StringUtils.isNotEmpty(data)) {
				JSONObject jsonObject = JSONObject.parseObject(data);
				Long createtime = System.currentTimeMillis();
				Long expirettime = System.currentTimeMillis() + (jsonObject.getInteger("expires_in") - 200) * 1000;
				JSONObject jo = new JSONObject();
				jo.put("accessToken",jsonObject.getString("access_token"));
				jo.put("expirettime",new Date(expirettime));
				jo.put("createtime",new Date(createtime));
				SysConfig sysConfig = new SysConfig();
				sysConfig.setConfigName("微信公众号的access_token");
				sysConfig.setRemark("微信公众号的access_token，存的是Json 对象，有三个字段：accessToken:accessToken，expirettime:过期时间戳，createtime：创建时间戳");
				sysConfig.setConfigType("Y");
				sysConfig.setConfigKey("access_token");
				sysConfig.setConfigValue(jo.toJSONString());
				sysConfigService.insertConfig(sysConfig);
				return jsonObject.getString("access_token");
			}
		}
		return null;
	}

	public void createBwwxMenu(String menu) {
		// 此处改为自己想要的结构体，替换即可
		String access_token = getAccess_token(null, null);

		String action = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + access_token;
		try {
			URL url = new URL(action);
			HttpURLConnection http = (HttpURLConnection) url.openConnection();

			http.setRequestMethod("POST");
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒

			http.connect();
			OutputStream os = http.getOutputStream();
			os.write(menu.getBytes("UTF-8"));// 传入参数
			os.flush();
			os.close();

			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String message = new String(jsonBytes, "UTF-8");
			log.info("createBwwxMenu返回数据：" + message);
		} catch (Exception e) {
			log.error("createBwwxMenu出现异常", e);
		}

	}

	public  String getBasicInfo(String openId) throws Exception {
		String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + getAccess_token(appid, appsecret)
				+ "&openid=" + openId + "&lang=zh_CN";
		return HttpRequest.get(url).execute().body();
	}

	public  void createMean(String APPID, String APPSECRET) {
		String ssms = "http://www.biftsce.com/weixinBf/weixin/allZixun?title=%E6%97%B6%E5%B0%9A%E4%B9%B0%E6%89%8B";
		String end = "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
		String menu = "";

		String zymsUrl = "https://www.fengyoucai.com/weixin/web/newIndex";

		String zyms = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + APPID + "&redirect_uri="
				+ URLEncoder.encode(zymsUrl) + end;
		menu = ("{\"button\":[{\"name\":\"个人中心\",\"type\":\"view\",\"url\":\"" + zyms + "\"}]}");

		String access_token = getAccess_token(APPID, APPSECRET);

		String action = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + access_token;
		try {
			URL url = new URL(action);
			HttpURLConnection http = (HttpURLConnection) url.openConnection();

			http.setRequestMethod("POST");
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒

			http.connect();
			OutputStream os = http.getOutputStream();
			os.write(menu.getBytes("UTF-8"));// 传入参数
			os.flush();
			os.close();

			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String message = new String(jsonBytes, "UTF-8");
			log.info("createMean返回数据：" + message);
		} catch (Exception e) {
			log.error("createMean出现异常", e);
		}
	}

	public  void deleteMenu(String string, String string2) {
		String menu = "{\"button\": [{\"name\": \"照片墙\",\"sub_button\": [{\"type\": \"click\",\"name\": \"我要参与\",\"key\": \"IAMJOIN\"},{\"type\": \"click\",\"name\": \"查看照片墙\",\"key\": \"VIEWPHTOT\"}]},{\"name\": \"有奖互动\", \"sub_button\": [{\"type\": \"click\",\"name\": \"比分竞猜\",\"key\": \"bifenjincai\"},{\"type\": \"click\",\"name\": \"首发预测\", \"key\": \"shoufayuce\"}]},{\"name\": \"球队\",\"sub_button\": [{\"type\": \"click\",\"name\": \"俱乐部\",\"key\": \"julebu\"},{\"type\": \"click\",\"name\": \"球队成员\",\"key\": \"qiuduichengyuan\"},{\"type\": \"click\",\"name\": \"积分榜\",\"key\": \"jifenbang\"},{\"type\": \"click\",\"name\": \"射手榜\",\"key\": \"sheshoubang\"},{\"type\": \"click\",\"name\": \"赛程\",\"key\": \"saicheng\"}]}]}";

		// 此处改为自己想要的结构体，替换即可
		String access_token = getAccess_token(string, string2);

		String action = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" + access_token;
		try {
			URL url = new URL(action);
			HttpURLConnection http = (HttpURLConnection) url.openConnection();

			http.setRequestMethod("POST");
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒

			http.connect();
			OutputStream os = http.getOutputStream();
			os.write(menu.getBytes("UTF-8"));// 传入参数
			os.flush();
			os.close();

			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String message = new String(jsonBytes, "UTF-8");
			log.info("deleteMenu返回数据：" + message);
		} catch (Exception e) {
			log.error("deleteMenu出现异常", e);
		}
	}



	// 获取wx名称
	public  String getWxName(String url) {
		String nickname = "";
		try {
			URL urlGet = new URL(url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();

			http.setRequestMethod("GET"); // 必须是get方式请求
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒

			http.connect();

			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			nickname = new String(jsonBytes, "UTF-8");

		} catch (Exception e) {
			log.error("获取微信名称出现异常", e);
		}

		return nickname;
	}

	/**
	 * 获取用户分组
	 */
	public  int createGroup(String token, String groupName) {
		String url = "https://api.weixin.qq.com/cgi-bin/groups/create?access_token=" + token;

		int sb = 0;
		try {
			URL urlGet = new URL(url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();

			http.setRequestMethod("GET"); // 必须是get方式请求
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒

			http.connect();

			OutputStream outputStream = http.getOutputStream();

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("name", groupName);

			JSONObject jsonObject2 = new JSONObject();
			jsonObject2.put("group", jsonObject);

			String json = jsonObject2.toJSONString();

			outputStream.write(json.getBytes("UTF-8"));

			outputStream.flush();
			outputStream.close();

			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String message = new String(jsonBytes, "UTF-8");

			JSONObject jsObject = JSONObject.parseObject(message);

			log.info("获取用户分组返回数据：" + jsObject);

			jsObject = jsObject.getJSONObject("group");

			sb = jsObject.getInteger("id");

		} catch (Exception e) {
			log.error("获取用户分组出现异常", e);
		}
		return sb;
	}

	public  int updateGroup(String token, String groupName, int id) {
		String url = "https://api.weixin.qq.com/cgi-bin/groups/update?access_token=" + token;

		int sb = 0;
		try {
			URL urlGet = new URL(url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();

			http.setRequestMethod("POST"); // 必须是get方式请求
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒

			http.connect();

			OutputStream outputStream = http.getOutputStream();

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("name", groupName);
			jsonObject.put("id", id);
			JSONObject jsonObject2 = new JSONObject();
			jsonObject2.put("group", jsonObject);
			String json = jsonObject.toJSONString();

			outputStream.write(json.getBytes("UTF-8"));

			outputStream.flush();
			outputStream.close();

			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String message = new String(jsonBytes, "UTF-8");

			JSONObject jsObject = JSONObject.parseObject(message);

			log.info("更新分组返回数据：" + jsObject);

			sb = jsObject.getInteger("errcode");

		} catch (Exception e) {
			log.error("更新分组出现异常", e);
		}
		return sb;
	}

	public  int updateUsersGroup(String token, String openid, int to_groupid) {
		String url = "https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=" + token;

		int sb = 0;
		try {
			URL urlGet = new URL(url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();

			http.setRequestMethod("POST"); // 必须是get方式请求
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒

			http.connect();

			OutputStream outputStream = http.getOutputStream();

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("openid", openid);
			jsonObject.put("to_groupid", to_groupid);
			String json = jsonObject.toJSONString();

			outputStream.write(json.getBytes("UTF-8"));

			outputStream.flush();
			outputStream.close();

			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String message = new String(jsonBytes, "UTF-8");

			JSONObject jsObject = JSONObject.parseObject(message);

			log.info("更新用户分组返回数据：" + jsObject);

			sb = jsObject.getInteger("errcode");

		} catch (Exception e) {
			log.error("更新用户分组出现异常", e);
		}
		return sb;
	}

	public  String crreateTickets(String token) {
		String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + token;

		String sb = "";
		try {
			URL urlGet = new URL(url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();

			http.setRequestMethod("GET"); // 必须是get方式请求
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒

			http.connect();

			OutputStream outputStream = http.getOutputStream();

			outputStream.write(("{\"action_name\": \"QR_LIMIT_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": "
					+ new Random().nextInt(100000) + "}}}").getBytes("UTF-8"));

			outputStream.flush();
			outputStream.close();

			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String message = new String(jsonBytes, "UTF-8");
			JSONObject jsObject = JSONObject.parseObject(message);
			log.info("crreateTickets返回数据：" + jsObject);
			sb = jsObject.getString("ticket");

		} catch (Exception e) {
			log.error("crreateTickets出现异常", e);
		}
		return sb;

	}

	public  Date getDate(long dateString) {
		try {
			return format.parse(format.format(new Date(dateString * 1000L)));
		} catch (ParseException e) {
			return new Date();
		}
	}

	//
	public  String getUserInfo(String openid) {
		String access_token = getAccess_token(appid, appsecret);
		String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + access_token + "&openid=" + openid
				+ "&lang=zh_CN";
		String data = getWxName(url);
		log.info("获取用户信息返回数据：" + data);
		return data;
	}

	public  String accountAdd(String kf_account, String nickname, String password) {
		String token = getAccess_token("wx36a52e51c224fd21", "6b9b56dd52bb4885f62c9ac397fb8cfd");
		String url = "https://api.weixin.qq.com/customservice/kfaccount/add?access_token=" + token;

		String sb = "";
		try {
			URL urlGet = new URL(url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();

			http.setRequestMethod("POST"); // 必须是get方式请求
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒

			http.connect();

			OutputStream outputStream = http.getOutputStream();

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("kf_account", kf_account);
			jsonObject.put("nickname", nickname);
			jsonObject.put("password", password);
			String value = jsonObject.toJSONString();

			log.info("accountAdd发送数据：" + value);
			outputStream.write((value).getBytes("UTF-8"));

			outputStream.flush();
			outputStream.close();

			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String message = new String(jsonBytes, "UTF-8");

			JSONObject jsObject = JSONObject.parseObject (message);

			log.info("accountAdd返回数据：" + jsObject);

			sb = jsObject.getString("ticket");
		} catch (Exception e) {
			log.error("accountAdd出现异常", e);
		}
		return sb;

	}

	public  String getTitcket() throws Exception {
		String accessToken = getAccess_token(gzhappid, gzhappsecret);
		String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi";
		String returnValue = httpGet(url,null);
		JSONObject jsonObject = JSONObject.parseObject(returnValue);
		String ticket = jsonObject.getString("ticket");
		log.info("getTitcket返回数据：" + jsonObject);
		return ticket;
	}

	// 获取带参数二维码
	public  String getQrcode() {
		String accessToken = getAccess_token(appid, appsecret);
		return crreateTickets(accessToken);
	}

	public  String jmsq() throws Exception {
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid
				+ "&redirect_uri=http://dya.s1.natapp.cc&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
		String returnValue = httpGet(url,null);
		JSONObject jsonObject = JSONObject.parseObject(returnValue);
		log.info("jmsq返回数据：" + jsonObject);
		return "jsonObject";
	}

	public  String getRandomStr(int length) {
		String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();

	}

	public  String getSysConfig(String key){
		String value = sysConfigService.selectConfigByKey(key);
		return value;
	}

	public  String httpPost(String url,JSONObject params){
		Map<String, String > heads = new HashMap<>();
		heads.put("Content-Type", "application/json;charset=UTF-8");
		HttpResponse response = HttpRequest.post(url)
				.headerMap(heads, false)
				.body(String.valueOf(params))
				.timeout(5 * 60 * 1000)
				.execute();
		return response.body();
	}

	public  String httpGet(String url,JSONObject params){
		Map<String, String > heads = new HashMap<>();
		heads.put("Content-Type", "application/json;charset=UTF-8");
		HttpResponse response = HttpRequest.get(url)
				.headerMap(heads, false)
				.body(String.valueOf(params))
				.timeout(5 * 60 * 1000)
				.execute();
		return response.body();
	}



	/**
	 * <br>
	 * 描述：微信公众号发送模板消息 <br>
	 * 接口文档：https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277
	 *
	 * @param openId openId，微信登录返回的openId
	 * @return
	 * @throws Exception
	 * @date: 2019年9月5日 下午2:45:19
	 * @author Tjw
	 */
	public  boolean sendMessage(JSONObject jsonObject, String openId, String templateId, String path)
			 {
		if (!StringUtils.isEmpty(openId)) {
			String access_token = getAccessToken();
			String url = " https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token;
			JSONObject params = new JSONObject();
			params.put("touser", openId);
			params.put("template_id", templateId);
			params.put("url",url);
			params.put("data", jsonObject);
			JSONObject miniprogram = new JSONObject();
			miniprogram.put("appid",appid);
			miniprogram.put("pagepath",path);
			params.put("miniprogram",miniprogram);
			log.info("微信公众号发送模板消息请求参数：" + params.toString());
			String data = httpPost(url, params);
			log.info("微信公众号发送模板消息返回数据：" + data);
			JSONObject dataMap = JSONObject.parseObject(data);
			if (dataMap != null && dataMap.get("errcode") != null
					&& Integer.parseInt(dataMap.get("errcode").toString()) == 0) {
				return true;
			}
		}
		return false;
	}


	public static void main(String[] args) {

		//System.out.println("token:"+getAccessToken());
	}

}
