package com.zhiwei.weixin;

import net.sf.json.JSONObject;

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

import com.zhiwei.weixin.accesstoken.CreatAccessToken;
import com.zhiwei.weixin.http.HttpRequest;
import com.zhiwei.weixin.pojo.Template;
import com.zhiweidata.bjfzxWebapp.util.WechatCodeUtil;

/** 
 * @Package com.zhiwei.weixin.industry
 * @ClassName: CreateIndustry
 * @Description: TODO(模版消息管理)
 * @author 志伟
 * @date 2015-3-27 下午7:10:39
 */
public class Templates {
	private static Logger logger = LoggerFactory.getLogger(Templates.class);
	
	//获取模版消息template_id
	private static String add_template_url = "https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=ACCESS_TOKEN";
	
	//发送模版消息
    private static String send_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
    
    // 调用接口获取access_token  
    private static String accessToken = null;
	public Templates() 
	{
//		accessToken = new CreatAccessToken().getAccessToken();  
		accessToken = WechatCodeUtil.getToken();//从微信中间件获取token
	}
	
	/**
	 * 
	 * @Title: gettemplateId 
	 * @Description: TODO(根据消息模版的短id获取长id) 
	 * @param @param template_id_short
	 * @param @return 设定文件 
	 * @return String 返回类型
	 */
	public String gettemplateId(String template_id_short)
	{
		String template_id = null;
		String url = add_template_url.replace("ACCESS_TOKEN", accessToken);
		JSONObject json = new JSONObject();
		json.put("template_id_short", template_id_short);
		try {
			JSONObject jsonObject = HttpRequest.httpRequest(url, "POST", json.toString());
			System.out.println(jsonObject);
			if("ok".equals(jsonObject.getString("errmsg")))
			{
				template_id = jsonObject.getString("template_id");
			}else
			{
				logger.info("消息模版已到上限");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("从接口访问数据出错",e.getMessage());
			return template_id;
		}
		
		return template_id;
	}
	
	 /**
	  * 
	  * @Title: okNotice 
	  * @Description: TODO(发送通过模版通知) 
	  * @param @param openid
	  * @param @param template_id
	  * @param @return 设定文件 
	  * @return int 返回类型
	  */
	public int send(Template template)
	{
		int msgid = 0;
		String url = send_url.replace("ACCESS_TOKEN", accessToken);
		try {
			String templateJson = JSONObject.fromObject(template).toString();
			System.out.println(templateJson);
			JSONObject jsonObject = HttpRequest.httpRequest(url, "POST", templateJson);
			if(null != jsonObject)
			{
				if("ok".equals(jsonObject.getString("errmsg")))
				{
					msgid = jsonObject.getInt("msgid");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("发送创建模版消息请求时出现错误", e.getMessage());
			msgid = 0;
		}
		return msgid;
	}
	
	
	
	
	public static void main(String[] args)throws Exception
	{
		Templates templates = new Templates();
		Template template = new Template();
		
		
		
		
		
		templates.send(template);
	}

}
