package com.cftech.common.typeappform.util;

import com.cftech.common.promotionstock.model.AfterStockDto;
import com.cftech.common.promotionstock.model.EvalityNumberDto;
import com.cftech.common.promotionstock.model.GrantDetailDto;
import com.cftech.common.promotionstock.service.PromotionStockService;
import com.cftech.common.typeappform.model.TypeAppForm;
import com.cftech.core.sql.Conds;
import com.cftech.core.util.Constants;
import com.cftech.core.util.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.NumberFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author lisw
 * @program schaeffler
 * @description 促销品统计报表
 * @createDate 2020-01-17 10:00:29
 **/
@Component
public class NewStatisticalExportUtil {

    private StatisticalCommonExportUtil statisticalCommonExportUtil = null;

    @Autowired
    private PromotionStockService promotionStockService;


    public void exportStatistical(String fileName, String startDate, String endDate, HttpServletResponse response) throws IOException {
        // 创建excel文件对象
        HSSFWorkbook wb = new HSSFWorkbook();
        statisticalCommonExportUtil = new StatisticalCommonExportUtil(wb);
        // 创建N个sheet
        Sheet sheetManagerStock = wb.createSheet("管理员库存统计");
        Sheet sheetSupplierStock = wb.createSheet("供应商发货统计");
        Sheet sheetDeptStatistical = wb.createSheet("按部门领用统计");
        Sheet sheetUseStatistical = wb.createSheet("按用途领用统计");
        Sheet sheetEvaluateStatistical = wb.createSheet("评价信息统计");
        Sheet sheetPromotionStatistical = wb.createSheet("促销品发放明细");
        String[] managerArr = rtnSheet1(startDate, endDate);
        String[] supplierArr = rtnSheet2(startDate, endDate);
        //第一个sheet数据填充
        String[] sheetManagerTitles = new String[]{"管理员库存统计", "管理员本月发货明细", "管理员本月发货金额", "管理员本月剩余库存", "管理员本月剩余库存金额"};
        createContentRow(sheetManagerStock, sheetManagerTitles, managerArr);
        //合并单元格
        sheetManagerMerged(sheetManagerStock);
        //第二个sheet
        String[] sheetSupplierTitles = new String[]{"供应商发货统计", "供应商发货明细", "供应商发货金额", "供应商物流金额", "需支付给供应商的金额"};
        createContentRow(sheetSupplierStock, sheetSupplierTitles, supplierArr);
        //合并单元格
        sheetManagerMerged(sheetSupplierStock);

        //第三个sheet
        String[] deptsAndUseTitles = new String[]{"月度部门领用统计", "领用明细（按降序排列）", "领用金额", "占总量百分比"};
        List<GrantDetailDto> grantDetailDtoDepts = promotionStockService.deptGrantDetails(startDate, endDate);
        Map<String, List<GrantDetailDto>> corpIdMap =
                grantDetailDtoDepts.stream().collect(Collectors.groupingBy(GrantDetailDto::getDname));
        createContentRowDeptAndUse(sheetDeptStatistical, deptsAndUseTitles, corpIdMap);
        //第四个sheet
        List<GrantDetailDto> grantDetailDtoUses = promotionStockService.useGrantDetails(startDate, endDate);
        Map<String, List<GrantDetailDto>> corpIdUseMap =
                grantDetailDtoUses.stream().collect(Collectors.groupingBy(GrantDetailDto::getUname));
        createContentRowDeptAndUse(sheetUseStatistical, deptsAndUseTitles, corpIdUseMap);
        //第五个sheet
        sheetQualityContent(sheetEvaluateStatistical,startDate,endDate);
        //第六个sheet
        sheetLogStaictical(sheetPromotionStatistical,startDate,endDate);
        //所有sheet首行合并单元格
        for(int i = 0;i<wb.getNumberOfSheets();i++){
            createHeaderFirsts(wb.getSheetAt(i),startDate,endDate);
        }
        //输出到客户端进行下载
        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();
    }

    //获取内容并解析sheet1,管理员库存统计
    public String[] rtnSheet1(String startDate, String endDate) {
        String[] managers = new String[5];
        //获取管理员的发货明细
        List<GrantDetailDto> managerGrantList = promotionStockService.managerGrantDetail(startDate, endDate);



        if (!managerGrantList.isEmpty()) {
            StringBuffer managerGrantBuffer = new StringBuffer();
            BigDecimal managerGrantTotalPrice = new BigDecimal("0");
            for (GrantDetailDto grantDetailDto : managerGrantList) {
                managerGrantBuffer.append(grantDetailDto.getItemname() + "*" + grantDetailDto.getGrantCount() + ";" + statisticalCommonExportUtil.getLineStr());
                managerGrantTotalPrice = managerGrantTotalPrice.add(grantDetailDto.getTotalPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
            }
            managers[1] = managerGrantBuffer.toString();
            managers[2] = managerGrantTotalPrice.toString();
        }
        //获取管理员的剩余库存明细
        List<AfterStockDto> afterStockDtos = promotionStockService.managerAfterStock(startDate, endDate);
        if (!afterStockDtos.isEmpty()) {
            StringBuffer afterStockBuffer = new StringBuffer();
            BigDecimal managerAfterStockTotalPrice = new BigDecimal("0");
            for (AfterStockDto afterStockDto : afterStockDtos) {
                afterStockBuffer.append(afterStockDto.getItemname() + "*" + afterStockDto.getAfterChangeStock() + ";" + statisticalCommonExportUtil.getLineStr());
                managerAfterStockTotalPrice = managerAfterStockTotalPrice.add(afterStockDto.getTotalPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
            }
            managers[3] = afterStockBuffer.toString();
            managers[4] = managerAfterStockTotalPrice.toString();
        }
        return managers;
    }

    //获取内容并极细sheet2，供应商库存统计
    public String[] rtnSheet2(String startDate, String endDate) {
        String[] suppliers = new String[5];
        //供应商发货总金额
        BigDecimal grantBigDecimal = new BigDecimal("0");
        //解析供应商发货明细
        List<GrantDetailDto> grantDetailDtos = promotionStockService.supplierGrantDetail(startDate, endDate);
        if (!grantDetailDtos.isEmpty()) {
            StringBuffer supplierGrantBuffer = new StringBuffer();
            for (GrantDetailDto grantDetailDto : grantDetailDtos) {
                supplierGrantBuffer.append(grantDetailDto.getItemname() + "*" + grantDetailDto.getGrantCount() + ";" + statisticalCommonExportUtil.getLineStr());
                grantBigDecimal = grantBigDecimal.add(grantDetailDto.getTotalPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
            }
            suppliers[1] = supplierGrantBuffer.toString();
            suppliers[2] = grantBigDecimal.toString();
        }

        //供应商物流金额
        BigDecimal logisticsPrice = promotionStockService.supplierLogisticsPrice(startDate, endDate);
        if (logisticsPrice == null) {
            logisticsPrice = new BigDecimal("0");
        }

        suppliers[3] = logisticsPrice.toString();
        suppliers[4] = grantBigDecimal.add(logisticsPrice).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
        return suppliers;
    }



    //每个sheet的第一列绘制
    public void createHeaderFirsts(Sheet sheet,String startDate,String endDate) {
        sheet.setDefaultColumnWidth(30);
        Row row = sheet.createRow(0);
        row.setHeight(statisticalCommonExportUtil.getRowHeight());
        Cell cell = row.createCell(0);
        CellStyle cellStyle = statisticalCommonExportUtil.getGrey25CellStyle();
        cellStyle.setAlignment(HorizontalAlignment.LEFT); // 水平布局：居左
        cell.setCellValue(startDate + "至" + endDate + sheet.getSheetName());
        cell.setCellStyle(cellStyle);
        for (int i = 1; i <= 30; i++) {
            Cell cellTemp = row.createCell(i);
            cellTemp.setCellValue("");
            cellTemp.setCellStyle(cellStyle);
        }
        CellRangeAddress region = new CellRangeAddress(0, 0, 0, 30);
        sheet.addMergedRegion(region);
    }

    //创建内容区前两个sheet（管理员库存统计，供应商发货统计）的表头
    public void createContentRow(Sheet sheet, String[] titles, String[] content) {
        Row row = sheet.createRow(1);
        row.setHeight(statisticalCommonExportUtil.getRowHeight());
        for (int i = 0; i < titles.length; i++) {
            Cell cell = row.createCell(i);
            if (i == titles.length - 1) {
                cell.setCellStyle(statisticalCommonExportUtil.getGoldCellStyle());
            } else {
                cell.setCellStyle(statisticalCommonExportUtil.getGreenCellStyle());
            }
            cell.setCellValue(titles[i]);
        }
        Row rowContent = sheet.createRow(2);
        rowContent.setHeight(statisticalCommonExportUtil.getRowHeight());
        for (int i = 0; i < content.length; i++) {
            try{
                Double d = Double.valueOf(content[i]);
                statisticalCommonExportUtil.createThousandBit(i,content[i],rowContent, (HSSFWorkbook) sheet.getWorkbook());
            }catch (Exception e){
                statisticalCommonExportUtil.createCell(i,content[i],rowContent);
            }
        }
    }

    //创建内容区第三个sheet（按部门纬度进行统计发放明细），第四个sheet（按用途纬度进行统计发放明细）
    public void createContentRowDeptAndUse(Sheet sheet, String[] titles, Map<String, List<GrantDetailDto>> corpIdMap) {
        Row row = sheet.createRow(1);
        row.setHeight(statisticalCommonExportUtil.getRowHeight());
        for (int i = 0; i < titles.length; i++) {
            Cell cell = row.createCell(i);
            cell.setCellStyle(statisticalCommonExportUtil.getGreenCellStyle());
            cell.setCellValue(titles[i]);
        }

        Set<String> keys = corpIdMap.keySet();
        //所有零用的促销品数量
        Map<String, Integer> allGrantCountMap = new HashMap<>();
        //所有部门加在一起的发货金额
        BigDecimal bigDecimalAllTotalPrice = new BigDecimal("0");
        Row rowAll = sheet.createRow(2);
        int index = 3;
        for (String key : keys) {
            Row rowdept = sheet.createRow(index++);
            List<GrantDetailDto> grantDetailDtos = corpIdMap.get(key);
            StringBuffer stringBuffer = new StringBuffer();
            BigDecimal sligeBigDecimal = new BigDecimal("0");//本部门总的发货金额
            for (GrantDetailDto grantDetailDto : grantDetailDtos) {
                if(grantDetailDto.getTotalPrice()==null){
                    grantDetailDto.setTotalPrice(new BigDecimal(0));
                }
                sligeBigDecimal =sligeBigDecimal.add(grantDetailDto.getTotalPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
                Integer count = grantDetailDto.getGrantCount();
                if(count==null){
                    count=0;
                }
                String itemName = grantDetailDto.getItemname();
                if (allGrantCountMap.containsKey(grantDetailDto.getItemname())) {
                    Integer oldcount = allGrantCountMap.get(itemName);
                    oldcount += count;
                    allGrantCountMap.put(itemName, oldcount);
                } else {
                    allGrantCountMap.put(itemName, count);
                }
                stringBuffer.append(itemName + "*" + count + statisticalCommonExportUtil.getLineStr());

            }
            bigDecimalAllTotalPrice =bigDecimalAllTotalPrice.add(sligeBigDecimal).setScale(2, BigDecimal.ROUND_HALF_UP);
            for (int i = 0; i < 4; i++) {
                switch (i) {
                    case 0:
                        statisticalCommonExportUtil.createCell(i,key,rowdept);
                        //cell.setCellValue(key);
                        break;
                    case 1:
                        statisticalCommonExportUtil.createCell(i,stringBuffer.toString(),rowdept);
                        //cell.setCellValue(stringBuffer.toString());
                        break;
                    case 2:
                        statisticalCommonExportUtil.createThousandBit(i,sligeBigDecimal.toString(),rowdept, (HSSFWorkbook) sheet.getWorkbook());
                        //convertType(cell,sligeBigDecimal.toString());
                        break;
                    default:
                        statisticalCommonExportUtil.createCell(i,"",rowdept);
                        break;
                }
            }
        }
        if (allGrantCountMap.size() > 0) {//汇总内容填充

            allGrantCountMap = sortByValue2(allGrantCountMap, 0);
            Set<String> allKeys = allGrantCountMap.keySet();
            StringBuffer allGrantDetailsBuffer = new StringBuffer();
            for (String allKey : allKeys) {
                allGrantDetailsBuffer.append(allKey + "*" + allGrantCountMap.get(allKey) + statisticalCommonExportUtil.getLineStr());
            }
            for (int i = 0; i < 4; i++) {

                switch (i) {
                    case 0:
                        statisticalCommonExportUtil.createCell(i,"月度领用总统计（所有）",rowAll);
                        //cell.setCellValue("月度领用总统计（所有）");
                        break;
                    case 1:
                        statisticalCommonExportUtil.createCell(i,allGrantDetailsBuffer.toString(),rowAll);
                        //cell.setCellValue(allGrantDetailsBuffer.toString());
                        break;
                    case 2:
//                        cell.setCellValue(bigDecimalAllTotalPrice.toString());
                       statisticalCommonExportUtil.createThousandBit(i,bigDecimalAllTotalPrice.toString(),rowAll, (HSSFWorkbook) sheet.getWorkbook());
                        //convertType(cell,bigDecimalAllTotalPrice.toString());
                        break;
                    case 3:
                        statisticalCommonExportUtil.createCell(i,"100%",rowAll);
                        //cell.setCellValue("100%");
                        break;
                }
            }
        }

        //计算百分比
        int rows = sheet.getLastRowNum();
        for (int p = 3; p <=rows; p++) {
            Row rowTemp = sheet.getRow(p);
            Cell cell = rowTemp.getCell(2);
            BigDecimal price = new BigDecimal(cell.getNumericCellValue());//占用金额
            price = price.divide(bigDecimalAllTotalPrice,2,BigDecimal.ROUND_HALF_UP);
            NumberFormat percent = NumberFormat.getPercentInstance();
            percent.setMaximumFractionDigits(2);
            String percentPrice = percent.format(price.doubleValue());
            Cell cellPrecent = rowTemp.getCell(3);
            cellPrecent.setCellValue(percentPrice);
            cellPrecent.setCellStyle(statisticalCommonExportUtil.getGenterateCellStyle());
        }
    }

    //创建第五个sheet，评价统计
    private void sheetQualityContent(Sheet sheet,String startDate,String endDate){
        EvalityNumberDto managerEvalityNumberDto = promotionStockService.managerEvaluate(startDate,endDate);
        EvalityNumberDto applyEvalityNumberDto = promotionStockService.applyEvaluate(startDate,endDate);
        Integer managerConfirm = promotionStockService.managerConfirm(startDate,endDate);
        String [] qualityTitles= new String[] {"管理员提交评价订单数量","","申请人提交评价订单数量","","管理员确认收货订单数量",""};
        List<String []> mapList = new ArrayList<>();
        String[] titleMap = new String[]{"月度评价统计","整体评价","促销品质量","物流服务"};
        mapList.add(titleMap);
        String[] managerMap = new String[]{"管理员","","",""};
        String[]  applyMap = new String[]{"申请人","","",""};
        if(managerEvalityNumberDto!=null){
            qualityTitles[1] = String.valueOf(managerEvalityNumberDto.getCount());
            Integer allEvaluateCount = managerEvalityNumberDto.getAllEvaluateCount();
            Integer qualityEvaluateCount = managerEvalityNumberDto.getQualityEvaluateCount();
            Integer logisticsEvaluateCount = managerEvalityNumberDto.getLogisticsEvaluateCount();
            managerMap[1]=allEvaluateCount!=null?allEvaluateCount.toString():"0";
            managerMap[2]=qualityEvaluateCount!=null?qualityEvaluateCount.toString():"0";
            managerMap[3]=logisticsEvaluateCount!=null?logisticsEvaluateCount.toString():"0";
        }
        if(applyEvalityNumberDto!=null){
            qualityTitles[3] = String.valueOf(applyEvalityNumberDto.getCount());
            Integer allEvaluateCount = applyEvalityNumberDto.getAllEvaluateCount();
            Integer qualityEvaluateCount = applyEvalityNumberDto.getQualityEvaluateCount();
            Integer logisticsEvaluateCount = applyEvalityNumberDto.getLogisticsEvaluateCount();
            applyMap[1] = allEvaluateCount!=null?allEvaluateCount.toString():"0";
            applyMap[2] = qualityEvaluateCount!=null?qualityEvaluateCount.toString():"0";
            applyMap[3] = logisticsEvaluateCount!=null?logisticsEvaluateCount.toString():"0";
        }
        mapList.add(managerMap);
        mapList.add(applyMap);
        qualityTitles[5] = String.valueOf(managerConfirm);
        Row row =  sheet.createRow(1);
        row.setHeight(statisticalCommonExportUtil.getRowHeight());
        for(int i =0;i<6;i++){
            Cell cell = row.createCell(i);
            if(i%2==0){
                cell.setCellStyle(statisticalCommonExportUtil.getGreenCellStyle());
            }else{
                cell.setCellStyle(statisticalCommonExportUtil.getGenterateCellStyle());
            }
            convertType(cell,qualityTitles[i]);
        }

        //创建空行，占位行高
        Row rowEmpty = sheet.createRow(2);
        rowEmpty.setHeight(statisticalCommonExportUtil.getRowHeight());

        for (int i = 0; i < mapList.size(); i++) {
            String [] array = mapList.get(i);
            Row createRow = sheet.createRow(3+i);
            createRow.setHeight(statisticalCommonExportUtil.getRowHeight());
            for (int k = 0; k < array.length; k++) {
                Cell cell = createRow.createCell(k);
                convertType(cell,array[k]==null?"":array[k]);
                //cell.setCellValue(array[k]==null?"":array[k]);
                if(i==0 || k==0){
                    cell.setCellStyle(statisticalCommonExportUtil.getGreenCellStyle());
                }else{
                    cell.setCellStyle(statisticalCommonExportUtil.getGenterateCellStyle());
                }
            }
        }
    }

    //第六个sheet,明细信息
    private void sheetLogStaictical(Sheet sheet,String startDate,String endDate){
        String [] sheetPromotionStaticticalTitle = new String[]{"序号","申请单号","Legal Entity","部门","成本中心","发放状态","发货方","发货明细",
                "发货物流信息","供应商发货物流金额","管理员发货备注","发货总金额","管理员发货金额","供应商发货金额","需支付给供应商的金额"
        };
        Row rowFirst = sheet.createRow(1);
        rowFirst.setHeight(statisticalCommonExportUtil.getRowHeight());
        for (int i = 0; i <sheetPromotionStaticticalTitle.length ; i++) {
            Cell cell = rowFirst.createCell(i);
            cell.setCellStyle(statisticalCommonExportUtil.getGreenCellStyle());
            cell.setCellValue(sheetPromotionStaticticalTitle[i]);
        }
        Conds conds = new Conds();
        conds.equal("appform.del_flag", Constants.DEL_FLAG_0);
        List<TypeAppForm> typeAppForms = promotionStockService.fetchSearchByPageByAppform(conds,startDate,endDate);
        if(!typeAppForms.isEmpty()){
            for (int i = 0; i < typeAppForms.size(); i++) {
                Row dataRow = sheet.createRow(i+2);
                TypeAppForm typeAppForm = typeAppForms.get(i);
                statisticalCommonExportUtil.createCell(0,typeAppForm.getSerialNumber(),dataRow);
                statisticalCommonExportUtil.createCell(1,typeAppForm.getNumber(),dataRow);
                statisticalCommonExportUtil.createCell(2,typeAppForm.getLegalEntity(),dataRow);
                statisticalCommonExportUtil.createCell(3,typeAppForm.getDname(),dataRow);
                statisticalCommonExportUtil.createCell(4,typeAppForm.getCostCenter(),dataRow);
                statisticalCommonExportUtil.createCell(5,typeAppForm.getIssuingStateName(),dataRow);
                String items = typeAppForm.getItems();
                String grantSourceName = "";//发放方
                String logistics = ""; //物流信息
                String grantDetails = "";//发放信息
                //发货总金额
                String sumGrantPrice = null;
                switch (typeAppForm.getGrantSource()){
                    case "0"://仅供应商
                        if(StringUtils.isNotBlank(typeAppForm.getDisLogisticsOrderInfo())){
                            logistics+=typeAppForm.getDisLogisticsOrderInfo();
                        }
                        grantDetails = statisticalCommonExportUtil.parseItemsSupplierJSON(items);
                        grantSourceName="仅供应商";
                        sumGrantPrice=typeAppForm.getDisTotalPrice();
                        /**
                         * 仅供应商的时候，如果发生退库，金额是退到管理员发货金额上面的。供应商发货数量和发货金额并不会减少。
                         * 故，此处应该判断一下，管理员发货金额，如果不为空，说明存在退库。管理员发货金额，为负数。加上这个金额，才是最终退库后的实际发货总金额
                         */
                        if(StringUtils.isNotBlank(typeAppForm.getTotalPrice())){
                            BigDecimal disBig = new BigDecimal(typeAppForm.getDisTotalPrice());
                            BigDecimal managerBig = new BigDecimal(typeAppForm.getTotalPrice());
                            sumGrantPrice=disBig.add(managerBig).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                        }
                        break;
                    case "1"://仅管理员
                        if(StringUtils.isNotBlank(typeAppForm.getLogisticsOrderInfo())){
                            logistics+=typeAppForm.getLogisticsOrderInfo();
                        }
                        grantDetails = statisticalCommonExportUtil.parseItemsManagerJSON(items);
                        grantSourceName="仅管理员";
                        sumGrantPrice=typeAppForm.getTotalPrice();
                        break;
                    case "2"://供应商加管理员
                        grantSourceName="供应商+管理员";
                        String managerName = " 管理员:";
                        String supplierName = " 供应商:";
                        if(StringUtils.isNotBlank(typeAppForm.getLogisticsOrderInfo())){
                            logistics+=managerName+typeAppForm.getLogisticsOrderInfo();
                        }
                        if(StringUtils.isNotBlank(typeAppForm.getDisLogisticsOrderInfo())){
                            logistics+=supplierName+typeAppForm.getDisLogisticsOrderInfo();
                        }
                        grantDetails=managerName+statisticalCommonExportUtil.parseItemsManagerJSON(items)+statisticalCommonExportUtil.getLineStr();
                        grantDetails+=supplierName+statisticalCommonExportUtil.parseItemsSupplierJSON(items);
                        BigDecimal disBig = new BigDecimal(typeAppForm.getDisTotalPrice());
                        BigDecimal managerBig = new BigDecimal(typeAppForm.getTotalPrice());
                        sumGrantPrice=disBig.add(managerBig).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                        break;
                }
                statisticalCommonExportUtil.createCell(6,grantSourceName,dataRow);
                statisticalCommonExportUtil.createCell(7,grantDetails,dataRow);
                statisticalCommonExportUtil.createCell(8,logistics,dataRow);
                statisticalCommonExportUtil.createThousandBit(9,typeAppForm.getDisLogisticsPrice(),dataRow, (HSSFWorkbook) sheet.getWorkbook());
                statisticalCommonExportUtil.createCell(10,typeAppForm.getManagerSubmitRemarks(),dataRow);
                statisticalCommonExportUtil.createThousandBit(11,sumGrantPrice,dataRow, (HSSFWorkbook) sheet.getWorkbook());
                statisticalCommonExportUtil.createThousandBit(12,typeAppForm.getTotalPrice(),dataRow, (HSSFWorkbook) sheet.getWorkbook());
                statisticalCommonExportUtil.createThousandBit(13,typeAppForm.getDisTotalPrice(),dataRow, (HSSFWorkbook) sheet.getWorkbook());
                //需要支付给供应商的金额，发放金额+物流金额
                if(StringUtils.isNotBlank(typeAppForm.getDisLogisticsPrice())){
                    BigDecimal bigLogisticsDecimal = new BigDecimal(typeAppForm.getDisLogisticsPrice());
                    BigDecimal bigGrantDecimal = new BigDecimal(typeAppForm.getDisTotalPrice());
                    BigDecimal res = bigGrantDecimal.add(bigLogisticsDecimal).setScale(2, BigDecimal.ROUND_HALF_UP);
                    statisticalCommonExportUtil.createThousandBit(14,res,dataRow, (HSSFWorkbook) sheet.getWorkbook());
                }else{
                    statisticalCommonExportUtil.createCell(14,"",dataRow);
                }
            }
        }
    }



    //合并管理员库存统计，供应商发货统计两个sheet中需要合并的单元格
    private void sheetManagerMerged(Sheet sheet) {
        CellRangeAddress regionTitle = new CellRangeAddress(1, 2, 0, 0);
        sheet.addMergedRegion(regionTitle);
    }

    public void convertType(Cell cell,String v){
        if(StringUtils.isBlank(v))
        {
            return;
        };
        Pattern integerP = Pattern.compile("^-?\\d+$");
        Matcher integerMatcher = integerP.matcher(v);
        Pattern doubleP = Pattern.compile("^(-?\\d+)(\\.\\d+)?$");
        Matcher doubleMatcher = doubleP.matcher(v);
        if (integerMatcher.matches()) {// 是数字
            cell.setCellValue(Integer.valueOf(v));
        } else if(doubleMatcher.matches()){
            cell.setCellValue(Double.valueOf(v));
        }else{
            cell.setCellValue(v);
        }
    }



    //Map排序

    /**
     * @param map
     * @param flag 1正序 0 倒序
     * @param <K>
     * @param <V>
     * @return
     */
    public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue2(Map<K, V> map, int flag) {

        if (flag == 1) {
            return map.entrySet().stream().sorted((o1, o2) -> o1.getValue().compareTo(o2.getValue())).map(entry -> {
                Map<K, V> result = new LinkedHashMap<>();
                result.put(entry.getKey(), entry.getValue());
                return result;
            }).reduce((map1, map2) -> {
                map2.entrySet().forEach(entry -> map1.put(entry.getKey(), entry.getValue()));
                return map1;
            }).get();
        } else {
            return map.entrySet().stream().sorted((o1, o2) -> o2.getValue().compareTo(o1.getValue())).map(entry -> {
                Map<K, V> result = new LinkedHashMap<>();
                result.put(entry.getKey(), entry.getValue());
                return result;
            }).reduce((map1, map2) -> {
                map2.entrySet().forEach(entry -> map1.put(entry.getKey(), entry.getValue()));
                return map1;
            }).get();

        }

    }
}
