package com.uas.platform.b2b.support;

import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

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

import net.sf.jxls.transformer.XLSTransformer;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.LocalizedResourceHelper;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.servlet.view.document.AbstractExcelView;

import com.uas.platform.b2b.core.util.ContextUtils;
import com.uas.platform.b2b.core.util.DateFormatUtils;

/**
 * 利用jxls模板生成excel
 * 
 * @author yingp
 * 
 */
public class JxlsExcelView extends AbstractExcelView {

	/**
	 * 最大导出行
	 */
	public final static int MAX_SIZE = 50000;

	private String fileName;

	private static final String EXTENSION = ".xls";

	public JxlsExcelView(String tplPath, String fileName) {
		super();
		setUrl(tplPath);
		this.fileName = fileName;
	}

	@Override
	protected HSSFWorkbook getTemplateSource(String url, HttpServletRequest request) throws Exception {
		LocalizedResourceHelper helper = new LocalizedResourceHelper(ContextUtils.getApplicationContext());
		Locale userLocale = RequestContextUtils.getLocale(request);
		Resource inputFile = helper.findLocalizedResource(url, EXTENSION, userLocale);
		if (this.logger.isDebugEnabled()) {
			this.logger.debug("Loading Excel workbook from " + inputFile);
		}
		POIFSFileSystem fs = new POIFSFileSystem(inputFile.getInputStream());
		return new HSSFWorkbook(fs);
	}

	@Override
	protected void buildExcelDocument(Map<String, Object> map, HSSFWorkbook workbook, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if (map == null) {
            map = new HashMap<String, Object>();
        }
		map.put("export", new Export());
		XLSTransformer transformer = new XLSTransformer();
		transformer.transformWorkbook(workbook, map);
		response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8") + EXTENSION);
	}

	public class Export {

		private String date;
		private String user;

		public String getDate() {
			return date;
		}

		public void setDate(String date) {
			this.date = date;
		}

		public String getUser() {
			return user;
		}

		public void setUser(String user) {
			this.user = user;
		}

		public Export() {
			this.user = SystemSession.getUser().getUserName();
			this.date = DateFormatUtils.DATETIME_FORMAT.format(new Date());
		}
	}

}
