package com.cftech.brand.util;

import java.io.File;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cftech.brand.apply.detail.model.BrandApplyDetailVo;
import com.cftech.brand.apply.model.BrandApply;
import com.cftech.brand.apply.model.BrandApplyVo;
import com.cftech.common.promotionstock.model.GrantDetailDto;
import com.cftech.core.util.DateFormatUtils;
import com.cftech.core.util.DateUtils;
import com.cftech.core.util.StringUtils;
import com.cftech.core.util.SystemConfig;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.DefaultResourceLoader;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 品牌申请导出
 * @author faye
 * @date 2020-2-10
 */

public class BrandExportUtil {

    /**
     * @Title: fmtMicrometer
     * @Description: 格式化数字为千分位
     * @param text
     * @return    设定文件
     * @return String    返回类型
     */
    public static String fmtMicrometer(String text) {
        DecimalFormat df = new DecimalFormat(",###");

        double number = 0.0;
        try {
            number = Double.parseDouble(text);
        } catch (Exception e) {
            number = 0.0;
        }
        return df.format(number);
    }
    /*public static String fmtMicrometer(String text) {
        DecimalFormat df = null;
        if (text.indexOf(".") > 0) {
            if (text.length() - text.indexOf(".") - 1 == 0) {
                df = new DecimalFormat("###,##0.");
            } else if (text.length() - text.indexOf(".") - 1 == 1) {
                df = new DecimalFormat("###,##0.0");
            } else {
                df = new DecimalFormat("###,##0.00");
            }
        } else {
            df = new DecimalFormat("###,##0");
        }
        double number = 0.0;
        try {
            number = Double.parseDouble(text);
        } catch (Exception e) {
            number = 0.0;
        }
        return df.format(number);
    }*/
    /**
     * 导出统计报表
     * @param fileName
     * @param datas
     * @param beginTime
     * @param endTime
     * @param response
     */
    public static void exportStatistical(String fileName,List<BrandApplyVo> datas,String beginTime,String endTime, HttpServletResponse response){
        try {
            String title=beginTime+"至"+endTime+"品牌申请统计";
            String basePath= SystemConfig.p.getProperty("docXmlTemplatePath");
            XSSFWorkbook  wb =new XSSFWorkbook(new FileInputStream(basePath+"brandApplyStatisticsTemplate.xlsx"));
//            XSSFWorkbook wb =new XSSFWorkbook(new FileInputStream("E:\\文档\\信睿\\舍弗勒\\2020\\品牌申请\\brandApplyStatisticsTemplate.xlsx"));

            //按照部门统计
            Sheet depSheet=wb.getSheetAt(0);
            Map<String, List<BrandApplyVo>> depMap =
                    datas.stream().collect(Collectors.groupingBy(BrandApplyVo::getDepartmentName));
            handleSheetDataByDC(title,"月度申请总统计（所有）",datas,depMap,depSheet);

            //按照类别统计
            Sheet categorySheet=wb.getSheetAt(1);
            Map<String, List<BrandApplyVo>> categoryMap =
                    datas.stream().collect(Collectors.groupingBy(BrandApplyVo::getCategoryName));
            handleSheetDataByDC(title,"月度领用总统计（所有）",datas,categoryMap,categorySheet);

            //按照设计人员统计
            Sheet designerSheet=wb.getSheetAt(2);
            designerSheet.getRow(0).getCell(0).setCellValue(title);
            handleSheetDataByDesigner(title,datas,designerSheet);

            //按照供应商统计
            Sheet supplierSheet=wb.getSheetAt(3);
            supplierSheet.getRow(0).getCell(0).setCellValue(title);
            handleSheetDataBySupplier(title,datas,supplierSheet);


            //关闭订单数量
            Sheet closeOrderSheet=wb.getSheetAt(4);
            closeOrderSheet.getRow(0).getCell(0).setCellValue(title);
            handleCloseCountSheet(datas,closeOrderSheet);

            //输出到客户端进行下载
            OutputStream outputStream = response.getOutputStream();
            response.reset();
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8")  + ".xls");
            //定义下载的类型，标明是excel文件
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            //这时候把创建好的excel写入到输出流
            wb.write(outputStream);
            //养成好习惯，出门记得随手关门
            outputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    public static Boolean isOnTime(Date actualDeliveryDate,Date intendedDeliveryDate){
        actualDeliveryDate=DateUtils.parseDate(DateUtils.formatDate(actualDeliveryDate,"yyyy-MM-dd"));
        if(actualDeliveryDate.compareTo(intendedDeliveryDate)<=0){
           return true;
        }
        return false;
    }
    /**
     * 按照供应商统计
     * @param datas
     * @param sheet
     */
    public static void handleSheetDataBySupplier(String title,List<BrandApplyVo> datas,Sheet sheet){
        sheet.getRow(0).getCell(0).setCellValue(title);
        List<BrandApplyVo> supplierDatas=new ArrayList<BrandApplyVo>();
        int evaluateCount=0;
        BigDecimal evaluateSum=new BigDecimal(0);
        int onTimeCount=0;
        int completedCount=0;
        BigDecimal totalCost=new BigDecimal(0);
        for(BrandApplyVo data:datas){
            if(data.getSupplierId()!=null){
                supplierDatas.add(data);
                //已完成订单数量
                if(StringUtils.equals("5",data.getStatus())){
                    totalCost= totalCost.add(new BigDecimal(data.getOuterCost())).setScale(2,BigDecimal.ROUND_HALF_UP);
                    if(StringUtils.isNotBlank(data.getMakeQuanlityScore())){
                        evaluateCount++;
                        evaluateSum=evaluateSum.add(new BigDecimal(data.getMakeQuanlityScore())).setScale(2,BigDecimal.ROUND_HALF_UP);
                    }
                    completedCount++;
                    if(isOnTime(data.getActualDeliveryDate(),data.getIntendedDeliveryDate())){
                        onTimeCount++;
                    }
                }
            }
        }
        String onTimeRateStr= getOnTimeRate(onTimeCount,completedCount);

        String evaluateAvg=" ";
        if(evaluateCount!=0){
            evaluateAvg =evaluateSum.divide(new BigDecimal(evaluateCount),2,BigDecimal.ROUND_HALF_UP).toString();

        }
        int totalCount=supplierDatas.size();
        Row totalRow=sheet.createRow(3);
        totalRow.createCell(0).setCellValue("月度制作统计");
        totalRow.createCell(1).setCellValue(totalCount);
        totalRow.createCell(2).setCellValue(fmtMicrometer(totalCost.toString()));
        totalRow.createCell(3).setCellValue(onTimeRateStr);
        totalRow.createCell(4).setCellValue(evaluateAvg);

        Map<String, List<BrandApplyVo>> designerMap =
                supplierDatas.stream().collect(Collectors.groupingBy(BrandApplyVo::getSupplierName));
        Set<String> keys = designerMap.keySet();
        int index=4;
        for(String key:keys){
            List<BrandApplyVo> brandApplyVoList=designerMap.get(key);
            int totalCountD=brandApplyVoList.size();
            int evaluateCountD=0;
            BigDecimal evaluateSumD=new BigDecimal(0);
            BigDecimal totalCostD=new BigDecimal(0);
            int completedCountD=0;
            int onTimeCountD=0;
            for(BrandApplyVo obj:brandApplyVoList){
                //已完成订单数量
                if(StringUtils.equals("5",obj.getStatus())){
                    totalCostD= totalCostD.add(new BigDecimal(obj.getOuterCost())).setScale(2,BigDecimal.ROUND_HALF_UP);
                    if(StringUtils.isNotBlank(obj.getMakeQuanlityScore())){
                        evaluateCountD++;
                        evaluateSumD=evaluateSumD.add(new BigDecimal(obj.getMakeQuanlityScore())).setScale(2,BigDecimal.ROUND_HALF_UP);
                    }
                    completedCountD++;
                    if(isOnTime(obj.getActualDeliveryDate(),obj.getIntendedDeliveryDate())){
                        onTimeCountD++;
                    }
                }
            }
            String onTimeRateDStr=getOnTimeRate(onTimeCountD,completedCountD);
            String evaluateAvgD=" ";
            if(evaluateCountD!=0){
                evaluateAvgD =evaluateSumD.divide(new BigDecimal(evaluateCountD),2,BigDecimal.ROUND_HALF_UP).toString();

            }
            Row row=sheet.createRow(index);
            row.createCell(0).setCellValue(key);
            row.createCell(1).setCellValue(totalCountD);
            row.createCell(2).setCellValue(fmtMicrometer(totalCostD.toString()));
            row.createCell(3).setCellValue(onTimeRateDStr);
            row.createCell(4).setCellValue(evaluateAvgD);
            index++;
        }
    }

    /**
     * 按照设计人员统计
     * @param datas
     * @param sheet
     */
    public static void handleSheetDataByDesigner(String title,List<BrandApplyVo> datas,Sheet sheet){
        sheet.getRow(0).getCell(0).setCellValue(title);
        List<BrandApplyVo> designerDatas=new ArrayList<BrandApplyVo>();
        BigDecimal totalManHour=new BigDecimal(0);
        BigDecimal totalHourlyRate=new BigDecimal(0);
        int evaluateCount=0;
        BigDecimal evaluateSum=new BigDecimal(0);
        int onTimeCount=0;
        int completedCount=0;
        BigDecimal totalCost=new BigDecimal(0);
        for(BrandApplyVo data:datas){
            if(data.getEmpId()!=null){
                designerDatas.add(data);
                //已完成订单数量
                if(StringUtils.equals("5",data.getStatus())){
                    completedCount++;
                    totalManHour= totalManHour.add(new BigDecimal(data.getManHour())).setScale(2,BigDecimal.ROUND_HALF_UP);;
                    totalHourlyRate=totalHourlyRate.add(new BigDecimal(data.getHourlyRate())).setScale(2,BigDecimal.ROUND_HALF_UP);;
                    totalCost= totalCost.add(new BigDecimal(data.getInnerCost())).multiply(new BigDecimal(data.getHourlyRate())).setScale(2,BigDecimal.ROUND_HALF_UP);
                    if(StringUtils.isNotBlank(data.getDesignQuanlityScore())){
                        evaluateCount++;
                        evaluateSum=evaluateSum.add(new BigDecimal(data.getDesignQuanlityScore())).setScale(2,BigDecimal.ROUND_HALF_UP);
                    }
                    if(isOnTime(data.getActualDeliveryDate(),data.getIntendedDeliveryDate())){
                        onTimeCount++;
                    }
                }
            }
        }
        int totalCount=designerDatas.size();
        String hourlyRateAvgStr="";
        if(totalCount!=0){
            BigDecimal hourlyRateAvg=totalHourlyRate.divide(new BigDecimal(totalCount),2,BigDecimal.ROUND_HALF_UP);
            hourlyRateAvgStr=hourlyRateAvg.toString();
        }
        String evaluateAvg="";
        if(evaluateCount!=0){
            evaluateAvg= evaluateSum.divide(new BigDecimal(evaluateCount),2,BigDecimal.ROUND_HALF_UP).toString();
        }
        String onTimeRateStr=getOnTimeRate(onTimeCount,completedCount);
        Row totalRow=sheet.createRow(3);
        totalRow.createCell(0).setCellValue("月度设计统计");
        totalRow.createCell(1).setCellValue(totalCount);
        totalRow.createCell(2).setCellValue(totalManHour.toString());
        totalRow.createCell(3).setCellValue(hourlyRateAvgStr);
        totalRow.createCell(4).setCellValue(totalCost.toString());
        totalRow.createCell(5).setCellValue(onTimeRateStr);
        totalRow.createCell(6).setCellValue(evaluateAvg);

        Map<String, List<BrandApplyVo>> designerMap =
                designerDatas.stream().collect(Collectors.groupingBy(BrandApplyVo::getEmpName));
        Set<String> keys = designerMap.keySet();
        int index=4;
        for(String key:keys){
            List<BrandApplyVo> brandApplyVoList=designerMap.get(key);
            int totalCountD=brandApplyVoList.size();
            BigDecimal totalManHourD=new BigDecimal(0);
            BigDecimal totalHourlyRateD=new BigDecimal(0);
            int evaluateCountD=0;
            BigDecimal evaluateSumD=new BigDecimal(0);
            int onTimeCountD=0;
            int completedCountD=0;
            BigDecimal totalCostD=new BigDecimal(0);
            for(BrandApplyVo obj:brandApplyVoList){
                //已完成订单数量
                if(StringUtils.equals("5",obj.getStatus())){
                    BigDecimal hourlyRate=new BigDecimal(obj.getHourlyRate());
                    totalManHourD=totalManHourD.add(new BigDecimal(obj.getManHour())).setScale(2,BigDecimal.ROUND_HALF_UP);
                    totalHourlyRateD= totalHourlyRateD.add(hourlyRate).setScale(2,BigDecimal.ROUND_HALF_UP);
                    totalCostD= totalCostD.add(new BigDecimal(obj.getInnerCost())).multiply(hourlyRate).setScale(2,BigDecimal.ROUND_HALF_UP);
                    if(StringUtils.isNotBlank(obj.getDesignQuanlityScore())){
                        evaluateCountD++;
                        evaluateSumD=evaluateSumD.add(new BigDecimal(obj.getDesignQuanlityScore())).setScale(2,BigDecimal.ROUND_HALF_UP);
                    }
                    completedCountD++;
                    if(isOnTime(obj.getActualDeliveryDate(),obj.getIntendedDeliveryDate())){
                        onTimeCountD++;
                    }
                }
            }
            String onTimeRateDStr=getOnTimeRate(onTimeCountD,completedCountD);
            BigDecimal hourlyRateAvgD=totalHourlyRateD.divide(new BigDecimal(totalCountD),2,BigDecimal.ROUND_HALF_UP);
            String evaluateAvgD=" ";
            if(evaluateCountD!=0){
                evaluateAvgD =evaluateSumD.divide(new BigDecimal(evaluateCountD),2,BigDecimal.ROUND_HALF_UP).toString();

            }
            Row row=sheet.createRow(index);
            row.createCell(0).setCellValue(key);
            row.createCell(1).setCellValue(totalCountD);
            row.createCell(2).setCellValue(totalManHourD.toString());
            row.createCell(3).setCellValue(hourlyRateAvgD.toString());
            row.createCell(4).setCellValue(totalCostD.toString());
            row.createCell(5).setCellValue(onTimeRateDStr);
            row.createCell(6).setCellValue(evaluateAvgD);
            index++;
        }
    }

    /**
     * 按照部门统计
     * @param datas
     * @param sheet
     */
    public static void handleSheetDataByDC(String title,String firstName,List<BrandApplyVo> datas, Map<String, List<BrandApplyVo>> map,Sheet sheet){
        sheet.getRow(0).getCell(0).setCellValue(title);
        JSONArray dataArray=new JSONArray();
        JSONObject firstData=getRowDataByDC(datas);
        firstData.put("name",firstName);
        dataArray.add(firstData);
        Set<String> keys = map.keySet();
        for(String key:keys){
            List<BrandApplyVo> brandApplyVoList=map.get(key);
            JSONObject dataObj=getRowDataByDC(brandApplyVoList);
            dataObj.put("name",key);
            dataArray.add(dataObj);
        }
        int index=3;
        for(int i=0,j=dataArray.size();i<j;i++){
            Row row=sheet.createRow(index);
            JSONObject obj=dataArray.getJSONObject(i);
            row.createCell(0).setCellValue(obj.getString("name"));
            row.createCell(1).setCellValue(obj.getIntValue("count"));
            row.createCell(2).setCellValue(obj.getString("innerCost"));
            row.createCell(3).setCellValue(obj.getString("outerCost"));
            row.createCell(4).setCellValue(obj.getString("totalCost"));
            row.createCell(5).setCellValue(obj.getString("onTimeRate"));
            row.createCell(6).setCellValue(obj.getString("serviceScoreAvg"));
            index++;
        }
    }

    //计算总统计
    private  static JSONObject getRowDataByDC(List<BrandApplyVo> datas){
        BigDecimal totalInnerCost=new BigDecimal(0);
        BigDecimal totalOuterCost=new BigDecimal(0);
        BigDecimal totalCost;

        int evaluateCount=0;
        BigDecimal evaluateSum=new BigDecimal(0);

        int onTimeCount=0;
        int completedCount=0;
        //月度总统计
        JSONObject obj=new JSONObject();
        for(BrandApplyVo data:datas){
            //已完成订单数量
            if(StringUtils.equals("5",data.getStatus())){
                if(data.getInnerCost()!=null){
                    totalInnerCost= totalInnerCost.add(new BigDecimal(data.getInnerCost()).multiply(new BigDecimal(data.getHourlyRate()).setScale(2,BigDecimal.ROUND_HALF_UP)));
                }
                if(data.getOuterCost()!=null){
                    totalOuterCost=totalOuterCost.add(new BigDecimal(data.getOuterCost())).setScale(2,BigDecimal.ROUND_HALF_UP);
                }
                if(StringUtils.isNotBlank(data.getServiceScore())){
                    evaluateCount++;
                    evaluateSum=evaluateSum.add(new BigDecimal(data.getServiceScore())).setScale(2,BigDecimal.ROUND_HALF_UP);
                }
                completedCount++;
                if(isOnTime(data.getActualDeliveryDate(),data.getIntendedDeliveryDate())){
                    onTimeCount++;
                }
            }
        }
        BigDecimal serviceScoreAvg=new BigDecimal(0);
        if(evaluateCount>0){
            serviceScoreAvg=evaluateSum.divide(new BigDecimal(evaluateCount),2, BigDecimal.ROUND_HALF_UP);
        }
        String onTimeRateStr=getOnTimeRate(onTimeCount,completedCount);
        totalCost=totalInnerCost.add(totalOuterCost).setScale(2,BigDecimal.ROUND_HALF_UP);
        obj.put("count", datas.size());
        obj.put("innerCost",fmtMicrometer(totalInnerCost.toString()));
        obj.put("outerCost",fmtMicrometer(totalOuterCost.toString()));
        obj.put("totalCost",fmtMicrometer(totalCost.toString()));
        obj.put("onTimeRate",onTimeRateStr);
        obj.put("serviceScoreAvg",serviceScoreAvg);
        return obj;
    }

    //计算关闭订单数量
    private  static void handleCloseCountSheet(List<BrandApplyVo> datas,Sheet sheet){
        int closeCount=0;
        for(BrandApplyVo data:datas){
            if(StringUtils.equals("4",data.getStatus())){
                closeCount++;
            }
        }
        sheet.getRow(1).getCell(1).setCellValue(closeCount);
    }


    public static void ExportBrandApply(List<BrandApplyVo> datas, HttpServletResponse response){
        try {
            String basePath= SystemConfig.p.getProperty("docXmlTemplatePath");
            XSSFWorkbook  wb =new XSSFWorkbook(new FileInputStream(basePath+"BrandApplyExportTemplate.xlsx"));
//            XSSFWorkbook wb =new XSSFWorkbook(new FileInputStream("E:\\文档\\信睿\\舍弗勒\\2020\\品牌申请\\BrandApplyExportTemplate.xlsx"));

            //读取了模板内所有sheet内容
            Sheet sheet = wb.getSheetAt(0);
            //获取总列数
            int index=2;
            for(BrandApplyVo data:datas){
                Row row=sheet.createRow(index);
                row.createCell(0).setCellValue(data.getNumber());
                String createDate= DateFormatUtils.getDateFormat(data.getCreateTime());
                row.createCell(1).setCellValue(createDate);
                row.createCell(2).setCellValue(data.getName());
                row.createCell(3).setCellValue(data.getDepartmentName());
                row.createCell(4).setCellValue(data.getEmail());
                row.createCell(5).setCellValue(data.getLegalEntity());
                row.createCell(6).setCellValue(data.getCostCenter());
                row.createCell(7).setCellValue(data.getLineManager());
                row.createCell(8).setCellValue(data.getLineManagerEmail());
                row.createCell(9).setCellValue(data.getCategoryName());
                StringBuffer categoryData=new StringBuffer();
                StringBuffer numData=new StringBuffer();
                for(BrandApplyDetailVo categoryObj:data.getDetails()){
                    categoryData.append(categoryObj.getMaterialName()+"\r\n");
                    numData.append(categoryObj.getMaterialName()+"×"+categoryObj.getQuantity()+"\n");
                }
                row.createCell(10).setCellValue(categoryData.toString());
                row.createCell(11).setCellValue(data.getRequireSpecify());
                String needMake="否";
                String numbers="";
                if(StringUtils.equals("1",data.getIsMaterialObject())){
                    needMake="是";
                    numbers=numData.toString();
                }
                row.createCell(12).setCellValue(needMake);
                row.createCell(13).setCellValue(numbers);
                row.createCell(14).setCellValue(DateFormatUtils.getDateFormat(data.getDeliveryDate()));
                row.createCell(15).setCellValue(data.getDescription());
                String requireCategory="";
                if(StringUtils.equals("0",data.getDistributionClass())){
                    requireCategory="仅设计";
                }else if(StringUtils.equals("1",data.getDistributionClass())){
                    requireCategory="仅制作";
                }else{
                    requireCategory="设计和制作";
                }
                row.createCell(16).setCellValue(requireCategory);
                row.createCell(17).setCellValue(data.getContactInformation());
                row.createCell(18).setCellValue(data.getEmpName());



                row.createCell(19).setCellValue("");


                row.createCell(20).setCellValue(data.getManHour()!=null?data.getManHour().toString():"");
                row.createCell(21).setCellValue(data.getHourlyRate()!=null?data.getHourlyRate().toString():"");
                row.createCell(22).setCellValue(data.getEstimateInternalCosts()!=null?fmtMicrometer(data.getEstimateInternalCosts().toString()):"");
                row.createCell(23).setCellValue(data.getSupplierName());
                row.createCell(24).setCellValue(data.getEstimateExternalCosts()!=null?fmtMicrometer(data.getEstimateExternalCosts().toString()):"");
                row.createCell(25).setCellValue(data.getQuotedPrice()!=null?fmtMicrometer(data.getQuotedPrice().toString()):"");
                row.createCell(26).setCellValue(data.getIntendedDeliveryDate()!=null? DateUtils.formatDate(data.getIntendedDeliveryDate(),"yyyy-MM-dd"):"");
                String status="";
                if(StringUtils.equals("0",data.getStatus())){
                    status="待接单";
                }else if(StringUtils.equals("1",data.getStatus())){
                    status="待确认";
                }else if(StringUtils.equals("2",data.getStatus())){
                    status="待审批";
                }else if(StringUtils.equals("3",data.getStatus())){
                    status="审批通过";
                }else if(StringUtils.equals("4",data.getStatus())){
                    status="关闭";
                }else if(StringUtils.equals("5",data.getStatus())){
                    status="已完成";
                }else if(StringUtils.equals("6",data.getStatus())){
                    status="已取消";
                }
                row.createCell(27).setCellValue(status);
                row.createCell(28).setCellValue(data.getCloseReason());
                row.createCell(29).setCellValue(data.getActualDeliveryDate()!=null?DateUtils.formatDate(data.getActualDeliveryDate(),"yyyy-MM-dd"):"");

                BigDecimal actInnerCost=new BigDecimal("0");
                if(data.getInnerCost()!=null&&data.getHourlyRate()!=null){
                    actInnerCost=new BigDecimal(data.getInnerCost()).multiply(new BigDecimal(data.getHourlyRate())).setScale(2,BigDecimal.ROUND_HALF_UP);
                }
                row.createCell(30).setCellValue(data.getInnerCost()!=null? fmtMicrometer(actInnerCost.toString()):"");
                row.createCell(31).setCellValue(data.getOuterCost()!=null?fmtMicrometer(data.getOuterCost().toString()):"");
                row.createCell(32).setCellValue(data.getTotalCost()!=null?fmtMicrometer(new BigDecimal(data.getOuterCost()).add(actInnerCost).toString()):"");
                row.createCell(33).setCellValue(data.getDesignQuanlityScore());
                row.createCell(34).setCellValue(data.getMakeQuanlityScore());
                row.createCell(35).setCellValue(data.getManagerFeedback());
                row.createCell(36).setCellValue(data.getServiceScore());
                row.createCell(37).setCellValue(data.getFeedback());
                row.createCell(38).setCellValue(data.getManagerRemark());
                index++;
            }
            OutputStream outputStream = response.getOutputStream();
            response.reset();
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("品牌工作报表-"+System.currentTimeMillis()/1000,"UTF-8")  + ".xlsx");
            //定义下载的类型，标明是excel文件
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            //这时候把创建好的excel写入到输出流
            wb.write(outputStream);
            //养成好习惯，出门记得随手关门
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getOnTimeRate(int onTimeCount,int completedCount){
        String onTimeRateStr=" ";
        if (completedCount !=0) {
            BigDecimal onTimeCountBD=new BigDecimal(String.valueOf(onTimeCount));
            BigDecimal completedCountBD=new BigDecimal(String.valueOf(completedCount));
            BigDecimal onTimeRate=onTimeCountBD.divide(completedCountBD,2,BigDecimal.ROUND_HALF_UP);
            onTimeRateStr=onTimeRate.multiply(new BigDecimal("100")).setScale(0,BigDecimal.ROUND_HALF_UP).toString()+"%";
        }
        return onTimeRateStr;
    }
}
