package com.yh.saas.plugin.yiliangyiyun.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.sofa.runtime.api.annotation.SofaReference;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.winsea.svc.base.base.entity.CommonRoleResource;
import com.winsea.svc.base.base.service.ICommonRoleResourceService;
import com.winsea.svc.base.base.util.DateUtils;
import com.winsea.svc.base.security.entity.User;
import com.winsea.svc.base.security.util.AuthSecurityUtils;
import com.yh.saas.plugin.yiliangyiyun.constant.StatusEnum;
import com.yh.saas.plugin.yiliangyiyun.entity.*;
import com.yh.saas.plugin.yiliangyiyun.mapper.StockPurchaseReceiptReportMapper;
import com.yh.saas.plugin.yiliangyiyun.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 现货采购入库报表 服务实现类
 * </p>
 *
 * @author Gdc
 * @since 2021-09-17
 */
@Service
@Slf4j
public class StockPurchaseReceiptReportServiceImpl extends ServiceImpl<StockPurchaseReceiptReportMapper, StockPurchaseReceiptReport> implements IStockPurchaseReceiptReportService {


    @Autowired
    private INewWorkflowService workflowService;

    @SofaReference
    private ICommonRoleResourceService roleResourceService;
    @Autowired
    private IContractManagementInfoService contractManagementInfoService;
    @Autowired
    private IContractGoodsInfoService contractGoodsInfoService;
    @Autowired
    private IWarehouseInOutInfoService warehouseInOutInfoService;
    @Value("${file-root-path}")
    private String localPath;
    /**
     * 采购入库统计
     *
     * @param stockPurchaseReceiptReport
     * @return
     */
    @Override
    public Page<StockPurchaseReceiptReport> selectPurchaseOrder(StockPurchaseReceiptReport stockPurchaseReceiptReport) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (stockPurchaseReceiptReport.getCurrentPage() - 1)
                * stockPurchaseReceiptReport.getPageSize());
        List<String> businessKeys = null;
        if ("1".equals(stockPurchaseReceiptReport.getSearchType())) {
            businessKeys = workflowService.getTaskBusinessKeysByCode("STOCK-PROCUREMENT-RECEIPT-REPORT");
        }
        List<String> statusSet = new ArrayList<>();
        List<String> resourceIdList = this.getResourceIdList();
        if (resourceIdList.contains("procurementStockInReport-Edit")) { // 填写，提交    权限做完以后替换
            List<String> statusList = Lists.newArrayList(StatusEnum.PUR_RETURN.getFlag());
            statusSet.addAll(statusList);
        }
        //公司id
        pageView.put("compId", stockPurchaseReceiptReport.getCompId());
        pageView.put("searchKeyWord", stockPurchaseReceiptReport.getSearchKeyWord());
        pageView.put("searchType", stockPurchaseReceiptReport.getSearchType());
        pageView.put("pageSize", stockPurchaseReceiptReport.getPageSize());
        pageView.put("startDate", stockPurchaseReceiptReport.getStartDate());
        pageView.put("endDate", stockPurchaseReceiptReport.getEndDate());
        pageView.put("currentPage", stockPurchaseReceiptReport.getCurrentPage());
        pageView.put("contractNo", stockPurchaseReceiptReport.getContractNo());
        pageView.put("statusFlag", stockPurchaseReceiptReport.getStatusFlag());
        pageView.put("businessKeys", businessKeys);
        pageView.put("statusSet", statusSet);
        // 查询采购入库总数
        Integer dataCount = baseMapper.getCountByCondition(pageView);
        List<StockPurchaseReceiptReport> dataList = baseMapper.getListByCondition(pageView);
        if (!CollectionUtils.isEmpty(dataList)) {
            for (StockPurchaseReceiptReport purchaseReceiptReport1:dataList){
                WarehouseInOutInfo warehouseInOutInfo=warehouseInOutInfoService.selectOne(new EntityWrapper<WarehouseInOutInfo>()
                .eq("contract_no",purchaseReceiptReport1.getContractNo())
                .eq("car_no",purchaseReceiptReport1.getCarNo()).eq("warehouse_name",purchaseReceiptReport1.getWarehouseName()));
                if (warehouseInOutInfo!=null){
                    purchaseReceiptReport1.setPoundImg(warehouseInOutInfo.getAddressUrl());
                }
                String taskId = "";
                // 只有待审核状态才有taskId
                if (StringUtils.isNotBlank(purchaseReceiptReport1.getWorkflowId())) {
                    JSONObject jsonObject = workflowService.getActiveTask(Lists.newArrayList(purchaseReceiptReport1.getWorkflowId()), purchaseReceiptReport1.getId());
                    taskId = jsonObject.getString("taskId");
                    purchaseReceiptReport1.setTaskId(taskId);
                }
            }
        }
        Page<StockPurchaseReceiptReport> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(stockPurchaseReceiptReport.getCurrentPage());
        page.setSize(stockPurchaseReceiptReport.getPageSize());
        return page;
    }


    /**
     * 定金/备注
     *
     * @param contractManagementInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String disAndRemark(ContractManagementInfo contractManagementInfo) {
        //查询合同
        ContractManagementInfo contractManagementInfo1 = contractManagementInfoService.selectById(contractManagementInfo.getId());
        if (contractManagementInfo1 != null) {
            if(StringUtils.isNotBlank(contractManagementInfo.getDeposit())){
                contractManagementInfo1.setDeposit(contractManagementInfo.getDeposit());
                contractManagementInfo1.setDepositUrl(contractManagementInfo.getDepositUrl());
            }
            if(StringUtils.isNotBlank(contractManagementInfo.getRemark())){
                contractManagementInfo1.setRemark(contractManagementInfo.getRemark());
            }
            //更改采购入库报表信息
            contractManagementInfoService.updateById(contractManagementInfo1);
            return "OK";
        }
        return "NG";
    }


    /**
     * 修改结算重量
     *
     * @param stockPurchaseReceiptReport
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String edit(StockPurchaseReceiptReport stockPurchaseReceiptReport) {
        //查询采购入库报表
        StockPurchaseReceiptReport stockPurchaseReceiptReport1 = this.selectById(stockPurchaseReceiptReport.getId());
        if (stockPurchaseReceiptReport1 != null) {
            if ("1".equals(stockPurchaseReceiptReport.getFlag())) {
                stockPurchaseReceiptReport1.setSettlementWeight(stockPurchaseReceiptReport.getSettlementWeight());
                stockPurchaseReceiptReport1.setAmountIngPayable(stockPurchaseReceiptReport.getSettlementWeight() * stockPurchaseReceiptReport1.getSettlementPrice());
                stockPurchaseReceiptReport1.setAmountNotPayable(stockPurchaseReceiptReport1.getAmountIngPayable() - stockPurchaseReceiptReport1.getAmountEdPayable());
            }
            else{
                stockPurchaseReceiptReport1.setSettlementPrice(stockPurchaseReceiptReport.getSettlementPrice());
                stockPurchaseReceiptReport1.setAmountIngPayable(stockPurchaseReceiptReport1.getSettlementWeight() * stockPurchaseReceiptReport.getSettlementPrice());
                stockPurchaseReceiptReport1.setAmountNotPayable(stockPurchaseReceiptReport1.getAmountIngPayable() - stockPurchaseReceiptReport1.getAmountEdPayable());
            }
            //更改采购入库报表信息
            this.updateById(stockPurchaseReceiptReport1);
            return "OK";
        }
        return "NG";
    }
    /**
     * 出纳付款
     *
     * @param stockPurchaseReceiptReport
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String payMoney(StockPurchaseReceiptReport stockPurchaseReceiptReport) {
        List<StockPurchaseReceiptReport> stockPurchaseReceiptReportList = stockPurchaseReceiptReport.getStockPurchaseReceiptReportList();
        Double money = stockPurchaseReceiptReport.getMoney();
        //付款多条
        if (!CollectionUtils.isEmpty(stockPurchaseReceiptReportList)) {
            for (StockPurchaseReceiptReport stockPurchaseReceiptReport1 : stockPurchaseReceiptReportList) {
                StockPurchaseReceiptReport stockPurchaseReceiptReport2 = this.selectById(stockPurchaseReceiptReport1.getId());
                //付款金额大于本次循环未付金额
                if (money >= stockPurchaseReceiptReport1.getAmountNotPayable()) {
                    money = money - stockPurchaseReceiptReport1.getAmountNotPayable();
                    //全部付款
                    stockPurchaseReceiptReport1.setStatus(StatusEnum.PUR_PAYaLL.getName());
                    stockPurchaseReceiptReport1.setStatusFlag(StatusEnum.PUR_PAYaLL.getFlag());
                    stockPurchaseReceiptReport1.setPaymentDate(stockPurchaseReceiptReport.getPaymentDate());
                    stockPurchaseReceiptReport1.setPaymentScreenshot(stockPurchaseReceiptReport2.getPaymentScreenshot() != null ? stockPurchaseReceiptReport2.getPaymentScreenshot() + '$' + stockPurchaseReceiptReport.getPaymentScreenshot() : stockPurchaseReceiptReport.getPaymentScreenshot());
                    stockPurchaseReceiptReport1.setAmountEdPayable(stockPurchaseReceiptReport1.getAmountEdPayable() + stockPurchaseReceiptReport1.getAmountNotPayable());
                    stockPurchaseReceiptReport1.setAmountNotPayable(0.0d);
                    this.updateById(stockPurchaseReceiptReport1);
                } else if (money > 0) {
                    Double moneyTmp = money - stockPurchaseReceiptReport1.getAmountNotPayable();
                    //部分付款
                    stockPurchaseReceiptReport1.setStatus(StatusEnum.PUR_PAY.getName());
                    stockPurchaseReceiptReport1.setStatusFlag(StatusEnum.PUR_PAY.getFlag());
                    stockPurchaseReceiptReport1.setPaymentDate(stockPurchaseReceiptReport.getPaymentDate());
                    stockPurchaseReceiptReport1.setPaymentScreenshot(stockPurchaseReceiptReport2.getPaymentScreenshot() != null ? stockPurchaseReceiptReport2.getPaymentScreenshot() + '$' + stockPurchaseReceiptReport.getPaymentScreenshot() : stockPurchaseReceiptReport.getPaymentScreenshot());
                    stockPurchaseReceiptReport1.setAmountEdPayable(stockPurchaseReceiptReport1.getAmountEdPayable() + money);
                    stockPurchaseReceiptReport1.setAmountNotPayable(stockPurchaseReceiptReport1.getAmountNotPayable() - money);
                    this.updateById(stockPurchaseReceiptReport1);
                    money = moneyTmp;
                } else {
                    break;
                }
            }
        }
        return "OK";
    }
    /**
     * 合同编号下拉列表
     *
     * @param compId
     */
    @Override
    public List<ContractManagementInfo> selectContractNoList(String compId) {
        //查现货采购合同
        List<ContractManagementInfo> contractManagementInfoList = contractManagementInfoService.selectList(new EntityWrapper<ContractManagementInfo>()
                .eq("comp_id", compId)
                .eq("contract_type", "2")
                .eq("delete_flag", "0")
                .orderBy("update_date", false));

        for (ContractManagementInfo contractManagementInfo : contractManagementInfoList) {
            ContractGoodsInfo contractGoodsInfo = contractGoodsInfoService.selectOne(new EntityWrapper<ContractGoodsInfo>()
                    .eq("contract_id",contractManagementInfo.getId()));
            contractManagementInfo.setGoodsName(contractGoodsInfo.getGoodsName());
            Double money = 0.0d;
            //查现货采购入库报表
            List<StockPurchaseReceiptReport> stockPurchaseReceiptReportList = this.selectList(new EntityWrapper<StockPurchaseReceiptReport>()
                    .eq("contract_no", contractManagementInfo.getContractNo())
                    .eq("delete_flag", "0"));
            if (!CollectionUtils.isEmpty(stockPurchaseReceiptReportList)) {
                for (StockPurchaseReceiptReport stockPurchaseReceiptReport : stockPurchaseReceiptReportList) {
                    money = money + stockPurchaseReceiptReport.getAmountNotPayable();
                }
                //有未付金额
                if (money > 0) {
                    contractManagementInfo.setReportStatus("待结算");
                } else {
                    contractManagementInfo.setReportStatus("已结算");
                }
            }
        }
        return contractManagementInfoList;
    }

    /**
     * 查看
     * @param id
     * @return
     */
    @Override
    public StockPurchaseReceiptReport getInfo(String id) {
        StockPurchaseReceiptReport stockPurchaseReceiptReport=this.selectById(id);
        ContractManagementInfo contractManagementInfo=contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
            .eq("contract_no",stockPurchaseReceiptReport.getContractNo())
            .eq("comp_id",stockPurchaseReceiptReport.getCompId()));
        //货物信息
        ContractGoodsInfo contractGoodsInfo = contractGoodsInfoService.selectOne(new EntityWrapper<ContractGoodsInfo>().eq(ContractGoodsInfo.QueryFiles.CONTRACT_ID, contractManagementInfo.getId()));
        stockPurchaseReceiptReport.setPrice(contractManagementInfo.getUnitContractPrice());
        stockPurchaseReceiptReport.setCustomer(contractManagementInfo.getSeller());
        stockPurchaseReceiptReport.setGoodsName(contractGoodsInfo.getGoodsName());
        return stockPurchaseReceiptReport;
    }

    @Override
    public void export(StockPurchaseReceiptReport stockPurchaseReceiptReport, HttpServletResponse response) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        // 1.Excel的头部信息
        String headerTitle = "";

        // 2.创建一个webbook 对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();

        // 3.在webbook中添加一个sheet，对应Excel文件中的sheet
        HSSFSheet sheet;

        sheet = wb.createSheet("现货采购报表信息");
        headerTitle = "现货采购报表信息";

        // 4.设置打印参数
        sheet.setMargin(HSSFSheet.TopMargin, (short) 1);// 页边距（上）
        sheet.setMargin(HSSFSheet.BottomMargin, (short) 1);// 页边距（下）
        sheet.setMargin(HSSFSheet.LeftMargin, (short) 1);// 页边距（左）
        sheet.setMargin(HSSFSheet.RightMargin, (short) 1);// 页边距（右）

        // 不显示网格
        sheet.setDisplayGridlines(false);
        // 设置水平居中
        sheet.setHorizontallyCenter(true);

        /**************** 数据行样式 start ****************/
        HSSFFont fontTitle = wb.createFont();
        fontTitle.setFontName("宋体");
        fontTitle.setFontHeightInPoints((short) 14);
        // 设置字体加粗
        fontTitle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

        HSSFFont fontComp = wb.createFont();
        fontComp.setFontName("宋体");
        fontComp.setFontHeightInPoints((short) 16);
        // 设置字体加粗
        fontComp.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

        HSSFFont fontDetail = wb.createFont();
        fontDetail.setFontName("宋体");
        fontDetail.setFontHeightInPoints((short) 12);

        // title
        HSSFCellStyle styleTitle = wb.createCellStyle();
        // 指定单元格居中对齐
        styleTitle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 指定单元格垂直居中对齐
        styleTitle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleTitle.setWrapText(true);
        // 设置单元格字体
        styleTitle.setFont(fontTitle);
        // 右边框
        styleTitle.setBorderRight(HSSFCellStyle.BORDER_NONE);
        // 左边框
        styleTitle.setBorderLeft(HSSFCellStyle.BORDER_NONE);
        // 上边框
        styleTitle.setBorderTop(HSSFCellStyle.BORDER_NONE);
        // 下边框
        styleTitle.setBorderBottom(HSSFCellStyle.BORDER_NONE);

        HSSFCellStyle contextstyle = wb.createCellStyle();
        // 指定单元格居中对齐
        contextstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 指定单元格垂直居中对齐
        contextstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        contextstyle.setWrapText(true);
        // 设置单元格字体
        contextstyle.setFont(fontDetail);
        // 右边框
        contextstyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 左边框
        contextstyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 上边框
        contextstyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 下styleDetailTitle
        contextstyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);

        // title
        HSSFCellStyle styleComp = wb.createCellStyle();
        // 指定单元格居中对齐
        styleComp.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 指定单元格垂直居中对齐
        styleComp.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleComp.setWrapText(true);
        // 设置单元格字体
        styleComp.setFont(fontComp);
        // 右边框
        styleComp.setBorderRight(HSSFCellStyle.BORDER_NONE);
        // 左边框
        styleComp.setBorderLeft(HSSFCellStyle.BORDER_NONE);
        // 上边框
        styleComp.setBorderTop(HSSFCellStyle.BORDER_NONE);
        // 下边框
        styleComp.setBorderBottom(HSSFCellStyle.BORDER_NONE);

        HSSFCellStyle styleInfo = wb.createCellStyle();
        // 指定单元格居中对齐
        styleInfo.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        // 指定单元格垂直居中对齐
        styleInfo.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleInfo.setWrapText(true);
        // 设置单元格字体
        styleInfo.setFont(fontDetail);
        // 右边框
        styleInfo.setBorderRight(HSSFCellStyle.BORDER_NONE);
        // 左边框
        styleInfo.setBorderLeft(HSSFCellStyle.BORDER_NONE);
        // 上边框
        styleInfo.setBorderTop(HSSFCellStyle.BORDER_NONE);
        // 下边框
        styleInfo.setBorderBottom(HSSFCellStyle.BORDER_NONE);

        HSSFCellStyle styleDetail = wb.createCellStyle();
        // 指定单元格居中对齐
        styleDetail.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 指定单元格垂直居中对齐
        styleDetail.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleDetail.setWrapText(true);
        // 设置单元格字体
        styleDetail.setFont(fontDetail);
        // 右边框
        styleDetail.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 左边框
        styleDetail.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 上边框
        styleDetail.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 下styleDetailTitle
        styleDetail.setBorderBottom(HSSFCellStyle.BORDER_THIN);

        HSSFCellStyle styleDetailYellow = wb.createCellStyle();
        // 指定单元格居中对齐
        styleDetailYellow.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 指定单元格垂直居中对齐
        styleDetailYellow.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleDetailYellow.setWrapText(true);
        // 设置单元格字体
        styleDetailYellow.setFont(fontDetail);
        // 右边框
        styleDetailYellow.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 左边框
        styleDetailYellow.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 上边框
        styleDetailYellow.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 下styleDetailTitle
        styleDetailYellow.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        styleDetailYellow.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        styleDetailYellow.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);


        HSSFCellStyle styleDetailLeft = wb.createCellStyle();
        // 指定单元格居中对齐
        styleDetailLeft.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        // 指定单元格垂直居中对齐
        styleDetailLeft.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleDetailLeft.setWrapText(true);
        // 设置单元格字体
        styleDetailLeft.setFont(fontDetail);
        // 右边框
        styleDetailLeft.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 左边框
        styleDetailLeft.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 上边框
        styleDetailLeft.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 下styleDetailTitle
        styleDetailLeft.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        /**************** 数据行样式 end ****************/

        // 设置列宽
        sheet.setColumnWidth(0, 1 * 256 + 184);
        sheet.setColumnWidth(1, 12 * 256 + 184);
        sheet.setColumnWidth(2, 12 * 256 + 184);
        sheet.setColumnWidth(3, 12 * 256 + 184);
        sheet.setColumnWidth(4, 12 * 256 + 184);
        sheet.setColumnWidth(5, 12 * 256 + 184);
        sheet.setColumnWidth(6, 12 * 256 + 184);
        sheet.setColumnWidth(7, 12 * 256 + 184);
        sheet.setColumnWidth(8, 12 * 256 + 184);
        sheet.setColumnWidth(9, 12 * 256 + 184);
        sheet.setColumnWidth(10, 12 * 256 + 184);
        sheet.setColumnWidth(11, 12 * 256 + 184);
        sheet.setColumnWidth(12, 12 * 256 + 184);
        sheet.setColumnWidth(13, 12 * 256 + 184);
        sheet.setColumnWidth(14, 12 * 256 + 184);
        sheet.setColumnWidth(15, 1 * 256 + 184);

        // 创建单元格对象
        HSSFCell cell = null;

        // 创建打印设置对象
        HSSFPrintSetup ps = sheet.getPrintSetup();
        // 打印方向，true：横向，false：纵向(默认)
        ps.setLandscape(false);
        // // 打印质量
        // ps.setVResolution((short) 700)
        // 设置缩放比例
        ps.setScale((short) 80);
        // 纸张类型
        ps.setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);


        int rownum = 1;
        HSSFRow row0 = sheet.createRow((int) rownum);
        row0.setHeightInPoints(25);
        cell = row0.createCell(1);
        cell.setCellStyle(styleTitle);
        cell.setCellValue("现货采购报表信息");
        sheet.addMergedRegion(new CellRangeAddress(rownum, rownum, (short) 1, (short) 22));
        cell = row0.createCell(2);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(3);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(4);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(5);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(6);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(7);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(8);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(9);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(10);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(11);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(12);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(13);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(14);
        cell.setCellStyle(styleTitle);
        rownum++;

        HSSFRow row1 = sheet.createRow((int) rownum);
        row1.setHeightInPoints(30);
        cell = row1.createCell(1);
        cell.setCellValue("仓库");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(2);
        cell.setCellValue("车牌号");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(3);
        cell.setCellValue("入库日期");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(4);
        cell.setCellValue("毛重");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(5);
        cell.setCellValue("皮重");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(6);
        cell.setCellValue("扣重");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(7);
        cell.setCellValue("净重");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(8);
        cell.setCellValue("结算重量");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(9);
        cell.setCellValue("结算单价");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(10);
        cell.setCellValue("应付金额");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(11);
        cell.setCellValue("已付金额");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(12);
        cell.setCellValue("未付金额");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(13);
        cell.setCellValue("付款日期");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(14);
        cell.setCellValue("状态");
        cell.setCellStyle(styleDetail);


        rownum++;
        // 详情信息
        if (!CollectionUtils.isEmpty(stockPurchaseReceiptReport.getStockPurchaseReceiptReportList())) {
            for (int i = 0; i < stockPurchaseReceiptReport.getStockPurchaseReceiptReportList().size(); i++) {
                StockPurchaseReceiptReport stockPurchaseReceiptReport1 = stockPurchaseReceiptReport.getStockPurchaseReceiptReportList().get(i);
                HSSFRow rowx = sheet.createRow((int) rownum);
                rowx.setHeightInPoints(20);
                cell = rowx.createCell(1);
                cell.setCellValue(stockPurchaseReceiptReport1.getWarehouseName());
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(2);
                cell.setCellValue(editString(stockPurchaseReceiptReport1.getCarNo()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(3);
                String date = addDateOneDay(stockPurchaseReceiptReport1.getWarehousingDate());
                cell.setCellValue(date);
                cell.setCellStyle(styleDetail);
                HSSFDataFormat df = wb.createDataFormat(); // 此处设置数据格式
                contextstyle.setDataFormat(df.getBuiltinFormat("#,##0.00"));//保留两位小数点
                cell = rowx.createCell(4);
                cell.setCellValue(editDouble(stockPurchaseReceiptReport1.getGrossWeight()));
                cell.setCellStyle(contextstyle);
                cell = rowx.createCell(5);
                cell.setCellValue(editDouble(stockPurchaseReceiptReport1.getTare()));
                cell.setCellStyle(contextstyle);
                cell = rowx.createCell(6);
                cell.setCellValue(editDouble(stockPurchaseReceiptReport1.getDeductionWeight()));
                cell.setCellStyle(contextstyle);
                cell = rowx.createCell(7);
                cell.setCellValue(editDouble(stockPurchaseReceiptReport1.getNetWeight()));
                cell.setCellStyle(contextstyle);
                cell = rowx.createCell(8);
                cell.setCellValue(editDouble(stockPurchaseReceiptReport1.getSettlementWeight()));
                cell.setCellStyle(contextstyle);
                cell = rowx.createCell(9);
                cell.setCellValue(editDouble(stockPurchaseReceiptReport1.getSettlementPrice()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(10);
                cell.setCellValue(editDouble(stockPurchaseReceiptReport1.getAmountIngPayable()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(11);
                cell.setCellValue(editDouble(stockPurchaseReceiptReport1.getAmountEdPayable()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(12);
                cell.setCellValue(editDouble(stockPurchaseReceiptReport1.getAmountNotPayable()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(13);
                String date1 = addDateOneDay(stockPurchaseReceiptReport1.getPaymentDate()!=null?stockPurchaseReceiptReport1.getPaymentDate():new Date());
                cell.setCellValue(date1);
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(14);
                cell.setCellValue(stockPurchaseReceiptReport1.getStatus());
                cell.setCellStyle(styleDetail);
                rownum++;
            }
        }



        String path = null;
        String tempPath = null;
        String excelPath = null;

        try {

            // 取得绝对路径
            tempPath = URLDecoder.decode((localPath), "utf-8");

            // EXCEL路径
            excelPath = "/web/temp/pay/" + DateUtil.formatDate(new Date(), DateUtils.DATE_FMT_YYYYMMDD_NS) + '/'
                    + UUID.randomUUID().toString().replaceAll("-", "");

            path = tempPath + excelPath + '/' + "合同信息"
                    + ".xls";

        } catch (Exception e) {
            log.debug(e.getMessage());
        }
        // 下载
        download(path, response, wb);

    }


    private String addDateOneDay(Date date) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        return sdf.format(date);
    }

    /**
     * 判断浮点数
     *
     * @param example
     * @return
     */
    private Float editFloat(Float example) {
        Float exampleOne = example != null ? example : 0f;
        return exampleOne;
    }
    /**
     * 判断浮点数
     *
     * @param example
     * @return
     */
    private Double editDouble(Double example) {
        Double exampleOne = example != null ? example : 0d;
        return exampleOne;
    }

    /**
     * 判断字符串
     *
     * @param example
     * @return
     */
    private String editString(String example) {
        String exampleOne = example != null ? example : "";
        return exampleOne;
    }

    /**
     * 下载
     *
     * @param path
     * @param response
     */
    private void download(String path, HttpServletResponse response, Workbook wb) {

        try {

            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String fileName = file.getName();
            // 给文件名编码
            fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");

            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);

            // 定义byte输出流
            ByteArrayOutputStream out = new ByteArrayOutputStream();

            // 写导出文件
            wb.write(out);

            // 取得模板文件中的数据
            byte[] result = out.toByteArray();

            // 设置输出数据类型
            response.setContentType("application/vnd.ms-excel");
            // 设置输出数据长度
            response.setContentLength(result.length);

            // 设置文件名称
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            // 将文件流输出到画面
            response.getOutputStream().write(result);

            out.flush();
            out.close();

        } catch (IOException ex) {
            log.debug(ex.getMessage());
        }

    }


    private List<String> getResourceIdList() {
        User currentUser = AuthSecurityUtils.getCurrentUserInfo();
        // 当前登录人主要角色
        return roleResourceService.getBindResourcesByUserId(currentUser.getUserId()).stream()
                .map(CommonRoleResource::getResourceId).collect(Collectors.toList());
    }

}
