package com.zhiwei.finance;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zhiwei.util.JsonToObject;
import com.zw.entity.NewsResult;
import com.zw.entity.UserInfo;

import net.sf.json.JSONObject;
import weixin.popular.api.MessageAPI;
import weixin.popular.api.TokenAPI;
import weixin.popular.api.UserAPI;
import weixin.popular.bean.message.templatemessage.TemplateMessage;
import weixin.popular.bean.message.templatemessage.TemplateMessageItem;
import weixin.popular.bean.message.templatemessage.TemplateMessageResult;
import weixin.popular.bean.token.Token;
import weixin.popular.bean.user.Group;

/**
 * 微信推送
 * 
 * @author admin
 *
 */
public class WeixinSend {
	private static final Logger log = LoggerFactory.getLogger(WeixinSend.class);
	private static Token token;

	public WeixinSend(String appId, String appSecret) {
		token = TokenAPI.token(appId, appSecret);
	}

	public synchronized void sendUseTemp(String temp_id, NewsResult news, List<String> openids) {
		String access_token = JsonToObject.getToken();
		for (String openid : openids) {
			TemplateMessage templateMessage = new TemplateMessage();
			templateMessage.setTemplate_id(temp_id);
			templateMessage.setUrl(news.getUrl());
			LinkedHashMap<String, TemplateMessageItem> datamap = new LinkedHashMap<>();
			datamap.put("first", new TemplateMessageItem(
					news.getTime() + "|" + news.getSource() + "|" + "关联：" + news.getShortName(), "RED"));
			datamap.put("keyword1", new TemplateMessageItem(" 标题：" + news.getTitle(), null));
			datamap.put("keyword2", new TemplateMessageItem(news.getContent(), null));
			templateMessage.setTouser(openid);
			templateMessage.setData(datamap);
			TemplateMessageResult result = MessageAPI.messageTemplateSend(access_token, templateMessage);
			if ((result.getErrmsg() == null) || (!"ok".equals(result.getErrmsg()))) {
				log.debug("发送触发消息失败," + result.getErrmsg());
			}
			try {
				Thread.sleep(50L);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public synchronized void sendUseTemp(String temp_id, NewsResult news, String openid) {
		String access_token = JsonToObject.getToken();
		TemplateMessage templateMessage = new TemplateMessage();
		templateMessage.setTemplate_id(temp_id);
		templateMessage.setUrl(news.getUrl());
		LinkedHashMap<String, TemplateMessageItem> datamap = new LinkedHashMap<>();
		datamap.put("first", new TemplateMessageItem("", null));
		datamap.put("keyword1", new TemplateMessageItem(" 标题：" + news.getTitle(), null));
		datamap.put("keyword2", new TemplateMessageItem(
				news.getContent() + "\n" + news.getTime() + "|" + news.getSource() + "|" + "关联：" + news.getShortName(),
				null));
		templateMessage.setTouser(openid);
		templateMessage.setData(datamap);
		TemplateMessageResult result = MessageAPI.messageTemplateSend(access_token, templateMessage);
		if ((result.getErrmsg() == null) || (!"ok".equals(result.getErrmsg()))) {
			log.debug("发送触发消息失败," + result.getErrmsg());
		}
		try {
			Thread.sleep(50L);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public List<String> getOpenid(String access_token, String idNum) {
		List<String> list = new ArrayList<>();
		String[] openid = null;
		try {
			String result = "";
			BufferedReader in = null;
			URL url = new URL(
					"https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + access_token + "&next_openid");

			URLConnection connection = url.openConnection();

			connection.connect();

			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result = result + line;
			}
			JSONObject jsonObject = JSONObject.fromObject(result);
			String data = jsonObject.getString("data");
			log.debug(result);
			String[] info = data.split(":");
			openid = info[1].replace("[", "").replace("]", "").replace("}", "").split(",");
			String[] arrayOfString1 = openid;
			int i = arrayOfString1.length;
			int j = 0;
			if (j < i) {
				String o = arrayOfString1[j];
				o = o.replace("\"", "");
				Group gorp = UserAPI.groupsGetid(access_token, o.replace("\"", ""));
				if (idNum.equals(String.valueOf(gorp.getGroupid()))) {
					list.add(o);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	public List<String> getOpenid(String access_token) {
		List<String> list = new ArrayList<>();
		String[] openid = null;
		try {
			String result = "";
			BufferedReader in = null;
			URL url = new URL(
					"https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + access_token + "&next_openid");

			URLConnection connection = url.openConnection();
			connection.connect();
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result = result + line;
			}
			JSONObject jsonObject = JSONObject.fromObject(result);
			String data = jsonObject.getString("data");
			log.debug(result);
			String[] info = data.split(":");
			openid = info[1].replace("[", "").replace("]", "").replace("}", "").split(",");
			for (String o : openid) {
				o = o.replace("\"", "");
				list.add(o);
			}
		} catch (Exception e) {
			log.info("openid获取失败 ");
		}
		return list;
	}

	public UserInfo getUserMessage(String access_token, String openid) {
		UserInfo user = new UserInfo();
		try {
			String result = "";
			BufferedReader in = null;
			URL url = new URL("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + access_token + "&openid="
					+ openid + "&lang=zh_CN");
			URLConnection connection = url.openConnection();
			connection.connect();
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result = result + line;
			}
			JSONObject jsonObject = JSONObject.fromObject(result);
			log.debug(jsonObject.toString());
			System.out.println(jsonObject);
			try {
				user.setSubscribe(jsonObject.getString("subscribe"));
				user.setOpenid(jsonObject.getString("openid"));
				user.setNickname(jsonObject.getString("nickname"));
				user.setSex(jsonObject.getString("sex"));
				user.setLanguage(jsonObject.getString("language"));
				user.setCity(jsonObject.getString("city"));
				user.setProvince(jsonObject.getString("province"));
				user.setCountry(jsonObject.getString("country"));
				user.setHeadimgurl(jsonObject.getString("headimgurl"));
				user.setSubscribe_time(jsonObject.getString("subscribe_time"));
				user.setRemark(jsonObject.getString("remark"));
				user.setGroupid(jsonObject.getString("groupid"));
				user.setTagid_list(jsonObject.getString("tagid_list"));
			} catch (Exception e) {
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return user;
	}

	public static void main(String[] args) throws ParseException {
		WeixinSend w = new WeixinSend("wx92c35fbf3a418be8", "474e30858801615f0edf61215ea24305");
		w.sendUseTemp("2jWpk0N1CC-fQQdJnXJQuc2WOh7yh_Ozn0-T0K9mExQ", new NewsResult(), new ArrayList<>());
	}
}
