package weaver.interfaces.htsc.subcompayment;

import com.alibaba.fastjson.JSONObject;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SubcomPaymentDetailExport 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_zgsfk 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==0 || fklx==1 || fklx==2 ){//子公司通用报销
                exportDataList = getSubcomCommonReimData(fklx,requestid,tablename,exportDataList);
            }

            if(fklx==3 ){//资管差旅报销
                exportDataList = getSubcomTravelReimbPayData(requestid,tablename,exportDataList);
            }

            if (fklx==4){//紫金差旅报销
                new BaseBean().writeLog("勾选的流程为资金差旅报销流程，准备执行导入Excel方法");
                exportDataList = getPurpleGoldTravelReimbPayData(requestid,tablename,exportDataList);
            }

            if (fklx==5){//子公司差旅报销
                exportDataList = getSonCompanyTravelReimbPayData(requestid,tablename,exportDataList);
            }
            //资管通用付款、紫金通用付款
            if (fklx==6 || fklx==7){
                exportDataList = getGeneralpaymentData(requestid,tablename,exportDataList,fklx);
            }
        }
        return exportDataList;

    }


    /**
     * 通用付款Excel导出
     * @param requestid
     * @param tablename
     * @return exportDataList
     */
    public List<List<String>> getGeneralpaymentData(String requestid,String tablename,List<List<String>> exportDataList,int fklx){

        BaseBean bb = new BaseBean();
        bb.writeLog("=======================================================");
        if (exportDataList != null) {
            try {
                //获取主表和明细表11相关字段
                RecordSet rs = new RecordSet();
                String sql = "select a.szbm,a.lcbh as fkbh,'' as fkdw,b.skdw,b.khx,b.yxzh,b.yxzfje,b.szjg,b.fycdbm  from ("+tablename+" a join "+tablename+"_dt11 b on a.id = b.mainid) where requestid = '"+requestid+"'";
                bb.writeLog("即将执行的sql是："+sql);
                rs.executeQuery(sql);
                String[] columns = rs.getColumnName();
                while (rs.next()) {
                    List<String> oneRow = new ArrayList<String>();
                    for (String column : columns) {
                        if ("szbm".equals(column.toLowerCase()) || "szjg".equals(column.toLowerCase()) ||
                                "fycdbm".equals(column.toLowerCase())){
                            if(fklx == 7 && "fycdbm".equals(column.toLowerCase())){
                                oneRow.add(anotherGetMultiDeptNames(weaver.general.Util.null2String(rs.getString(column.toLowerCase()))));
                            }else {
                                oneRow.add(getMultiDeptNames(weaver.general.Util.null2String(rs.getString(column.toLowerCase()))));
                            }
                        }else if ("khx".equals(column.toLowerCase())){
                            oneRow.add(getkhxName(weaver.general.Util.null2String(rs.getString(column.toLowerCase()))));
                        }else {
                            oneRow.add(weaver.general.Util.null2String(rs.getString(column.toLowerCase())));
                        }
                    }
                    exportDataList.add(oneRow);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            exportDataList = new ArrayList();
        }

        return exportDataList;
    }

    /**
     * 查询子公司通用付款数据
     * @param requestid
     * @param tablename
     * @return
     */
    public List<List<String>> getSubcomCommonPayData(String requestid,String tablename,List<List<String>> exportDataList){
        if(exportDataList!=null){
            try{
                RecordSet rs = new RecordSet();
                String sql = " 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(sql,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);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }else {
            exportDataList = new ArrayList();
        }

        return exportDataList;
    }

    /**
     * 查询子公司差旅报销公司付款数据
     * @param requestid
     * @param tablename
     * @return
     */
    public List<List<String>> getSubcomTravelReimbPayData(String requestid,String tablename,List<List<String>> exportDataList){
        if(exportDataList!=null){
            try{
                RecordSet rs = new RecordSet();
                String sql = " select szbm,lcbh,'' fkdw,ccr skdw,khxmc,yxzh,yxzfje,b.szjg,b.bm 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 exportDataList
     */
    public List<List<String>> getPurpleGoldTravelReimbPayData(String requestid,String tablename,List<List<String>> exportDataList){

        BaseBean bb = new BaseBean();
        bb.writeLog("=======================================================");
        if (exportDataList != null) {
            try {
                //获取对应流程的费用承担部门的List集合
                List<String> fycdbm = getFycdbm(requestid, tablename);
                bb.writeLog("获取的费用承担部门集合是："+fycdbm);
                //获取主表和明细表10相关字段
                RecordSet rs = new RecordSet();
                String sql = "select szbm,lcbh,'' as fkdw,ccr,khx,yxzh,yxzfje,a.szjg from ("+tablename+" a join "+tablename+"_dt10 b on a.id = b.mainid) where requestid = '"+requestid+"'";
                bb.writeLog("即将执行的sql是："+sql);
                rs.executeQuery(sql);
                String[] columns = rs.getColumnName();
                int guide = 0;
                while (rs.next()) {
                    List<String> oneRow = new ArrayList<String>();
                    for (String column : columns) {
                        if ("szbm".equals(column.toLowerCase()) || "szjg".equals(column.toLowerCase())){
                            oneRow.add(getMultiDeptNames(weaver.general.Util.null2String(rs.getString(column.toLowerCase()))));
                        }else if ("ccr".equals(column.toLowerCase())){
                            oneRow.add(getLastname(weaver.general.Util.null2String(rs.getString(column.toLowerCase()))));
                        }else if ("khx".equals(column.toLowerCase())){
                            oneRow.add(getkhxName(weaver.general.Util.null2String(rs.getString(column.toLowerCase()))));
                        }else {
                            oneRow.add(weaver.general.Util.null2String(rs.getString(column.toLowerCase())));
                        }
                    }
                    oneRow.add(getFycdbm(fycdbm.get(guide)));
                    guide+=1;
                    exportDataList.add(oneRow);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            exportDataList = new ArrayList();
        }

        return exportDataList;
    }

    /**
     * 查询子公司差旅报销公司付款数据
     * @param requestid
     * @param tablename
     * @return
     */
    public List<List<String>> getSonCompanyTravelReimbPayData(String requestid,String tablename,List<List<String>> exportDataList){
        if(exportDataList!=null){
            try{
                BaseBean bb = new BaseBean();
                bb.writeLog("搜索子公司差旅报销Excel所需数据");
                ResourceComInfo resComInfo = new ResourceComInfo();
                Map<String, String> dt9Data = getDtData(tablename, requestid);
                bb.writeLog("获取的对应明细表9数据时："+ JSONObject.toJSONString(dt9Data));
                RecordSet rs = new RecordSet();
                String sql = "select szbm,lcbh,'' as fkdw,ccr,khxmc,yxzh,yxzfje,b.szjg from "+tablename+"_dt10 a join "+tablename+" b on a.mainid = b.id where requestid = '"+requestid+"'";
                rs.executeQuery(sql);
                while (rs.next()){
                    List<String> oneRow = new ArrayList<>();
                    String[] columnNames = rs.getColumnName();
                    for (String columnName : columnNames) {
                        if ("szbm".equals(columnName.toLowerCase()) || "szjg".equals(columnName.toLowerCase())){
                            oneRow.add(getMultiDeptNames(rs.getString(columnName.toLowerCase())));
                        }else if ("ccr".equals(columnName.toLowerCase())){
                            oneRow.add(resComInfo.getLastname(rs.getString(columnName.toLowerCase())));
                        }
                        else {
                            oneRow.add(rs.getString(columnName.toLowerCase()));
                        }

                    }
                    oneRow.add(dt9Data.get(rs.getString("ccr"))==null? "" :dt9Data.get(rs.getString("ccr")));
                    exportDataList.add(oneRow);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }else {
            exportDataList = new ArrayList();
        }

        return exportDataList;
    }

    /**
     * 查询子公司通用报销数据
     * @param requestid
     * @param tablename
     * @return
     */
    public List<List<String>> getSubcomCommonReimData(int fklx,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=? ";
                if(fklx==1){
                    sql = " select szbm,lcbh,b.fycdbm fkdw,ygxm skdw,khxmc,yxzh,yxzfje,b.szjg,b.bm 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("fkdw".equals(columName) && fklx==1){
                            value = getZjDeptName(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;
    }




    /**
     * 根据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 deptcode
     * @return
     */
    public String getZjDeptName(String deptcode){
        String deptname = "";
        if(!"".equals(deptcode)){
            RecordSet rs = new RecordSet();
            rs.executeQuery("  select bmmc from uf_zjbmb where bmbh=? ",deptcode);
            if(rs.next()){
                deptname = Util.null2String(rs.getString("bmmc"));
            }
        }
        return deptname;
    }




    /**
     * 查询多部门部门名称
     * @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+") ");
            if(rs.getCounts() == 0){
                rs.execute(" select departmentname from hrmdepartment where departmentcode in("+deptid+") ");
            }
            while(rs.next()){
                deptnames += Util.null2String(rs.getString("departmentname"))+",";
            }
            if(!"".equals(deptnames)){
                deptnames = deptnames.substring(0,deptnames.length()-1);
            }
        }
        return deptnames;
    }

    /**
     * 紫金通用查询多部门部门名称
     * @param deptid
     * @return
     */
    public String anotherGetMultiDeptNames(String deptid){
        String deptnames = "";
        if(!"".equals(deptid)){

            String[] deptids = deptid.split(",");
            String values = "";
            for (String value:deptids){
                values = values+"'"+value +"'" + ",";
            }
            values = values.substring(0,values.length()-1);
            RecordSet rs = new RecordSet();
            rs.execute(" select departmentname from hrmdepartment where departmentcode in("+values+") ");
            while(rs.next()){
                deptnames += Util.null2String(rs.getString("departmentname"))+",";
            }
            if(!"".equals(deptnames)){
                deptnames = deptnames.substring(0,deptnames.length()-1);
            }
        }
        return deptnames;
    }

    public String getLastname(String id){
        weaver.general.BaseBean bb = new weaver.general.BaseBean();
        RecordSet rs = new RecordSet();
        rs.executeQuery("select lastname from hrmresource where id = '"+id+"'");
        if (rs.next()){
            return rs.getString("lastname");
        }else {
            return "";
        }
    }

    public String getkhxName(String id){
        weaver.general.BaseBean bb = new weaver.general.BaseBean();
        bb.writeLog("进入根据id获取开户行名称");
        RecordSet rs = new RecordSet();
        rs.executeQuery("select yxmc from uf_khh where lxh = '"+id+"'");
        String yxmc = "";
        if (rs.next()){
            yxmc =  rs.getString("yxmc");
        }
        bb.writeLog("获取的名称是："+yxmc);
        return yxmc;
    }

    public  Map<String,String> getDtData(String tablename,String requestid){
        Map<String,String> data = new HashMap<>();
        RecordSet rs = new RecordSet();
        String sql = "select ccr,fycdbm from "+tablename+"_dt9 where mainid = (select id from "+tablename+" where requestid = '"+requestid+"')";
        rs.executeQuery(sql);
        List<String> keys = new ArrayList<>();
        while (rs.next()){
            String ccr = rs.getString("ccr");
            String fycdbm = getMultiDeptNames(rs.getString("fycdbm"));
            if (keys.contains(ccr)){
                String old = data.get(ccr);
                data.put(ccr,old+","+fycdbm);
            }else {
                keys.add(ccr);
                data.put(ccr,fycdbm);
            }
        }
        return data;
    }

    public List<String> getFycdbm(String requestId, String tablename) {
        List<String> fycdbm = new ArrayList<>();
        weaver.general.BaseBean bb = new weaver.general.BaseBean();
        bb.writeLog("进入根据requestid获取流程费用承担部门");
        RecordSet rs = new RecordSet();
        String sql = "select fycdbm from " + tablename + " a  join " + tablename + "_dt9 b on a.id = b.mainid where requestid = '" + requestId + "'";
        bb.writeLog("即将执行的获取费用承担部门代码是：" + sql);
        rs.executeQuery(sql);
        while (rs.next()) {
            fycdbm.add(weaver.general.Util.null2String(rs.getString("fycdbm")));
        }
        bb.writeLog("结果是：" + JSONObject.toJSONString(fycdbm));
        return fycdbm;
    }

    public String getFycdbm(String param){
//        select bmmc from uf_zjbmb where BMBH = 'ZZ001051'
        weaver.general.BaseBean bb = new weaver.general.BaseBean();
        bb.writeLog("进入根据id获取费用承担部门");
        RecordSet rs = new RecordSet();
        rs.executeQuery("select bmmc from uf_zjbmb where BMBH = '"+param+"'");
        String yxmc = "";
        if (rs.next()){
            yxmc =  rs.getString("bmmc");
        }
        bb.writeLog("获取的名称是："+yxmc);
        return yxmc;
    }


    /**
     * 导出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) {
        SubcomPaymentDetailExport subcomPaymentDetailExport = new SubcomPaymentDetailExport();
        subcomPaymentDetailExport.anotherGetMultiDeptNames("ZSDASD,Z234234");

    }



}
