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.web.servlet.export.ExportExcelGenerator;

import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletResponse;
import net.mlw.vlh.ValueList;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class CSVExportGenerator implements ExportExcelGenerator, ApplicationContextAware {

   private ApplicationContext ac;
   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 pageName = this.sdf.format(new Date());
      Pattern pattern = Pattern.compile("\\s+");
      Matcher matcher = pattern.matcher(pageName);
      pageName = matcher.replaceAll("");
      String header = "attachment; filename=" + pageName + ".csv";
      res.setCharacterEncoding("GBK");
      res.setContentType("application/ms-excel; charset=GBK");
      res.setHeader("content-disposition", header);
      ValueListQueryManager gridQueryManager = (ValueListQueryManager)this.ac.getBean("valueListQueryManager");
      boolean isfirst = true;
      StringBuffer titles = new StringBuffer();

      for(int writer = 0; writer < tableConfig.getColumnProperties().size(); ++writer) {
         ColumnProperty offset = (ColumnProperty)tableConfig.getColumnProperties().get(writer);
         if(offset.isExportExcel()) {
            if(isfirst) {
               isfirst = false;
            } else {
               titles.append(",");
            }

            titles.append(LocalizedMessage.getLocalizedMessage(offset.getTitle(), referenceModel, locale));
         }
      }

      PrintWriter var28 = res.getWriter();
      var28.println(titles);
      int var27 = 0;
      params.put("pagingNumberPer", "5000");

      int exportTotalPages;
      do {
         ++var27;
         params.put("pagingPage", "" + var27);
         ValueList valueList = gridQueryManager.queryByValueList(hql, params);
         exportTotalPages = valueList.getValueListInfo().getTotalNumberOfPages();
         StringBuffer sb = new StringBuffer();
         Iterator i = valueList.getList().iterator();

         while(i.hasNext()) {
            sb.setLength(0);
            Object[] objs = null;
            Object obj = i.next();
            if(obj instanceof Object[]) {
               objs = (Object[])obj;
            } else {
               objs = new Object[]{obj};
            }
            ArrayList list = new ArrayList();
            int j;
            for(j = 0; j < objs.length; ++j) {
               list.add(objs[j]);
            }
            isfirst = true;

            for(j = 0; j < tableConfig.getColumnProperties().size(); ++j) {
               ColumnProperty property = (ColumnProperty)tableConfig.getColumnProperties().get(j);
               String columnValue = "";
               if(property.isExportExcel()) {
                  if(property.getValueIndex() < objs.length) {
                     columnValue = this.convertToStringIfNecessary(objs[property.getValueIndex()]).toString();
                  }

                  if(property.getFormat() != null && property.getFormat().length() > 0) {
                     Formatter formatter = (Formatter)this.ac.getBean(property.getFormat());
                     if(!"-".equals(columnValue) && columnValue.length() != 0) {
                        columnValue = formatter.format(property.getFormatParam(), columnValue, list, referenceModel, locale);
                     }
                  }

                  if(isfirst) {
                     isfirst = false;
                  } else {
                     sb.append(",");
                  }

                  sb.append(columnValue);
               }
            }

            var28.println(sb);
         }
      } while(var27 < exportTotalPages);

   }

   private Object convertToStringIfNecessary(Object object) {
      if(object == null) {
         return "-";
      } else if(object instanceof Long) {
         return object;
      } else {
         String temp;
         if(object instanceof java.sql.Date) {
            temp = dateFormatter.format(object);
            if(temp.startsWith("1900")) {
               temp = "";
            }

            return temp;
         } else if(object instanceof Timestamp) {
            temp = datetimeFormatter.format(object);
            if(temp.startsWith("1900")) {
               temp = "";
            }

            return temp;
         } else if(!object.toString().contains(",")) {
            if(object.toString().contains("\n")) {
               temp = object.toString();
               temp = StringUtils.replace(temp, "\n", " ");
               return temp;
            } else if(object.toString().contains("\r\n")) {
               temp = object.toString();
               temp = StringUtils.replace(temp, "\r\n", " ");
               return temp;
            } else {
               return object.toString();
            }
         } else {
            for(temp = object.toString(); temp.contains(","); temp = temp.replace(",", "，")) {
               ;
            }

            return temp;
         }
      }
   }

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


}
