package cn.base.servlet;

import java.io.OutputStream;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.lowagie.text.Document;
import com.lowagie.text.PageSize;
import com.lowagie.text.rtf.RtfWriter2;

public abstract class ExportWord {
	private static Logger log = Logger.getLogger(ExportWord.class);
	private HttpServletResponse response;
	private Document document;
	private String fileName;
	
	public Document getDocument() {
		return document;
	}

	public void setDocument(Document document) {
		this.document = document;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	/**
	 * 
	 * @param response 
	 * @param fileName
	 * @param col ±νΈρΑΠΚύ
	 */
	public ExportWord(HttpServletResponse response, String fileName) {
		this.response = response;
		this.fileName = fileName;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public void export(Map map) throws Exception{
		initDocument();
		initTable(map);
		close();
	}
	
	public void initDocument() {
		try {
			byte[] yte = fileName.getBytes("GB2312");  
			fileName = new String(yte, "ISO-8859-1");
			response.setHeader("Content-disposition", "attachment; filename="+fileName);  
			response.setContentType("application/msword");
			document = new Document(PageSize.A4);
			OutputStream out = response.getOutputStream();
			RtfWriter2.getInstance(document, out);
			document.open();
		} catch(Exception e) {
			log.error("ExportWord-initDocument:" + e);
		}
	}
	
	protected abstract  void initTable(Map map) ;
	
	public void close() {
		try {
			document.close();
			OutputStream out = response.getOutputStream();
			out.flush();
			out.close();
		} catch(Exception e) {
			log.error("ExportWord-close:" + e);
		}
	}
}
