下载csv

package com.cathayins.cn.ae.k6.trx;

import com.cathay.ac.common.UnitUtil;
import com.cathay.ac.common.vo.UnitInfo_vo;
import com.cathay.common.bo.ReturnMessage;
import com.cathay.common.exception.DataNotFoundException;
import com.cathay.common.exception.ModuleException;
import com.cathay.common.service.authenticate.UserObject;
import com.cathay.common.trx.UCBean;
import com.cathay.common.util.DATE;
import com.cathay.common.util.IConstantMap;
import com.cathay.fm.component.FM_A0Z001;
import com.cathay.util.ReturnCode;
import com.cathayins.cn.ae.k6.module.AEK6_0002_mod;
import com.cathayins.cn.ae.k6.module.AEK6_0003_mod;
import com.cathayins.cn.common.RequestContextParser;
import com.igsapp.common.trx.ServiceException;
import com.igsapp.common.trx.TxException;
import com.igsapp.wibc.dataobj.Context;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.StringReader;
import java.math.BigDecimal;
import java.util.*;


/**
* <pre>
* 一、   程式功能概要说明﹕
* 1.    程式功能﹕统计作业_报表管理_董事长特别奖查询。
* 2.     程式名称﹕AEK6_0003.java
* 3.     作业方式﹕线上查询
* 4.   概要说明﹕
* 计算业绩提前奖。
* 5.   处理人员:System Timer。
* <p/>
* 二、   程式结构﹕
* <p/>
* <p/>
* 三、   传输参数
* 1.   竞赛种类选择。
* 2.   查询年度。预设当年度,可往前三年可下拉选择。
* 3.   查询季度。预设当季。
* <p/>
* 四、   相关档(TABLE)﹕
* 4.   INPUT1:主管单位责任额档 DTAGA028。
* 5.   INPUT2:报表栏位数据统计历史档DTAEK070。
* <p/>
* 五、   使用模组﹕
*      1.  批次作业异常讯息记录模组:ZZ_X0Z002.java
*      2.      批次作业处理件数记录模组:ZZ_X0Z001.java
*      3.      批次处理日期赋予模组:AC_00Z040.java
*      4.      读取当天之日期模组:DATE.getDBDate();
*      5.      单位模块:Unit.java.
*      6.      人事模块:FM_A0Z001.java
* <p/>
* </pre>
*
* @author zhenghao
* @since 2009-11-05
*/

public class AEK6_0003 extends UCBean{

        private Logger logger = Logger.getLogger(this.getClass());

    private Context.ResponseContext resp;

    private ReturnMessage msg;

    private UserObject user;

    private AEK6_0003_mod mod;


    public Context.ResponseContext doPrompt(Context.RequestContext req) throws TxException {
        msg.setReturnCode(ReturnCode.OK);
        msg.setMsgDesc("董事长特别奖查询 - 作业开始");

        loadConstants();
        resp.setResponseCode("success");
        return resp;
    }
   
    //查询部门的总体信息
    public Context.ResponseContext doQuery(Context.RequestContext req) throws TxException {
        msg.setReturnCode(ReturnCode.OK);
        msg.setMsgDesc("查詢完成");

        String YEAR = req.getParameter("YEAR");
        String SEASON = req.getParameter("SEASON");
       
        if (logger.isDebugEnabled()) {
            logger.debug("YEAR = " + YEAR);
            logger.debug("SEASON = " + SEASON);
        }

        List<Map> result = Collections.emptyList();
        try {
            result = query(YEAR, SEASON);
            FM_A0Z001 fm = new FM_A0Z001();
                UnitUtil util = new UnitUtil();
                for(int i = 0; i < result.size(); i++){
                        Map list = result.get(i);
                //将单位中文名称add到结果的list中
                UnitInfo_vo vo;
                String div1 = list.get("DIV_NO1").toString();
                String div2 = list.get("DIV_NO2").toString();
                vo = util.getContentByDivNo(div1, div2);
                String DIV_NAME = vo.getDIV_NAME();
                list.put("DIV_NAME", DIV_NAME);
                }
            putValue("point",result);
        } catch (DataNotFoundException e) {
            msg.setMsgDesc("查無資料");
        } catch (ModuleException e) {
            String msgStr = "查詢失敗!\n" + e.getMessage();
            msg.setReturnCode(ReturnCode.ERROR);
            msg.setMsgDesc(msgStr);
            logger.error(msgStr, e);
        }

        if (logger.isDebugEnabled()) {
            logger.debug("result = " + result);
        }
        resp.addOutputData("result", result);
        resp.setResponseCode("success");
        return resp;
    }


    private List query(String YEAR, String SEASON) throws ModuleException {
        HashMap aMap = new HashMap();
        if (StringUtils.equals(SEASON, "1")) {  
                aMap.put("START_DATE_1", YEAR + "0101");
                aMap.put("END_DATE_1", YEAR + "0331");
        } else if (StringUtils.equals(SEASON, "2")) {
                aMap.put("START_DATE_1", YEAR + "0401");
                aMap.put("END_DATE_1", YEAR + "0630");
        } else if (StringUtils.equals(SEASON, "3")) {
                aMap.put("START_DATE_1", YEAR + "0701");
                aMap.put("END_DATE_1", YEAR + "0930");
        } else if (StringUtils.equals(SEASON, "4")) {
                aMap.put("START_DATE_1", YEAR + "1001");
                aMap.put("END_DATE_1", YEAR + "1231");
        }
        aMap.put("YEAR",YEAR);
        aMap.put("SEASON",SEASON);
 
        List<Map> result = Collections.emptyList();
        result = mod.query(aMap);
       
        return result;
    }

   
    //查询部门下具体全部员工信息
    public Context.ResponseContext doQuery2(Context.RequestContext req) throws TxException{
        msg.setReturnCode(ReturnCode.OK);
        msg.setMsgDesc("查詢完成");

        String YEAR = req.getParameter("YEAR");
        String SEASON = req.getParameter("SEASON");
        String DIV_NO1 = req.getParameter("DIV_NO1");
       
        if (logger.isDebugEnabled()) {
            logger.debug("YEAR = " + YEAR);
            logger.debug("SEASON = " + SEASON);
        }

        HashMap aMap = new HashMap();
        if (StringUtils.equals(SEASON, "1")) {  
                aMap.put("START_DATE_1", YEAR + "0101");
                aMap.put("END_DATE_1", YEAR + "0331");
        } else if (StringUtils.equals(SEASON, "2")) {
                aMap.put("START_DATE_1", YEAR + "0401");
                aMap.put("END_DATE_1", YEAR + "0630");
        } else if (StringUtils.equals(SEASON, "3")) {
                aMap.put("START_DATE_1", YEAR + "0701");
                aMap.put("END_DATE_1", YEAR + "0930");
        } else if (StringUtils.equals(SEASON, "4")) {
                aMap.put("START_DATE_1", YEAR + "1001");
                aMap.put("END_DATE_1", YEAR + "1231");
        }
        aMap.put("YEAR",YEAR);
        aMap.put("SEASON",SEASON);
        aMap.put("DIV_NO1",DIV_NO1);
       
        List<Map> result_1 = Collections.emptyList();
        try {
                result_1 = mod.query_1(aMap);
                FM_A0Z001 fm = new FM_A0Z001();
                UnitUtil util = new UnitUtil();
                for(int i = 0; i < result_1.size(); i++){
                        //将员工姓名中文名称add到结果的list中
                        Map list = result_1.get(i);
                        String EMP_NO = list.get("EMP_NO").toString();
                Hashtable ht = fm.getEmpBasic(EMP_NO);
                String EMP_NAME="";
                if(ht == null ||ht.isEmpty()||ht.size()==0){
                        EMP_NAME="";
                }else{
                        EMP_NAME= ht.get("EMP_NAME")==null?"":ht.get("EMP_NAME").toString();
                }
                list.put("EMP_NAME", EMP_NAME);
                //将单位中文名称add到结果的list中
                UnitInfo_vo vo;
                String div1 = list.get("DIV_NO1").toString();
                String div2 = list.get("DIV_NO2").toString();
                vo = util.getContentByDivNo(div1, div2);
                String DIV_NAME = vo.getDIV_NAME();
                list.put("DIV_NAME", DIV_NAME);
                }
                putValue("point",result_1);
        } catch (DataNotFoundException e) {
            msg.setMsgDesc("查無資料");
        } catch (ModuleException e) {
            String msgStr = "查詢失敗!\n" + e.getMessage();
            msg.setReturnCode(ReturnCode.ERROR);
            msg.setMsgDesc(msgStr);
            logger.error(msgStr, e);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("result_1 = " + result_1);
        }

        resp.addOutputData("result_1", result_1);
        resp.setResponseCode("success");
        return resp;
    }
   
    private String calculatePREM_RATE(String PREM, String PFM_FYP_QUOTA) {
        if (!StringUtils.equals(PREM, "") && !StringUtils.equals(PREM, "0") && !StringUtils.equals(PFM_FYP_QUOTA, "") && !StringUtils.equals(PFM_FYP_QUOTA, "0")) {
            return new BigDecimal(PREM).divide(new BigDecimal(PFM_FYP_QUOTA), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2).toString();
        } else {
            return "0";
        }
    }


    public class SortByTotalPREM_RATE implements Comparator<Map> {
        public int compare(Map map1, Map map2) {
            BigDecimal PREM_RATE_map1 = new BigDecimal(ObjectUtils.defaultIfNull(map1.get("PREM_RATE_1"), "0").toString()).add(new BigDecimal(ObjectUtils.defaultIfNull(map1.get("PREM_RATE_2"), "0").toString())).add(new BigDecimal(ObjectUtils.defaultIfNull(map1.get("PREM_RATE_3"), "0").toString()));
            BigDecimal PREM_RATE_map2 = new BigDecimal(ObjectUtils.defaultIfNull(map2.get("PREM_RATE_1"), "0").toString()).add(new BigDecimal(ObjectUtils.defaultIfNull(map2.get("PREM_RATE_2"), "0").toString())).add(new BigDecimal(ObjectUtils.defaultIfNull(map2.get("PREM_RATE_3"), "0").toString()));
            return PREM_RATE_map2.compareTo(PREM_RATE_map1);
        }
    }


    public Context.ResponseContext doPrint(Context.RequestContext req) throws TxException {
        msg.setReturnCode(ReturnCode.OK);
        msg.setMsgDesc("下载成功");

        String YEAR = req.getParameter("YEAR");
        String SEASON = req.getParameter("SEASON");
        if (logger.isDebugEnabled()) {
            logger.debug("YEAR = " + YEAR);
            logger.debug("SEASON = " + SEASON);
        }

        List result = Collections.emptyList();
        try {
            result = query(YEAR, SEASON);
        } catch (DataNotFoundException e) {
        } catch (ModuleException e) {
            String msgStr = "下载失敗!\n" + e.getMessage();
            msg.setReturnCode(ReturnCode.ERROR);
            msg.setMsgDesc(msgStr);
            logger.error(msgStr, e);
        }

        if (result.size() > 0) {
                StringBuffer csv_strbuf = composeCVS(result);

            RequestContextParser contextParser = new RequestContextParser(req);
            HttpServletResponse httpResponse = contextParser.getHttpResponse();
            String fullFileName = DATE.getDBTimeStamp() + ".csv";
            if (logger.isDebugEnabled()) {
                logger.debug("fullFileName = " + fullFileName);
            }

            try {
                httpResponse.setContentType("application/cvsfile");
                httpResponse.setHeader("Content-Disposition", "attachment; filename=" + fullFileName);
                ServletOutputStream servletOutputStream = httpResponse.getOutputStream();
                IOUtils.copy(new StringReader(csv_strbuf.toString()), servletOutputStream);
                servletOutputStream.flush();
            } catch (IOException e) {
                String msgStr = "列印失敗\n" + e.getMessage();
                msg.setMsgDesc(msgStr);
                msg.setReturnCode(ReturnCode.ERROR);
            }
        }


        resp.setResponseCode("success");
        return resp;
    }

    private StringBuffer composeCVS(List<Map> result){
        StringBuffer csv_strbuf = new StringBuffer();
        try{
                FM_A0Z001 fm = new FM_A0Z001();
            UnitUtil util = new UnitUtil();
            // first line
            appendStringBuffer(csv_strbuf, "单位中文", false);
            appendStringBuffer(csv_strbuf, "员工姓名", false);
            appendStringBuffer(csv_strbuf, "目标", false);
            appendStringBuffer(csv_strbuf, "已达成保费", false);
            appendStringBuffer(csv_strbuf, "与目标差距", true);

            List<Map> list = Collections.emptyList();      
            list = (List<Map>) getValue("point");
           
            for (int i = 0; i < list.size(); i++) {
                Map aMap = list.get(i);
               
                appendStringBuffer(csv_strbuf, ObjectUtils.defaultIfNull(aMap.get("DIV_NAME"),"").toString(), false);
                appendStringBuffer(csv_strbuf, ObjectUtils.defaultIfNull(aMap.get("EMP_NAME"), "").toString(), false);
                appendStringBuffer(csv_strbuf, ObjectUtils.defaultIfNull(aMap.get("AIM"), "").toString(), false);
                appendStringBuffer(csv_strbuf, ObjectUtils.defaultIfNull(aMap.get("PREM"), "").toString(), false);
                appendStringBuffer(csv_strbuf, ObjectUtils.defaultIfNull(aMap.get("DIFF"), "").toString(), true);
            }  
        }catch (ModuleException e){
                String msgStr = "下载失敗!\n" + e.getMessage();
            msg.setReturnCode(ReturnCode.ERROR);
            msg.setMsgDesc(msgStr);
            logger.error(msgStr, e);
        }
        return csv_strbuf;
    }

    private StringBuffer appendStringBuffer(StringBuffer strbuf, String str, boolean isEndLine) {
        if ((null == str) || (str.length() == 0)) {
            str = " ";
        } else {
            str = str.trim();
        }

        if (isEndLine) {
            return strbuf.append(str + System.getProperty("line.separator"));
        } else {
            return strbuf.append(str + ",");
        }
    }


    private void loadConstants() {
        StringBuilder errorMsg = new StringBuilder();
        int year = Integer.parseInt(StringUtils.split(DATE.getDBDate(), "-")[0]);
        List<String> yearList = new ArrayList();
        for (int i = 0; i < 3; i++) {
            yearList.add(Integer.toString(year--));
        }
        resp.addOutputData("yearList", yearList);

        String season = "";
        Integer month = Integer.parseInt(StringUtils.split(DATE.getDBDate(), "-")[1]);
        if (month < 4) {
            season = "1";
        } else if (month >= 4 && month < 7) {
            season = "2";
        } else if (month >= 7 && month < 10) {
            season = "3";
        } else {
            season = "4";
        }
        resp.addOutputData("season", season);

        if (errorMsg.length() > 0) {
            msg.setReturnCode(ReturnCode.ERROR);
            msg.setMsgDesc(errorMsg.toString());
        }
    }


    public Context.ResponseContext start(Context.RequestContext req) throws ServiceException, TxException {
        super.start(req);
        initApp(req);
        return null;
    }

    private void initApp(Context.RequestContext req) {
        resp = this.newResponseContext();
        msg = new ReturnMessage();
        user = this.getUserObject(req);

        resp.addOutputData(IConstantMap.ErrMsg, msg);

        try {
            mod = new AEK6_0003_mod();
        } catch (ModuleException e) {
            logger.error(e, e);
        }
    }
}

你可能感兴趣的:(apache,数据结构,log4j,servlet,UP)