package com.dev.swms.server.web.servlet.export.impl;

import com.dev.energy.client.config.page.ColumnProperty;
import com.dev.energy.client.config.page.TableConfig;
import com.dev.energy.server.format.Formatter;
import com.dev.energy.server.service.ValueListQueryManager;
import com.dev.energy.server.util.LocalizedMessage;
import com.dev.swms.server.utils.ConvertEnumName;
import com.dev.swms.server.web.servlet.export.ExportExcelGenerator;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletResponse;
import jxl.Workbook;
import jxl.biff.EmptyCell;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.WritableCell;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import net.mlw.vlh.ValueList;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class XLSExportGenerator implements ExportExcelGenerator, ApplicationContextAware {

  // private ApplicationContext ac;
   private static final WritableFont detFont = new WritableFont(WritableFont.ARIAL, 9, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
   private static final WritableCellFormat detFormat = new WritableCellFormat(detFont);
   private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");


   public void exportExcel(ApplicationContext ac,String hql, Map params, TableConfig tableConfig, HttpServletResponse res, String referenceModel, String locale) throws Exception {
	   String pagingNumberPer="40000";
	   String pageName = this.sdf.format(new Date());
      Pattern pattern = Pattern.compile("\\s+");
      Matcher matcher = pattern.matcher(pageName);
      pageName = matcher.replaceAll("");
      String header = "attachment; filename=" + pageName + ".xls";
      res.setCharacterEncoding("GBK");
      res.setContentType("application/ms-excel; charset=GBK");
      res.setHeader("content-disposition", header);
      WritableWorkbook workbook = Workbook.createWorkbook(res.getOutputStream());
      params.put("pagingNumberPer", pagingNumberPer);
      params.put("pagingPage", "1");
      ValueListQueryManager gridQueryManager = (ValueListQueryManager)ac.getBean("valueListQueryManager");
      int s1=hql.indexOf("where");
      if(s1<0){
    	  s1=hql.indexOf("WHERE");
      }
      int s2=hql.indexOf("and 1=1");
      if(s2>0){
    	  if(s2-s1<=50){
	    	  String str=hql.substring(s1, s2);
	          hql=hql.replace(str, "where 1=1 ");
    	  }
      }
      ValueList valueList = gridQueryManager.queryByValueList(hql, params);
      int offset = 1;
      int exportTotalPages = valueList.getValueListInfo().getTotalNumberOfPages();
         do {
        	 int var27 = 1;
        	  pageName = this.sdf.format(new Date());
              pattern = Pattern.compile("\\s+");
              matcher = pattern.matcher(pageName);
             pageName = matcher.replaceAll("");
        	WritableSheet sheet = workbook.createSheet(pageName, offset);
            this.exportXLSTitle(tableConfig, sheet, referenceModel, locale);
            if(offset > 1) {
               params.put("pagingNumberPer", pagingNumberPer);
               params.put("pagingPage", "" + offset);
               valueList = gridQueryManager.queryValueList(hql, params);
            }
            for(Iterator var26 = valueList.getList().iterator(); var26.hasNext(); ++var27) {      
               Object[] objs= (Object[])var26.next();
               ArrayList list = new ArrayList();
               Collections.addAll(list, objs);
               List columnProperties = tableConfig.getColumnProperties();
               int cloSize=columnProperties.size();
             
               for(int col = 0; col <cloSize ; ++col) {
                  ColumnProperty property = (ColumnProperty)columnProperties.get(col);
                  this.writeSheetByType(ac,sheet, property, list, referenceModel, locale, var27, col);
               }
            }
            System.out.println("打印"+offset);
         } while(offset++ < exportTotalPages);
      workbook.write();
      workbook.close();
      res.getOutputStream().flush();
      res.getOutputStream().close();
   }

   protected void exportXLSTitle(TableConfig tableConfig, WritableSheet sheet, String model, String locale) throws Exception {
      WritableFont titleFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
      WritableCellFormat titleFormat = new WritableCellFormat(titleFont);
      titleFormat.setBackground(Colour.GRAY_25);
      titleFormat.setBorder(Border.ALL, BorderLineStyle.THIN);
      Label label = null;
      List columnProperties = tableConfig.getColumnProperties();
    	  for(int col = 0; col < columnProperties.size(); ++col) {
    	         ColumnProperty property = (ColumnProperty)columnProperties.get(col);
    	         if(property.isExportExcel()) {
    	            label = new Label(col, 0, LocalizedMessage.getLocalizedMessage(property.getTitle(), model, locale), titleFormat);
    	            sheet.addCell(label);
    	         }
      }
   }

//   public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
//      this.ac = applicationContext;
//   }

   protected void writeSheetByType(ApplicationContext ac,WritableSheet sheet, ColumnProperty property, List values, String model, String locale, int row, int col) throws RowsExceededException, WriteException, ParseException {
      if(property.isExportExcel()) {
         Object cell = null;
         Object value = values.get(property.getValueIndex());
         if(value != null && !"-".equals(value) && !"".equals(value)) {
            if(value instanceof Number) {
               cell = new jxl.write.Number(col, row, NumberUtils.createDouble(value.toString()).doubleValue());
            } else if(value instanceof java.sql.Date) {
               cell = new Label(col, row, dateFormatter.format(value), detFormat);
            } else if(value instanceof Timestamp) {
            	if(property.getTitle().indexOf("日期")!=-1){
            		 cell = new Label(col, row, dateFormatter.format(value), detFormat);
            	}else{
            		cell = new Label(col, row, datetimeFormatter.format(value), detFormat);
            	}
            } else {
               if(property.getFormat() != null && property.getFormat().length() > 0) {
                  Formatter formatter = (Formatter)ac.getBean(property.getFormat());
                  value =convertFormat(formatter, value, property, values, model, locale);
               }

               cell = new Label(col, row, value.toString(), detFormat);
            }
         } else {
            cell = new EmptyCell(col, row);
         }

         sheet.addCell((WritableCell)cell);
      }
   }

	@Override
	public void setApplicationContext(ApplicationContext arg0) throws BeansException {
		// TODO Auto-generated method stub
		
	}
	//format转换
	private String convertFormat(Formatter formatter,Object value, ColumnProperty property, List values, String model, String locale ){
		String v=ConvertEnumName.getConvertName(value+"");
		if(v.equals(value)){
			return formatter.format(property.getFormatParam(), value, values, model, locale);
		}else{
			return v;
		}
	}
}
