package com.uas.finance.controller;

import com.uas.finance.model.RepaymentPlan;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.web.servlet.view.document.AbstractExcelView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

/**
 * 创建excel视图类
 * created by shicr on 2018/2/25
 **/
public class ViewExcel extends AbstractExcelView {
    /**
     * Subclasses must implement this method to create an Excel HSSFWorkbook document,
     * given the model.
     *
     * @param model    the model Map
     * @param workbook the Excel workbook to complete
     * @param request  in case we need locale etc. Shouldn't look at attributes.
     * @param response in case we need to set cookies. Shouldn't write to it.
     */
    @Override
    protected void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileName = "还款计划.xls";
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/ms-excel");
        response.setHeader("Content-Disposition", "inline; filename="+new String(fileName.getBytes(),"iso8859-1"));
        OutputStream outputStream = response.getOutputStream();

        List<RepaymentPlan> repaymentPlans = (List<RepaymentPlan>) model.get("repaylist");
        // 产生Excel表头
        HSSFSheet sheet = workbook.createSheet("还款计划表");
        HSSFRow header = sheet.createRow(0);
        // 产生标题列
        header.createCell(0).setCellValue("还款日期");
        header.createCell(1).setCellValue("业务币种");
        header.createCell(2).setCellValue("本期应还本金");
        header.createCell(3).setCellValue("本期应还利息");
        header.createCell(4).setCellValue("经办经理");
        header.createCell(5).setCellValue("是否执行");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        int rowNumber = 1;
        for (RepaymentPlan repaymentPlan : repaymentPlans) {
            HSSFRow row = sheet.createRow(rowNumber++);
            // 产生标题列
            row.createCell(0).setCellValue(sdf.format(repaymentPlan.getRp_backdate()));
            row.createCell(1).setCellValue(repaymentPlan.getRp_currency());
            row.createCell(2).setCellValue(repaymentPlan.getRp_principal());
            row.createCell(3).setCellValue(repaymentPlan.getRp_interest());
            row.createCell(4).setCellValue(repaymentPlan.getRp_truster());
            row.createCell(5).setCellValue(repaymentPlan.getRp_iscloseoff());
        }
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }
}
