package com.iamberry.wechat.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.iamberry.wechat.core.entity.wx.Article;
import com.iamberry.wechat.core.entity.wx.ImageTextInfo;
import com.iamberry.wechat.core.entity.wx.ImageTextMore;
import com.iamberry.wechat.core.entity.wx.NewsMessage;
import com.iamberry.wechat.tools.NameUtils;

public class MessageManager {
	/**
	 * 获取图文信息
	 * @param requestMap
	 * @return
	 * @throws Exception
	 */
	public static String getImageTextInfo(Map<String, String> requestMap,ImageTextInfo imageTextInfo,List<ImageTextMore> imagetextMoreList)throws Exception{
		String picUrl = imageTextInfo.getImageUrl();
		String clickUrl = null;
		List<Article> articleList = new ArrayList<Article>();
		Article article = new Article();
		article.setTitle(imageTextInfo.getTitle()); //图文消息标题 
		article.setDescription(imageTextInfo.getDigest());//图文消息描述
		article.setPicUrl(picUrl);//图片URL
		article.setUrl(clickUrl);//点击图文消息跳转链接
	
		if(imageTextInfo.getClickOutUrl() != null && !"".equals(imageTextInfo.getClickOutUrl())){
			article.setUrl(imageTextInfo.getClickOutUrl()+ "?openid=" + requestMap.get("FromUserName")); //如果外链不为空则为外链
		}
		articleList.add(article);
		
		if (imagetextMoreList != null) {
			for(ImageTextMore textMore : imagetextMoreList){
				article = new Article();
				article.setTitle(textMore.getTitle()); //图文消息标题 
				 
				picUrl = textMore.getImageUrl();
				clickUrl = NameUtils.getConfig("MORE_CLICK_URL") + textMore.getMoreImageTextNo();
				article.setUrl(clickUrl);//点击图文消息跳转链接
				article.setPicUrl(picUrl);//图片链接
				article.setDescription(textMore.getDigest());//图文消息描述
				if(textMore.getClickOutUrl() != null && !"".equals(textMore.getClickOutUrl())){
					article.setUrl(textMore.getClickOutUrl() + "?openid=" + requestMap.get("FromUserName")); //如果外链不为空则为外链
				}
				articleList.add(article);			
			}
		}
		
		return getNewsMessage(requestMap, articleList);
	}
	
	/**
	 * 组装图文消息
	 * @param requestMap
	 * @param articles
	 * @return
	 */
	public static String getNewsMessage(Map<String, String> requestMap, List<Article> articles) {
		NewsMessage newsMessage = new NewsMessage();
		newsMessage.setFuncFlag(1);
		newsMessage.setArticles(articles);
		newsMessage.setArticleCount(articles.size());
		newsMessage.setToUserName(requestMap.get("FromUserName"));
		newsMessage.setFromUserName(requestMap.get("ToUserName"));
		newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
		newsMessage.setCreateTime(Long.parseLong(requestMap.get("CreateTime")));
		return MessageUtil.newsMessageToXml(newsMessage);
	}
}
