package weaver.interfaces.htsc.payment;

import com.weaver.formmodel.util.DateHelper;
import com.weaver.general.BaseBean;
import com.weaver.general.Util;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import weaver.conn.RecordSet;
import weaver.general.GCONST;
import weaver.hrm.resource.ResourceComInfo;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

public class PaymentDetailExport extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        // 第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = workbook.createSheet();
        sheet.setDefaultColumnWidth(15);
        sheet.setDefaultRowHeightInPoints(15);

        //单元格样式
        HSSFCellStyle titleStyle = titleCellStyle(workbook);
        HSSFCellStyle dataStyle = dataCellStyle(workbook);

        String ids = Util.null2String(req.getParameter("ids"));
        List<List<String>> dataList = queryDataList(ids);
        String title[] = {"拟稿部门","付款编号","付款单位","收款单位名称","开户行","银行账户","银行账户金额","所属机构","实际承担部门"};

        //生成表头数据
        HSSFRow row = sheet.createRow(0); //创建第0行  表头
        row.setHeightInPoints(30);// 设置标题行的高度
        for(int i=0;i<title.length;i++){
            HSSFCell cell0 = row.createCell(i);
            cell0.setCellStyle(titleStyle);
            cell0.setCellValue(title[i]);
        }


        //生成数据行
        int rownum = 1;
        for(int i = 0;i < dataList.size(); i ++){
            HSSFRow newRow = sheet.createRow(rownum);
            newRow.setHeightInPoints(30);// 设置数据行的高度
            List<String> dataItem = dataList.get(i);
            for (int j=0;j<dataItem.size();j++) {
                HSSFCell cell = newRow.createCell(j);
                cell.setCellStyle(dataStyle);
                cell.setCellValue(dataItem.get(j));
            }
            rownum++;
        }

        //导出数据
        exportExcel(workbook,res);


    }

    /**
     * 查询需要导出的数据
     * @param ids
     * @return
     */
    public List<List<String>> queryDataList(String ids){
        List<List<String>> dataList = new ArrayList();
        if(!"".equals(ids)){
            RecordSet rs = new RecordSet();
            String sql = " select requtid,fklx from uf_zbfk where id in ("+ids+")  " +
                    "order by instr('"+ids+",', id||',')  ";
            rs.execute(sql);
            while(rs.next()){
                int fklx = rs.getInt("fklx");
                String requestid = Util.null2String(rs.getString("requtid"));
                List<List<String>> detailData = getPayDetailData(requestid,fklx);
                dataList.addAll(detailData);
            }
        }
        return dataList;
    }

    /**
     * 根据requestID和fklx判断具体导出数据
     * @param requestid
     * @param fklx
     * @return
     */
    public List<List<String>> getPayDetailData(String requestid,int fklx){
        List<List<String>> exportDataList = new ArrayList();
        String tablename = getTableName(requestid);
        if(!"".equals(tablename)){
            if(fklx==9){//总部通用报销导出数据单独处理
                exportDataList = getReimbComPayData(requestid,tablename,exportDataList);
            }else if(fklx==10){//总部差旅报销
                exportDataList = getTravelReimbComPayData(requestid,tablename,exportDataList);
            }else if(fklx==3){
                exportDataList = getTravelSettlementData(requestid,tablename,exportDataList);
            }else if (fklx==4){//采购商城结算付款
                exportDataList = getPurchaseMallData(requestid,tablename,exportDataList);
            }else{ //其他通用
                exportDataList = getCommonComPayData(requestid,tablename,exportDataList);
            }


            if(fklx==2){//工会付款需要导出个人明细数据
                exportDataList = getGhPersonalPayData(requestid,tablename,exportDataList);
            }

        }
        return exportDataList;

    }


    /**
     * 查询通用报销公司付款数据
     * @param requestid
     * @param tablename
     * @return
     */
    public List<List<String>> getReimbComPayData(String requestid,String tablename,List<List<String>> exportDataList){
        if(exportDataList!=null){
            try{
                RecordSet rs = new RecordSet();
                String sql = " select szbm,lcbh,'' fkdw,ygxm skdw,khxmc,yxzh,yxzfje,b.szjg,b.fycdbm  " +
                        " from "+tablename+" a,"+tablename+"_dt11 b where a.id=b.mainid and a.requestid=? ";
                rs.executeQuery(sql,requestid);
                String[] columns = rs.getColumnName();
                ResourceComInfo resComInfo = new ResourceComInfo();
                while(rs.next()){
                    List<String> detailData = new ArrayList<String>();
                    for(int i=0;i<columns.length;i++){
                        String columName = columns[i].toLowerCase();
                        String value = Util.null2String(rs.getString(columName));
                        if("szbm".equals(columName) || "szjg".equals(columName) || "fycdbm".equals(columName) ){
                            value = getMultiDeptNames(value);
                        }
                        if("skdw".equals(columName)){
                            value = resComInfo.getLastname(value);
                        }
                        detailData.add(value);
                    }
                    exportDataList.add(detailData);

                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }else {
            exportDataList = new ArrayList();
        }

        return exportDataList;
    }

    /**
     * 查询采购商城结算付款数据
     * @param requestid
     * @param tablename
     * @return
     */
    public List<List<String>> getPurchaseMallData(String requestid,String tablename,List<List<String>> exportDataList){
        if(exportDataList!=null){
            try{
//                明细表8实际承担部门行转列
                RecordSet rs = new RecordSet();
                String sql = "";
                String sjcdbm = "";
                sql = "select wm_concat_old(FYSJCDBM) as sjcdbm  from "+tablename+"_dt8 where mainid = (select id from " +
                        ""+tablename+" where requestid = '"+requestid+"')";
                rs.executeQuery(sql);
                if(rs.next()){
                    sjcdbm = rs.getString("sjcdbm");
                }
                String sjcdbmName =  getMultiDeptNames(sjcdbm);//实际承担部门Name

                sql = "select c.szbm,c.lcbh,'' as fkdw,a.skdw,a.khx,a.yxzh,a.yxzfje,c.szjg " +
                        "from "+tablename+"_dt11 a left join "+tablename+" c on a.mainid = c.id where requestid = '"+requestid+"'";
                rs.executeQuery(sql);
                String[] columns2 = rs.getColumnName();
                while (rs.next()){
                    List<String> detailData = new ArrayList<String>();
                    for (int i = 0; i < columns2.length; i++) {
                        String columName = columns2[i].toLowerCase();
                        String value = Util.null2String(rs.getString(columName));
                        if("szbm".equals(columName)  || "fkdw".equals(columName) || "szjg".equals(columName) ){
                            value = getMultiDeptNames(value);
                        }else if ("yxzh".equals(columName)){
                            value = removenbsp(value);
                        }
                        detailData.add(value);
                    }
                    detailData.add(sjcdbmName);
                    exportDataList.add(detailData);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }else {
            exportDataList = new ArrayList();
        }
        return exportDataList;
    }

    private String removenbsp(String value) {
        return value.replaceAll("&nbsp;"," ");
    }
    /**
     * 查询差旅报销公司付款数据
     * @param requestid
     * @param tablename
     * @return
     */
    public List<List<String>> getTravelReimbComPayData(String requestid,String tablename,List<List<String>> exportDataList){
        if(exportDataList!=null){
            try{
                RecordSet rs = new RecordSet();
                String sql = " select distinct szbm,lcbh,'' fkdw,bxr skdw,khxmc,yxzh,yxzfje,szjg,szbm fycdbm\n" +
                        " from "+tablename+" a,"+tablename+"_dt10 b \n" +
                        " where a.id=b.mainid and a.requestid=? ";
                rs.executeQuery(sql,requestid);
                String[] columns = rs.getColumnName();
                ResourceComInfo resComInfo = new ResourceComInfo();
                while(rs.next()){
                    List<String> detailData = new ArrayList<String>();
                    for(int i=0;i<columns.length;i++){
                        String columName = columns[i].toLowerCase();
                        String value = Util.null2String(rs.getString(columName));
                        if("szbm".equals(columName) || "szjg".equals(columName) || "fycdbm".equals(columName) ){
                            value = getMultiDeptNames(value);
                        }
                        if("skdw".equals(columName)){
                            value = resComInfo.getLastname(value);
                        }
                        detailData.add(value);
                    }
                    exportDataList.add(detailData);

                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }else {
            exportDataList = new ArrayList();
        }

        return exportDataList;
    }


    /**
     * 查询通用的公司付款数据
     * @param requestid
     * @param tablename
     * @return
     */
    public List<List<String>> getCommonComPayData(String requestid,String tablename,List<List<String>> exportDataList){
        if(exportDataList!=null){
            RecordSet rs = new RecordSet();
            String sql1 = " select szbm,lcbh,'' fkdw,skdw,khxmc,yxzh,yxzfje,b.szjg,b.fycdbm  " +
                    " from "+tablename+" a,"+tablename+"_dt11 b where a.id=b.mainid and a.requestid=? ";
            rs.executeQuery(sql1,requestid);
            String[] columns = rs.getColumnName();
            while(rs.next()){
                List<String> detailData = new ArrayList<String>();
                for(int i=0;i<columns.length;i++){
                    String columName = columns[i].toLowerCase();
                    String value = Util.null2String(rs.getString(columName));
                    if("szbm".equals(columName) || "szjg".equals(columName) || "fycdbm".equals(columName) ){
                        value = getMultiDeptNames(value);
                    }
                    detailData.add(value);
                }
                exportDataList.add(detailData);

            }

        }else {
            exportDataList = new ArrayList();
        }

        return exportDataList;
    }


    /**
     * 查询工会个人付款数据
     * @param requestid
     * @param tablename
     * @return
     */
    public List<List<String>> getGhPersonalPayData(String requestid,String tablename,List<List<String>> exportDataList){
        if(exportDataList!=null){
            try {

                RecordSet rs = new RecordSet();
                String sql2 = " select szbm,lcbh,'' fkdw,ygxm skdw,khxmc,yxzh,yxzfje,b.szjg,b.fycdbm \n" +
                        "from "+tablename+" a,"+tablename+"_dt13 b \n" +
                        "where a.id=b.mainid and a.requestid=? ";
                rs.executeQuery(sql2,requestid);
                String[] columns2 = rs.getColumnName();
                ResourceComInfo resComInfo = new ResourceComInfo();
                while(rs.next()){
                    List<String> detailData = new ArrayList<String>();
                    for(int i=0;i<columns2.length;i++){
                        String columName = columns2[i].toLowerCase();
                        String value = Util.null2String(rs.getString(columName));
                        if("szbm".equals(columName) || "szjg".equals(columName) || "fycdbm".equals(columName) ){
                            value = getMultiDeptNames(value);
                        }
                        if("skdw".equals(columName)){
                            value = resComInfo.getLastname(value);
                        }
                        detailData.add(value);
                    }
                    exportDataList.add(detailData);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }else{
            exportDataList = new ArrayList();
        }


        return exportDataList;
    }

    /**
     * 查询商旅结算付款数据
     * @param requestid
     * @param tablename
     * @return
     */
    public List<List<String>> getTravelSettlementData(String requestid,String tablename,List<List<String>> exportDataList){
        if(exportDataList!=null){
            try {

                RecordSet rs = new RecordSet();
                String sql2 = "  select distinct szbm,lcbh,'' fkdw,skdw,khxmc,yxzh,b.yxzfje,'华泰证券股份有限公司' szjg,c.fysjcdbm fycdbm \n" +
                        "   from  "+tablename+" a, "+tablename+"_dt11 b,\n" +
                        "   ( select  mainid, wm_concat_old(distinct fysjcdbm) fysjcdbm \n" +
                        "   from "+tablename+" t1,"+tablename+"_dt12 t2 \n" +
                        "   where t1.id=t2.mainid and t1.requestid=? group by mainid) c\n" +
                        "   where a.id=b.mainid and a.id=c.mainid  and requestid=? ";
                rs.executeQuery(sql2,new Object[]{requestid,requestid});
                String[] columns2 = rs.getColumnName();
                ResourceComInfo resComInfo = new ResourceComInfo();
                while(rs.next()){
                    List<String> detailData = new ArrayList<String>();
                    for(int i=0;i<columns2.length;i++){
                        String columName = columns2[i].toLowerCase();
                        String value = Util.null2String(rs.getString(columName));
                        if("szbm".equals(columName)  || "fycdbm".equals(columName) ){
                            value = getMultiDeptNames(value);
                        }
                        detailData.add(value);
                    }
                    exportDataList.add(detailData);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }else{
            exportDataList = new ArrayList();
        }


        return exportDataList;
    }


    /**
     * 根据requestid查询表名
     * @param requestid
     * @return
     */
    public String getTableName(String requestid){
        String tablename = "";
        String sql = " select tablename from workflow_base a,workflow_bill b,workflow_requestbase c \n" +
                " where a.formid=b.id and a.id=c.workflowid and c.requestid=? ";
        RecordSet rs = new RecordSet();
        rs.executeQuery(sql,requestid);
        if(rs.next()){
            tablename = Util.null2String(rs.getString("tablename"));
        }
        return tablename;
    }







    /**
     * 查询多部门部门名称
     * @param deptid
     * @return
     */
    public String getMultiDeptNames(String deptid){
        String deptnames = "";
        if(!"".equals(deptid)){
            RecordSet rs = new RecordSet();
            rs.execute(" select departmentname from hrmdepartment where id in("+deptid+") ");
            while(rs.next()){
                deptnames += Util.null2String(rs.getString("departmentname"))+",";
            }
            if(!"".equals(deptnames)){
                deptnames = deptnames.substring(0,deptnames.length()-1);
            }
        }
        return deptnames;
    }


    /**
     * 导出Excel输出到浏览器
     * @param workbook
     * @param response
     */
    public void exportExcel(Workbook workbook,HttpServletResponse response){
        ServletOutputStream out = null;
        try {
            String fileName = "支付明细数据"+DateHelper.getCurrentDate()+"-"+System.currentTimeMillis();
            fileName = URLEncoder.encode(fileName, "UTF8");
            response.setContentType("application/vnd.ms-excel;chartset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
            out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        }catch (Exception e){
            new BaseBean().writeLog("付款支付明细导出出错：",e);
        }finally {
            try {
                if(out!=null){
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }


    public void initCell(HSSFCellStyle style, HSSFRow row, String name, int i){
        HSSFCell cell = row.createCell((short) i);
        cell.setCellValue(name);
        cell.setCellStyle(style);
    }


    /**
     * 设置单元格样式
     * @return
     */
    public HSSFCellStyle dataCellStyle(HSSFWorkbook wb){
        HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setWrapText(true);// 设置自动换行
        cellStyle.setAlignment(HorizontalAlignment.CENTER);    //HSSFCellStyle.ALIGN_CENTER
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // HSSFCellStyle.VERTICAL_CENTER // 创建一个居中格式
        cellStyle.setBorderBottom(BorderStyle.THIN); // HSSFCellStyle.BORDER_THIN
        cellStyle.setBorderLeft(BorderStyle.THIN);
        cellStyle.setBorderRight(BorderStyle.THIN);
        cellStyle.setBorderTop(BorderStyle.THIN);
        HSSFFont headerFont1 = (HSSFFont) wb.createFont(); // 创建字体样式
        headerFont1.setFontName("宋体"); // 设置字体类型
        headerFont1.setFontHeightInPoints((short) 12); // 设置字体大小
        cellStyle.setFont(headerFont1); // 为标题样式设置字体样式
        return cellStyle;

    }


    // 标题第一行样式
    public HSSFCellStyle titleCellStyle(HSSFWorkbook wb) {
        HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyle.setBorderBottom(BorderStyle.THIN); // HSSFCellStyle.BORDER_THIN
        cellStyle.setBorderLeft(BorderStyle.THIN);
        cellStyle.setBorderRight(BorderStyle.THIN);
        cellStyle.setBorderTop(BorderStyle.THIN);
        HSSFFont headerFont = (HSSFFont) wb.createFont(); // 创建字体样式
        headerFont.setFontName("宋体"); // 设置字体类型
        headerFont.setFontHeightInPoints((short) 12); // 设置字体大小
        cellStyle.setFont(headerFont); // 为标题样式设置字体样式
        return cellStyle;
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        this.doGet(req,res);
    }


    public static void main(String[] args) {
        GCONST.setRootPath("WEB-INF/");
        GCONST.setServerName("ecology");

    }



}
