package com.jw.app.portlet.action;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;

import com.gaowj.business.action.BasicAction;
import com.gaowj.business.comp.BusinessManager;
import com.gaowj.business.exception.BusinessException;
import com.gaowj.business.util.Page;
import com.gaowj.business.util.RequestUtils;
import com.gaowj.business.util.SessionUtil;
import com.gaowj.service.client.remote.util.AuthenticateUtil;
import com.gaowj.service.client.utils.UrlDataUtil;
import com.jw.app.business.PortletBusiness;
import com.jw.app.business.UnitBusiness;
import com.jw.app.business.utils.QueryParamUtil;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

public class dataAction extends BasicAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7897314852467856687L;

	private JSONObject jsonObject = new JSONObject();
	private int rows = 20;// 每页显示的记录数
	private int page = 1;// 当前第几页

	public JSONObject getJsonObject() {
		return jsonObject;
	}

	public void setJsonObject(JSONObject jsonObject) {
		this.jsonObject = jsonObject;
	}

	public int getRows() {
		rows = getPageSize();
		return rows;
	}

	public void setRows(int rows) {
		setPageSize(rows);
		this.rows = getPageSize();
	}

	public int getPage() {
		page = getPageNo();
		return page;
	}

	public void setPage(int page) {
		setPageNo(page);
		this.page = getPageNo();
	}
	
	public String listBaseApps() throws BusinessException{
		PortletBusiness business = BusinessManager
				.getBusiness(PortletBusiness.class);
		List<Map<String, Object>> listApps=business.listBaseApps(new HashMap<String, Object>());
		
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("rowSet", listApps);
		data.put("pageNo", pageNo);
		data.put("pageSize", pageSize);
		data.put("pageCount", pageCount);
		data.put("rows", listApps);
		data.put("total", listApps.size());
		jsonObject = new JSONObject();
		jsonObject.putAll(data);
		return "json";
	}

	public String listPTemplate() throws BusinessException {
		PortletBusiness business = BusinessManager
				.getBusiness(PortletBusiness.class);
		Map<String, Object> query = RequestUtils.getUpdateFieldMap(request,
				RequestUtils.UPDATEDATAFIELDPREFIX);

		try {
			query = QueryParamUtil.StringToDate(query);
			Page<Map<String, Object>> pageRows = business
					.list_portlet_template(pageNo, pageSize, query);
			for (Map<String, Object> rm : pageRows.getItems()) {
				rm.remove("TAKE_CONTENT");
				rm.remove("RSS_CONTENT");
			}
			setPageCount((pageRows.getCount() - 1) / pageSize + 1);
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("rowSet", QueryParamUtil.DateToString(pageRows
							.getItems()));
			data.put("pageNo", pageNo);
			data.put("pageSize", pageSize);
			data.put("pageCount", pageCount);
			data.put("rows", data.get("rowSet"));
			data.put("total", pageRows.getCount());
			jsonObject = new JSONObject();
			jsonObject.putAll(data);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "json";
	}
	
	public String listAllPTemplate() throws BusinessException {
		PortletBusiness business = BusinessManager
				.getBusiness(PortletBusiness.class);
		Map<String, Object> query = RequestUtils.getUpdateFieldMap(request,
				RequestUtils.UPDATEDATAFIELDPREFIX);

		try {
			query = QueryParamUtil.StringToDate(query);
			List<Map<String, Object>> listData = business
					.list_portlet_template(query);
			for (Map<String, Object> rm : listData) {
				if(rm.get("P_TYPE")==null||!rm.get("P_TYPE").equals("3"))
				{
					rm.remove("RSS_CONTENT");
					rm.remove("TAKE_CONTENT");
				}
			}
			int listDataCount = business.listCount_portlet_template(query);
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("rowSet", QueryParamUtil.DateToString(listData));
			data.put("pageNo", 1);
			data.put("pageSize", listDataCount);
			data.put("pageCount", listDataCount);
			data.put("rows", data.get("rowSet"));
			data.put("total", listDataCount);
			jsonObject = new JSONObject();
			jsonObject.putAll(data);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "json";
	}
	
	/**
	 * 获取用户的资源列表
	 * @return
	 * @throws BusinessException
	 */
	public String listAllPTemplateByUser() throws BusinessException {
		PortletBusiness business = BusinessManager
				.getBusiness(PortletBusiness.class);
		Map<String, Object> query = RequestUtils.getUpdateFieldMap(request,
				RequestUtils.UPDATEDATAFIELDPREFIX);

		try {
			query = QueryParamUtil.StringToDate(query);
			List<Map<String, Object>> listData = business
					.list_portlet_template_by_user(query);
			for (Map<String, Object> rm : listData) {
				if(rm.get("P_TYPE")==null||!rm.get("P_TYPE").equals("3"))
				{
					rm.remove("RSS_CONTENT");
					rm.remove("TAKE_CONTENT");
				}
			}
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("rowSet", QueryParamUtil.DateToString(listData));
			data.put("pageNo", 1);
			data.put("pageSize", listData.size());
			data.put("pageCount", listData.size());
			data.put("rows", data.get("rowSet"));
			data.put("total", listData.size());
			jsonObject = new JSONObject();
			jsonObject.putAll(data);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "json";
	}
	
	/**
	 * 显示发布类型树
	 * @return
	 * @throws BusinessException
	 */
	public String listPTemplateTree() throws BusinessException {
		PortletBusiness business = BusinessManager
				.getBusiness(PortletBusiness.class);
		Map<String, Object> query = RequestUtils.getUpdateFieldMap(request,
				RequestUtils.UPDATEDATAFIELDPREFIX);

		try {
			query = QueryParamUtil.StringToDate(query);
			List<Map<String, Object>> listData = business
					.list_portlet_template(query);
			for (Map<String, Object> rm : listData) {
				if(rm.get("P_TYPE")==null||!rm.get("P_TYPE").equals("3"))
				{
					rm.remove("RSS_CONTENT");
					rm.remove("TAKE_CONTENT");
				}
				rm.put("PARENT_ID", "1");
			}
			Map<String, Object>map=new HashMap<String, Object>();
			map.put("PORTLET_ID", "1");
			map.put("NAME", "发布内容");
			map.put("PARENT_ID", "0");
			listData.add(map);
			int listDataCount = business.listCount_portlet_template(query);
			listDataCount++;
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("rowSet", QueryParamUtil.DateToString(listData));
			data.put("pageNo", 1);
			data.put("pageSize", listDataCount);
			data.put("pageCount", listDataCount);
			data.put("rows", data.get("rowSet"));
			data.put("total", listDataCount);
			jsonObject = new JSONObject();
			jsonObject.putAll(data);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "json";
	}

	public String listAllPTemplate_takeContent() throws BusinessException {
		PortletBusiness business = BusinessManager
				.getBusiness(PortletBusiness.class);
		Map<String, Object> query = RequestUtils.getUpdateFieldMap(request,
				RequestUtils.UPDATEDATAFIELDPREFIX);

		try {
			query = QueryParamUtil.StringToDate(query);
			List<Map<String, Object>> listData = business
					.list_portlet_template(query);
			int listDataCount = business.listCount_portlet_template(query);
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("rowSet", QueryParamUtil.DateToString(listData));
			data.put("pageNo", 1);
			data.put("pageSize", listDataCount);
			data.put("pageCount", listDataCount);
			data.put("rows", data.get("rowSet"));
			data.put("total", listDataCount);
			jsonObject = new JSONObject();
			jsonObject.putAll(data);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "json";
	}

	/*
	 * 
	 * 获取样式列表
	 */
	public String listStyle() throws BusinessException {
		//样式
		String p_style = AuthenticateUtil.getEndpoint("p_style");
		//名称
		String p_style_name = AuthenticateUtil.getEndpoint("p_style_name");
//		try {
//			//p_style_name=new String(p_style_name.getBytes(), "US-ASCII");
//			p_style_name = new String(p_style_name.getBytes("ISO8859-1"), "utf-8");
//		} catch (UnsupportedEncodingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		String []strleName=p_style_name.split("\\,");
		//返回的列表信息
		List<Map<String , String>>listData=new ArrayList<Map<String,String>>();
		//返回的列表html信息
		String stringData="";
		int i=0;
		for (String style : p_style.split("\\,")) {
			Map<String , String> map=new HashMap<String, String>();
			map.put(strleName[i], style);
			stringData=stringData+"<div class='popover-item'><span class='value' /><a href='javascript:void(0)' onClick=\"changeStyle('"+style+"')\">"+strleName[i]+"</a></span><div class='clearfix'></div></div>";
			listData.add(map);
			i++;
		}
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("stringData", stringData);
		data.put("listData", listData);
		jsonObject = new JSONObject();
		jsonObject.putAll(data);
		return "json";
	}

	public String listAllPMyTemplate() throws BusinessException {
		PortletBusiness business = BusinessManager
				.getBusiness(PortletBusiness.class);
		Map<String, Object> query = RequestUtils.getUpdateFieldMap(request,
				RequestUtils.UPDATEDATAFIELDPREFIX);
		List<Map<String, Object>> listDataAll = new ArrayList<Map<String, Object>>();

		Map<String, Object> data = new HashMap<String, Object>();
		try {
			query = QueryParamUtil.StringToDate(query);
			if (SessionUtil.getEmdepart() != null) {
				String mQuery[] = SessionUtil.getEmdepart().split(",");
				for (String q : mQuery) {
					Map<String, Object> l = new HashMap<String, Object>();
					l.put("G_ID", q);
					l.put("COLUMN_ID", query.get("COLUMN_ID"));
					List<Map<String, Object>> listData = business
							.list_portlet_mytemplate_notall(l);
					for (Map<String, Object> rm : listData) {
						rm.remove("RSS_CONTENT");
						rm.remove("TAKE_CONTENT");
					}
					listDataAll.addAll(listData);
				}

				Map<String, Object> l_all = new HashMap<String, Object>();
				l_all.put("COLUMN_ID", query.get("COLUMN_ID"));
				List<Map<String, Object>> listData_all = business
						.list_portlet_mytemplate_all(l_all);
				for (Map<String, Object> rm : listData_all) {
					rm.remove("RSS_CONTENT");
					rm.remove("TAKE_CONTENT");
				}
				listDataAll.addAll(listData_all);

				int listDataCount = listDataAll.size();

				data.put("rowSet", QueryParamUtil.DateToString(listDataAll));
				data.put("pageNo", 1);
				data.put("pageSize", listDataCount);
				data.put("pageCount", listDataCount);
				data.put("rows", data.get("rowSet"));
				data.put("total", listDataCount);
			}
			jsonObject = new JSONObject();
			jsonObject.putAll(data);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "json";
	}

	public String listPSetup() throws BusinessException, IOException {
		PortletBusiness business = BusinessManager
				.getBusiness(PortletBusiness.class);
		Map<String, Object> query = RequestUtils.getUpdateFieldMap(request,
				RequestUtils.UPDATEDATAFIELDPREFIX);

		try {
			query = QueryParamUtil.StringToDate(query);
			Page<Map<String, Object>> pageRows = business.list_portlet_setup(
					pageNo, pageSize, query);
			setPageCount((pageRows.getCount() - 1) / pageSize + 1);
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("rowSet", QueryParamUtil.ClobToString(QueryParamUtil
					.DateToString(pageRows.getItems())));
			data.put("pageNo", pageNo);
			data.put("pageSize", pageSize);
			data.put("pageCount", pageCount);
			data.put("rows", data.get("rowSet"));
			data.put("total", pageRows.getCount());
			jsonObject = new JSONObject();
			jsonObject.putAll(data);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "json";
	}

	public String listAllPSetup() throws BusinessException, IOException {
		PortletBusiness business = BusinessManager
				.getBusiness(PortletBusiness.class);
		Map<String, Object> query = RequestUtils.getUpdateFieldMap(request,
				RequestUtils.UPDATEDATAFIELDPREFIX);

		try {
			query = QueryParamUtil.StringToDate(query);
			List<Map<String, Object>> listData = business
					.list_portlet_setup(query);
			int listDataCount = business.listCount_portlet_setup(query);
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("rowSet", QueryParamUtil.ClobToString(QueryParamUtil
					.DateToString(listData)));
			data.put("pageNo", 1);
			data.put("pageSize", listDataCount);
			data.put("pageCount", listDataCount);
			data.put("rows", data.get("rowSet"));
			data.put("total", listDataCount);
			jsonObject = new JSONObject();
			jsonObject.putAll(data);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "json";
	}

	public String urlData() throws BusinessException {
		PortletBusiness business = BusinessManager.getBusiness(PortletBusiness.class);
		Map<String, Object> query = RequestUtils.getUpdateFieldMap(request,RequestUtils.UPDATEDATAFIELDPREFIX);
		try {
			query = QueryParamUtil.StringToDate(query);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		List<Map<String, Object>> listData = business
				.list_portlet_template(query);
		Map<String, Object> l_data = listData.get(0);
		String content = "";
		String view_content = "";
		String view_content1 = "";
		if (l_data.get("URL") != null) {
			String take_url = (String) l_data.get("URL");
			String take_start = (String) l_data.get("TAKE_START");
			String take_end = (String) l_data.get("TAKE_END");
			String url_encoded = (String) l_data.get("URL_ENCODED");
			String is_pop = (String) l_data.get("IS_POP");
			String title = (String) l_data.get("TITLE");

			// request.getHeader("Host")替换
			String myurl = take_url;
			myurl = myurl.substring(myurl.indexOf("http://") + 7);
			myurl = myurl.substring(0, myurl.indexOf("/"));

			content = UrlDataUtil.getUrlContent(take_url, take_start, take_end,url_encoded);
			view_content = content;

			String pattern = "href=\"([^\"]*)\"";
			Pattern pKey = Pattern.compile(pattern, 2 | Pattern.DOTALL);
			Matcher mKey = pKey.matcher(content);
			boolean result = mKey.find();
			while (result) {
				if (mKey.group(1).indexOf("http://") == -1) {
					view_content = view_content.replace(mKey.group(1),
							"http://" + myurl + mKey.group(1));
				}
				result = mKey.find();
			}
			// 设计转新页面还是弹出
			view_content1 = view_content;
			pattern = "<a(.*?)>(.*?)";
			pKey = Pattern.compile(pattern, 2 | Pattern.DOTALL);
			mKey = pKey.matcher(view_content);
			result = mKey.find();
			while (result) {
				if (is_pop != null && StringUtils.equals(is_pop, "1")) {// 转到新页面

					if (mKey.group(1).toLowerCase().indexOf("target=") == -1) {
						view_content1 = view_content1.replace(mKey.group(1),
								mKey.group(1) + " target=\"_blank\"");
					}
				} else {// 默认弹出
					String pattern1 = "href=\"([^\"]*)\"";
					Pattern pKey1 = Pattern.compile(pattern1,
							2 | Pattern.DOTALL);
					Matcher mKey1 = pKey1.matcher(mKey.group(1));
					mKey1.find();
					String t_href = mKey1.group(1);
					view_content1 = view_content1.replace(mKey.group(1),
							" href = \"javascript:window.parent.openNewNoLock('"
									+ t_href + "','','" + title
									+ "',915,500);\"");

				}
				result = mKey.find();
			}
			// System.out.println(view_content1);
		}
		view_content1 = view_content1.replaceAll("\\s+", " ");
		query.put("TAKE_CONTENT", view_content1);
		business.update_portlet_template(query);
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("rowSet", view_content1);
		data.put("pageNo", 1);
		data.put("pageSize", 1);
		data.put("pageCount", 1);
		data.put("rows", data.get("rowSet"));
		data.put("total", 1);
		jsonObject = new JSONObject();
		jsonObject.putAll(data);

		return "json";
	}
	/**
	 * 控制'控制面板'隐藏或显示
	 */
	public String showFunc() throws BusinessException{
		String userid=SessionUtil.getCode();
		UnitBusiness business=BusinessManager
		.getBusiness(UnitBusiness.class);
		String G_ID = AuthenticateUtil.getEndpoint("G_ID");
		try {
			G_ID = new String(G_ID.getBytes("ISO8859-1"), "utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		List<String> list =  StringToList(G_ID);
		Map<String , Object>query=new HashMap<String, Object>();
		query.put("listgid", list);
		query.put("U_ID", userid);
		int count=0;
		count=business.userGroup(query);
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("count", count);
		jsonObject = new JSONObject();
		jsonObject.putAll(data);

		return "json";
	}
	/**
	 * 将,分隔的字符转成list<String>模式
	 * @param key
	 * @return
	 */
	public static List<String> StringToList(String key){
		List<String> list = new ArrayList<String>();
		if(StringUtils.isNotEmpty(key)){
		   String s[] = StringUtils.split((String) key, ",");
		   for(String st:s){
			   list.add(st);
		   }
		}
 		return list;
	}
	
	/**    
     * 根据链接地址得到数据    
     * @param url RSS形式的xml文件    
     * @throws IllegalArgumentException    
     * @throws FeedException    
     */     
    public static void parseXml(String url) throws IllegalArgumentException, FeedException {         
     
        try {         
        	URL Url=new URL(url);
            SyndFeedInput input = new SyndFeedInput();         
            SyndFeed feed = null;         
            URLConnection conn;         
            conn = Url.openConnection();         
            String content_encoding = conn.getHeaderField("Content-Encoding");         
                  
            if (content_encoding != null && content_encoding.contains("gzip")) {         
                System.out.println("conent encoding is gzip");         
                GZIPInputStream gzin = new GZIPInputStream(conn         
                        .getInputStream());         
                feed = input.build(new XmlReader(gzin));         
            } else {         
                feed = input.build(new XmlReader(conn.getInputStream()));         
            }         
                  
            List entries = feed.getEntries();//得到所有的标题<title></title>      
            for(int i=0; i < entries.size(); i++) {      
                SyndEntry entry = (SyndEntry)entries.get(i);      
//                System.out.println(entry.getTitle());   
//                System.out.println(entry.getAuthor());   
//                System.out.println(entry.getDescription().getValue());     
//                System.out.println(entry.getLink());   
            }      
            System.out.println("feed size:" + feed.getEntries().size());         
              
        } catch (IOException e) {         
            e.printStackTrace();         
        }         
	}

	public static void main(String[] args) throws Exception, FeedException {
		parseXml("http://rss.sina.com.cn/news/marquee/ddt.xml");
	}
}
