package com.mingsoft.servlet.admin.article;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

import com.mingsoft.biz.IArticleBiz;
import com.mingsoft.biz.impl.ArticleBizImpl;
import com.mingsoft.constant.JspPage;
import com.mingsoft.entity.ArticleEntity;
import com.mingsoft.servlet.BaseServlet;
import com.mingsoft.util.StringUtil;
/**
 * 显示文章列表
 * @author Administrator
 *			荣繁奎
 * QQ:1096199590
 * 技术支持：铭飞科技
 * 官网：www.ming-soft.com
 */
public class ArticleListServlet extends BaseServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(request, response);
		
		if(request.getParameter("type")!=null||request.getParameter("type")=="json"){
			doPost(request, response);
		}else{
			request.getRequestDispatcher(JspPage.ARTICLE_LIST).forward(request, response);
		}
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doPost(request, response);
		PrintWriter out = response.getWriter();
		//列表的显示的页数
		String page = request.getParameter("page");
		//每页显示的条数
		String rows = request.getParameter("rows");
		int pageNum = 1;
		int pageSize = 10;
		if(!StringUtil.strNull(page)&&(!StringUtil.strNull(rows))){
			pageSize = Integer.parseInt(rows);
			pageNum = (Integer.parseInt(page)-1)*pageSize;
			
		}
		IArticleBiz articleBiz = new ArticleBizImpl(); 
		List<ArticleEntity> list = articleBiz.queryForList(pageNum,pageSize);
		int total = articleBiz.queryArtcTotal();
		//过滤器 把时间对象转换为String
		JsonConfig config = new JsonConfig();
		config.registerJsonValueProcessor(Date.class, new JsonValueProcessor() {
			public Object processObjectValue(String arg0, Object arg1,
					JsonConfig arg2) {
				// TODO Auto-generated method stub
				SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
				return sd.format((Date) arg1);
			}

			public Object processArrayValue(Object arg0, JsonConfig arg1) {
				// TODO Auto-generated method stub
				return null;
			}
		});
		String str = "{\"total\":"+total+",\"rows\":"+JSONArray.fromObject(list, config).toString()+"}";
		out.write(str);
		out.close();
	}
}
