package com.yutu.base.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.yutu.base.entity.NoteResult;
import com.yutu.base.entity.Response;
import com.yutu.base.entity.SaleDetail;
import com.yutu.base.entity.SaleRules;
import com.yutu.base.utils.HttpsSendData;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class DownLoadService {

    private Logger logger = Logger.getLogger("download");

    @Value("${spring.urlConfig.overseasAirTicketUrl}")
    private String overseasAirTicketUrl;
    @Value("${spring.urlConfig.productServiceUrl}")
    private String productServiceUrl;
    @Value("${spring.pathConfig.saleReportExcelPath}")
    private String saleReportExcelPath;
    @Value("${spring.pathConfig.saleDetailReportExcelPath}")
    private String saleDetailReportExcelPath;

    @Autowired
    private SaleDetailReportService saleDetailReportService;
    @Autowired
    private ParseToSaleDetail parseToSaleDetail;

    /**
     * 获取销售数据
     *
     * @param requestBody
     * @return
     */
    public Response getSaleDetailReportData(String requestBody) {
        if (StringUtils.isBlank(requestBody)) {
            return Response.error("参数不能为空 [requestBody]");
        }
        logger.info("开始获取数据,参数:" + requestBody);
        long beginTime = System.currentTimeMillis();
//        String result = HttpsSendData.getPost(overseasAirTicketUrl+"orderInfo/getReportExcelData.do",requestBody);
        String result = HttpsSendData.getPost(overseasAirTicketUrl + "order/getReportExcelData", requestBody);
        if (StringUtils.isBlank(result)) {
            return Response.error("获取数据失败");
        }
        JSONObject resultObj = JSONObject.parseObject(result);
        if (resultObj.getInteger("status") != 0) {
            return Response.error("获取数据失败");
        }
        logger.info("获取数据成功,共用时:" + (System.currentTimeMillis() - beginTime));
        Map<String, String> resultMap = resultObj.getObject("data", Map.class);
        Response response = new Response();
        response.setStatus(Response.Status.SUCCEED);
        response.setData(resultMap);
        response.setErrorMessage("获取成功");
        return response;
    }

    /**
     * 下载销售报表
     *
     * @param requestBody
     * @return
     */
    public Response downLoadSaleDetailReport(String requestBody) {
        if (StringUtils.isBlank(requestBody)) {
            return Response.error("参数不能为空 [requestBody]");
        }
        String customerId = JSONObject.parseObject(requestBody).getString("customerId");

        logger.info("开始获取数据,参数:" + requestBody);
        long beginTime = System.currentTimeMillis();
        String result = HttpsSendData.getPost(overseasAirTicketUrl + "order/getReportExcelData", requestBody);
        if (StringUtils.isBlank(result)) {
            return Response.error("获取数据失败");
        }
        JSONObject resultObj = JSONObject.parseObject(result);
        if (resultObj.getInteger("status") != 0) {
            return Response.error("获取数据失败");
        }
        logger.info("获取数据成功,共用时:" + (System.currentTimeMillis() - beginTime));
        logger.info("开始解析数据生成报表 ...");
        Map<String, String> resultMap = resultObj.getObject("data", Map.class);
        Response response = new Response();
        try {
            final String filePath = saleDetailReportExcelPath + customerId + "/SalesDetailReport/";//指定文件保存路径
            String path = saleDetailReportService.createExcel(resultMap, filePath, "");
            response.setStatus(Response.Status.SUCCEED);
            response.setData(path);
            response.setErrorMessage("生成成功,总用时:" + (System.currentTimeMillis() - beginTime) + "ms");
            logger.info("生成销售明细报表,总用时:" + (System.currentTimeMillis() - beginTime) + "ms");
            return response;
        } catch (Exception e) {
            logger.error("生成报表发生异常", e);
            return Response.error("生成报表发生异常");
        }
    }

    /**
     * 下载加价规则 包含数据
     *
     * @param requestBody
     * @return
     */
    public Response downLoadSaleRules(String requestBody) {
        JSONObject requestObj = JSONObject.parseObject(requestBody);
        String customerId = requestObj.getString("customerId");
        long beginTime = System.currentTimeMillis();
        //请求运价直连工程获取源数据
        String result = HttpsSendData.getPost(productServiceUrl + "SaleRules/findByCustomerId", requestBody);
        if (StringUtils.isBlank(result)) {
            return Response.error("获取加价规则源数据异常");
        }
        JSONObject resultObj = JSONObject.parseObject(result);
        if (resultObj.getInteger("status") != 0) {
            return Response.error("获取加价规则源数据失败");
        }
        JSONArray dataArr = resultObj.getJSONArray("data");
        if (dataArr.size() == 0) {
            return Response.error("加价规则源数据共 0 条");
        }
        List<SaleRules> saleRules = new ArrayList<>();
        for (int i = 0; i < dataArr.size(); i++) {
            JSONObject data = dataArr.getJSONObject(i);
            SaleRules saleRule = new SaleRules(data.getString("id"), data.getString("customerId"), data.getString("channelId"),
                    data.getString("store"), data.getString("ruleCode"), data.getString("carrier"), data.getString("org"),
                    data.getString("dst"), data.getInteger("routeType"), data.getInteger("policyType"), data.getString("policyDesc"),
                    data.getInteger("point"), data.getInteger("costPrice"), data.getString("saleSdate"), data.getString("saleEdate"),
                    data.getString("ticketDays"), data.getString("tripSdate"), data.getString("tripEdate"), data.getInteger("status"),
                    data.getInteger("maxPrice"), data.getInteger("minPrice"), data.getInteger("minProfit"),
                    data.getBigDecimal("adultPricePoint"), data.getInteger("adultAddPrice"), data.getInteger("adultAddTax"), data.getBigDecimal("adultTaxPoint"),
                    data.getBigDecimal("childPricePoint"), data.getInteger("childAddPrice"), data.getInteger("childAddTax"), data.getBigDecimal("childTaxPoint"),
                    data.getString("operator"), data.getDate("createTime"), data.getDate("updateTime"), data.getInteger("deleted"),
                    data.getString("notApplicableFlightNum"), data.getString("applyFlightNum"), data.getInteger("remainCabinNum"), data.getString("cabinCode"),
                    data.getString("flightCycle"), data.getDouble("floorPrice"), data.getDouble("floorTax"), data.getInteger("fitShare"), data.getString("fitNationality"),
                    data.getString("disFitNationality"), data.getString("ageRange"), data.getString("attention"));
            saleRules.add(saleRule);
        }
        String filePath = saleReportExcelPath + customerId + "/SaleRulesExcel\\";
        File temp = new File(filePath);
        if (!temp.exists()) {
            temp.mkdir();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
        String date = sdf.format(new Date());
        File file = new File(date + "~销售规则.xls");
        FileOutputStream os = null;
        HSSFWorkbook book = null;
        try {

            //创建工作薄
            book = new HSSFWorkbook();
            HSSFSheet sheet = book.createSheet("销售规则");

            sheet.setColumnWidth(31, 7500);

            // 创建单元格样式
            HSSFCellStyle cellStyleTitle = book.createCellStyle();
            // 指定单元格居中对齐
            cellStyleTitle.setAlignment(HorizontalAlignment.CENTER);
            // 指定单元格垂直居中对齐
            cellStyleTitle.setVerticalAlignment(VerticalAlignment.CENTER);
            // 指定当单元格内容显示不下时自动换行
            cellStyleTitle.setWrapText(false);
            // ------------------------------------------------------------------
            HSSFCellStyle cellStyle = book.createCellStyle();
            // 指定单元格居中对齐
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            // 指定单元格垂直居中对齐
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            // 指定当单元格内容显示不下时自动换行
            cellStyle.setWrapText(false);
            // ------------------------------------------------------------------
            // 设置单元格字体
            HSSFFont font = book.createFont();
            font.setBold(true);
            font.setFontName("宋体");
            font.setColor(new Short("255"));
            font.setFontHeight((short) 200);
            cellStyleTitle.setFont(font);
            //创建标题行
            Row title = sheet.createRow(0);
            title.setRowStyle(cellStyleTitle);
            title.createCell(0).setCellValue("渠道");
            title.createCell(1).setCellValue("店铺编码");
            title.createCell(2).setCellValue("规则编号");
            title.createCell(3).setCellValue("航司两字代码");
            title.createCell(4).setCellValue("出港");
            title.createCell(5).setCellValue("到港");
            title.createCell(6).setCellValue("适用航班号");
            title.createCell(7).setCellValue("不适用航班号");
            title.createCell(8).setCellValue("行程类型");
            title.createCell(9).setCellValue("政策类型");
            title.createCell(10).setCellValue("政策描述");
            title.createCell(11).setCellValue("积分值");
            title.createCell(12).setCellValue("底价");
            title.createCell(13).setCellValue("销售开始日期");
            title.createCell(14).setCellValue("销售结束日期");
            title.createCell(15).setCellValue("提前出票天数");
            title.createCell(16).setCellValue("旅行开始日期");
            title.createCell(17).setCellValue("旅行结束日期");
            title.createCell(18).setCellValue("状态");
            title.createCell(19).setCellValue("最小金额");
            title.createCell(20).setCellValue("最大金额");
            title.createCell(21).setCellValue("最低利润值");
            title.createCell(22).setCellValue("成人加点");
            title.createCell(23).setCellValue("成人留钱");
//            title.createCell(24).setCellValue("成人加税");
//            title.createCell(25).setCellValue("成人加税点");
            title.createCell(26).setCellValue("儿童加点");
            title.createCell(27).setCellValue("儿童留钱");
//            title.createCell(28).setCellValue("儿童加税");
//            title.createCell(29).setCellValue("儿童加税点");
            title.createCell(30).setCellValue("舱位代码");
            title.createCell(31).setCellValue("销售规则Id");
            title.createCell(32).setCellValue("航班周期");
            title.createCell(33).setCellValue("底价票");
            title.createCell(34).setCellValue("底价税");
            title.createCell(35).setCellValue("适用共享");
            title.createCell(36).setCellValue("适用国籍");
            title.createCell(37).setCellValue("不适用国籍");
            title.createCell(38).setCellValue("年龄范围");
            title.createCell(39).setCellValue("购票需知");
            //遍历销售规则数据列表
            for (int i = 0; i < saleRules.size(); i++) {
                Row r = sheet.createRow(i + 1);

                Cell channelIdCell = r.createCell(0);
                channelIdCell.setCellStyle(cellStyle);
                if (saleRules.get(i).getChannelId() == null) {
                    channelIdCell.setCellValue("*");
                } else {
                    channelIdCell.setCellValue(saleRules.get(i).getChannelId());
                }

                Cell store = r.createCell(1);
                store.setCellStyle(cellStyle);
                if (saleRules.get(i).getStore() == null) {
                    store.setCellValue("*");
                } else {
                    store.setCellValue(saleRules.get(i).getStore());
                }

                Cell ruleCode = r.createCell(2);
                ruleCode.setCellStyle(cellStyle);
                if (saleRules.get(i).getRuleCode() == null) {
                    ruleCode.setCellValue("");
                } else {
                    ruleCode.setCellValue(saleRules.get(i).getRuleCode());
                }

                Cell carrierCell = r.createCell(3);
                carrierCell.setCellStyle(cellStyle);
                if (saleRules.get(i).getCarrier() == null) {
                    carrierCell.setCellValue("");
                } else {
                    carrierCell.setCellValue(saleRules.get(i).getCarrier());
                }

                Cell orgCell = r.createCell(4);
                orgCell.setCellStyle(cellStyle);
                if (saleRules.get(i).getOrg() == null) {
                    orgCell.setCellValue("*");
                } else {
                    orgCell.setCellValue(saleRules.get(i).getOrg());
                }

                Cell dstCell = r.createCell(5);
                dstCell.setCellStyle(cellStyle);
                if (saleRules.get(i).getDst() == null) {
                    dstCell.setCellValue("*");
                } else {
                    dstCell.setCellValue(saleRules.get(i).getDst());
                }
                Cell applyFlightNumCell = r.createCell(6);
                applyFlightNumCell.setCellStyle(cellStyle);
                if (StringUtils.isBlank(saleRules.get(i).getApplyFlightNum())) {
                    applyFlightNumCell.setCellValue("");
                } else {
                    applyFlightNumCell.setCellValue(saleRules.get(i).getApplyFlightNum());
                }
                Cell notApplicableFlightNumCell = r.createCell(7);
                notApplicableFlightNumCell.setCellStyle(cellStyle);
                if (StringUtils.isBlank(saleRules.get(i).getNotApplicableFlightNum())) {
                    notApplicableFlightNumCell.setCellValue("");
                } else {
                    notApplicableFlightNumCell.setCellValue(saleRules.get(i).getNotApplicableFlightNum());
                }


                Cell routeTypeCell = r.createCell(8);
                routeTypeCell.setCellStyle(cellStyle);
                if (saleRules.get(i).getRouteType() == null) {
                    routeTypeCell.setCellValue("不限");
                } else if (saleRules.get(i).getRouteType() == 0) {
                    routeTypeCell.setCellValue("不限");
                } else if (saleRules.get(i).getRouteType() == 1) {
                    routeTypeCell.setCellValue("单程");
                } else if (saleRules.get(i).getRouteType() == 2) {
                    routeTypeCell.setCellValue("往返");
                } else {
                    routeTypeCell.setCellValue("不限");
                }

                Cell policyType = r.createCell(9);
                policyType.setCellStyle(cellStyle);
                if (saleRules.get(i).getPolicyType() == null) {
                    policyType.setCellValue("普通");
                } else if (saleRules.get(i).getPolicyType() == 1) {
                    policyType.setCellValue("普通");
                } else if (saleRules.get(i).getPolicyType() == 2) {
                    policyType.setCellValue("积分");
                } else if (saleRules.get(i).getPolicyType() == 3) {
                    policyType.setCellValue("普通促销");
                } else if (saleRules.get(i).getPolicyType() == 4) {
                    policyType.setCellValue("扣位");
                } else if (saleRules.get(i).getPolicyType() == 5) {
                    policyType.setCellValue("促销积分");
                } else if (saleRules.get(i).getPolicyType() == 6) {
                    policyType.setCellValue("AG");
                } else if (saleRules.get(i).getPolicyType() == 7) {
                    policyType.setCellValue("私有运价");
                } else {
                    policyType.setCellValue("普通");
                }

                Cell policyDesc = r.createCell(10);
                policyDesc.setCellStyle(cellStyle);
                if (saleRules.get(i).getPolicyDesc() == null) {
                    policyDesc.setCellValue("");
                } else {
                    policyDesc.setCellValue(saleRules.get(i).getPolicyDesc());
                }

                Cell point = r.createCell(11);
                point.setCellStyle(cellStyle);
                if (saleRules.get(i).getPoint() == null) {
                    point.setCellValue("");
                } else {
                    point.setCellValue(saleRules.get(i).getPoint());
                }

                Cell costPrice = r.createCell(12);
                costPrice.setCellStyle(cellStyle);
                if (saleRules.get(i).getCostPrice() == null) {
                    costPrice.setCellValue("");
                } else {
                    costPrice.setCellValue(saleRules.get(i).getCostPrice());
                }

                Cell saleSdate = r.createCell(13);
                saleSdate.setCellStyle(cellStyle);
                if (saleRules.get(i).getSaleSdate() == null) {
                    saleSdate.setCellValue("");
                } else {
                    saleSdate.setCellValue(saleRules.get(i).getSaleSdate());
                }

                Cell saleEdate = r.createCell(14);
                saleEdate.setCellStyle(cellStyle);
                if (saleRules.get(i).getSaleEdate() == null) {
                    saleEdate.setCellValue("");
                } else {
                    saleEdate.setCellValue(saleRules.get(i).getSaleEdate());
                }

                Cell ticketDays = r.createCell(15);
                ticketDays.setCellStyle(cellStyle);
                if (saleRules.get(i).getTicketDays() == null) {
                    ticketDays.setCellValue("");
                } else {
                    ticketDays.setCellValue(saleRules.get(i).getTicketDays());
                }


                Cell tripSdate = r.createCell(16);
                tripSdate.setCellStyle(cellStyle);
                if (saleRules.get(i).getTripSdate() == null) {
                    tripSdate.setCellValue("");
                } else {
                    tripSdate.setCellValue(saleRules.get(i).getTripSdate());
                }

                Cell tripEdate = r.createCell(17);
                tripEdate.setCellStyle(cellStyle);
                if (saleRules.get(i).getTripEdate() == null) {
                    tripEdate.setCellValue("");
                } else {
                    tripEdate.setCellValue(saleRules.get(i).getTripEdate());
                }


                Cell statusCell = r.createCell(18);
                statusCell.setCellStyle(cellStyle);
                if (saleRules.get(i).getStatus() == null) {
                    statusCell.setCellValue("禁用");
                } else if (saleRules.get(i).getStatus() == 0) {
                    statusCell.setCellValue("禁用");
                } else if (saleRules.get(i).getStatus() == 1) {
                    statusCell.setCellValue("启用");
                } else {
                    statusCell.setCellValue("禁用");
                }


                Cell minPrice = r.createCell(19);
                minPrice.setCellStyle(cellStyle);
                if (saleRules.get(i).getMinPrice() == null) {
                    minPrice.setCellValue("");
                } else {
                    minPrice.setCellValue(saleRules.get(i).getMinPrice());
                }

                Cell maxPrice = r.createCell(20);
                maxPrice.setCellStyle(cellStyle);
                if (saleRules.get(i).getMaxPrice() == null) {
                    maxPrice.setCellValue("");
                } else {
                    maxPrice.setCellValue(saleRules.get(i).getMaxPrice());
                }

                Cell minProfit = r.createCell(21);
                minProfit.setCellStyle(cellStyle);
                if (saleRules.get(i).getMinProfit() == null) {
                    minProfit.setCellValue("");
                } else {
                    minProfit.setCellValue(saleRules.get(i).getMinProfit());
                }

                Cell adultPricePoint = r.createCell(22);
                adultPricePoint.setCellStyle(cellStyle);
                if (saleRules.get(i).getAdultPricePoint() == null) {
                    adultPricePoint.setCellValue(0.0);
                } else {
                    adultPricePoint.setCellValue(saleRules.get(i).getAdultPricePoint().toString());
                }

                Cell adultAddPrice = r.createCell(23);
                adultAddPrice.setCellStyle(cellStyle);
                if (saleRules.get(i).getAdultAddPrice() == null) {
                    adultAddPrice.setCellValue(0);
                } else {
                    adultAddPrice.setCellValue(saleRules.get(i).getAdultAddPrice());
                }

//				Cell adultTaxPoint = r.createCell(23);
//				adultTaxPoint.setCellStyle(cellStyle);
//				if (saleRules.get(i).getAdultPricePoint()==null) {
//					adultTaxPoint.setCellValue(0.0);
//				}else{
//					adultTaxPoint.setCellValue(saleRules.get(i).getAdultPricePoint().toString());
//				}

//                Cell adultAddTax = r.createCell(24);
//                adultAddTax.setCellStyle(cellStyle);
//                if (saleRules.get(i).getAdultAddTax()==null) {
//                    adultAddTax.setCellValue(0);
//                }else{
//                    adultAddTax.setCellValue(saleRules.get(i).getAdultAddTax());
//                }

//                Cell adultTaxPoint = r.createCell(25);
//                adultTaxPoint.setCellStyle(cellStyle);
//                if (saleRules.get(i).getAdultTaxPoint()==null) {
//                    adultTaxPoint.setCellValue(0.0);
//                }else{
//                    adultTaxPoint.setCellValue(saleRules.get(i).getAdultTaxPoint().toString());
//                }

                Cell childPricePoint = r.createCell(26);
                childPricePoint.setCellStyle(cellStyle);
                if (saleRules.get(i).getChildPricePoint() == null) {
                    childPricePoint.setCellValue(0.0);
                } else {
                    childPricePoint.setCellValue(saleRules.get(i).getChildPricePoint().toString());
                }

                Cell childAddPrice = r.createCell(27);
                childAddPrice.setCellStyle(cellStyle);
                if (saleRules.get(i).getChildAddPrice() == null) {
                    childAddPrice.setCellValue(0);
                } else {
                    childAddPrice.setCellValue(saleRules.get(i).getChildAddPrice());
                }

//                Cell childAddTax = r.createCell(28);
//                childAddTax.setCellStyle(cellStyle);
//                if (saleRules.get(i).getChildAddTax()==null) {
//                    childAddTax.setCellValue(0);
//                }else{
//                    childAddTax.setCellValue(saleRules.get(i).getChildAddTax());
//                }

//                Cell childTaxPoint = r.createCell(29);
//                childTaxPoint.setCellStyle(cellStyle);
//                if (saleRules.get(i).getChildTaxPoint()==null) {
//                    childTaxPoint.setCellValue(0.0);
//                }else{
//                    childTaxPoint.setCellValue(saleRules.get(i).getChildTaxPoint().toString());
//                }

                Cell cabinCode = r.createCell(30);
                cabinCode.setCellStyle(cellStyle);
                cabinCode.setCellValue(saleRules.get(i).getCabinCode());

                Cell saleRuleId = r.createCell(31);
                saleRuleId.setCellStyle(cellStyle);
                if (saleRuleId != null) {
                    saleRuleId.setCellValue(saleRules.get(i).getId());
                }

                Cell flightCycle = r.createCell(32);
                flightCycle.setCellStyle(cellStyle);
                if (StringUtils.isBlank(saleRules.get(i).getFlightCycle())) {
                    flightCycle.setCellValue("");
                } else {
                    flightCycle.setCellValue(saleRules.get(i).getFlightCycle());
                }

                Cell floorPrice = r.createCell(33);
                floorPrice.setCellStyle(cellStyle);
                if (saleRules.get(i).getFloorPrice() == null) {
                    floorPrice.setCellValue("");
                } else {
                    floorPrice.setCellValue(saleRules.get(i).getFloorPrice());
                }

                Cell floorTax = r.createCell(34);
                floorTax.setCellStyle(cellStyle);
                if (saleRules.get(i).getFloorTax() == null) {
                    floorTax.setCellValue("");
                } else {
                    floorTax.setCellValue(saleRules.get(i).getFloorTax());
                }

                Cell fitShare = r.createCell(35);
                fitShare.setCellStyle(cellStyle);
                if (saleRules.get(i).getFitShare() == null) {
                    fitShare.setCellValue("");
                } else {
                    if (saleRules.get(i).getFitShare() == 1) {
                        fitShare.setCellValue("适用");
                    } else if (saleRules.get(i).getFitShare() == 0) {
                        fitShare.setCellValue("不适用");
                    } else {
                        fitShare.setCellValue(saleRules.get(i).getFitShare());
                    }
                }

                Cell fitNationality = r.createCell(36);
                fitNationality.setCellStyle(cellStyle);
                if (saleRules.get(i).getFitNationality() == null) {
                    fitNationality.setCellValue("");
                } else {
                    fitNationality.setCellValue(saleRules.get(i).getFitNationality());
                }

                Cell disFitNationality = r.createCell(37);
                fitNationality.setCellStyle(cellStyle);
                if (saleRules.get(i).getDisFitNationality() == null) {
                    disFitNationality.setCellValue("");
                } else {
                    disFitNationality.setCellValue(saleRules.get(i).getDisFitNationality());
                }

                Cell ageRange = r.createCell(38);
                ageRange.setCellStyle(cellStyle);
                if (saleRules.get(i).getAgeRange() == null) {
                    ageRange.setCellValue("");
                } else {
                    ageRange.setCellValue(saleRules.get(i).getAgeRange());
                }

                Cell attention = r.createCell(39);
                attention.setCellStyle(cellStyle);
                if (saleRules.get(i).getAttention() == null) {
                    attention.setCellValue("");
                } else {
                    attention.setCellValue(saleRules.get(i).getAttention());
                }

            }
            //创建输出流
            os = new FileOutputStream(filePath + file);
            //将book中的数据写出
            book.write(os);
        } catch (Exception e) {
            logger.error("fail:", e);
        } finally {
            try {
                if (book != null) {
                    book.close();
                }
                if (os != null) {
                    os.close();
                }
            } catch (Exception e) {
                logger.error("关闭流异常", e);
            }

        }
        Response response = new Response();
        response.setStatus(Response.Status.SUCCEED);
        response.setData(filePath + file);
        return response;
    }

    public static HSSFWorkbook getBook(File file) {
        HSSFWorkbook book = null;
        try {
            book = new HSSFWorkbook(new FileInputStream(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return book;
    }


    protected static Object getCellString(HSSFCell cell) {
        Object result = null;
        if (cell != null) {
            int cellType = cell.getCellType();
            switch (cellType) {

                case HSSFCell.CELL_TYPE_STRING:
                    result = cell.getStringCellValue();
                    break;
                case HSSFCell.CELL_TYPE_NUMERIC:
                    result = cell.getNumericCellValue();
                    break;
                case HSSFCell.CELL_TYPE_FORMULA:
                    result = cell.getNumericCellValue();
                    break;
                case HSSFCell.CELL_TYPE_ERROR:
                    result = null;
                    break;
                case HSSFCell.CELL_TYPE_BOOLEAN:
                    result = cell.getBooleanCellValue();
                    break;
                case HSSFCell.CELL_TYPE_BLANK:
                    result = null;
                    break;
            }
        }
        return result;
    }

    public Response parseToSaleDetail(String requestBody) {
        logger.info("自动报表任务请求解析报表。。。");
        if (StringUtils.isBlank(requestBody)) {
            return Response.error("参数为空");
        }
        JSONObject obj = JSONObject.parseObject(requestBody);
        Map<String, String> params = JSONObject.parseObject(obj.getString("data"), new TypeReference<Map<String, String>>() {
        });
        String key = obj.getString("info");
        //将Map解析为报表内容对象
        List<SaleDetail> saleDetailList = new ArrayList<>();
        try {
            //解析主逻辑
            saleDetailList = parseToSaleDetail.parseToSaleDetailMain(params, key);
        } catch (Exception e) {
            logger.error("[自动报表] 解析Map到SaleDetail List 出现异常", e);
        }
        logger.info("自动报表任务解析数据完成,解析结果:saleDetailList.size() = " + saleDetailList.size());
        return Response.success(saleDetailList);
    }

    /**
     * 快速导出报表(新)
     *
     * @param requestBody
     * @return
     */
    public Response downLoadSaleDetailFromAutoSource(String requestBody) {
        String keyList = JSONObject.parseObject(requestBody).getString("keyList");
        logger.info("[AutoSource] 从saleDetail表数据中直接下载报表,keyList=" + keyList);
        long beginTime = System.currentTimeMillis();
        Map<String, String> params = new HashMap<>();
        params.put("keyList", keyList);
        String result = HttpsSendData.send(overseasAirTicketUrl + "autoSaleDetai/findByKeyList", params);
        NoteResult noteResult = JSONObject.parseObject(result, NoteResult.class);
        if (noteResult.getStatus() != 0) {
            logger.error("[AutoSource] 从saleDetail表中查询报表数据失败,keyList=" + keyList);
            return Response.error("[AutoSource] 从saleDetail表中查询报表数据失败,key=" + keyList);
        }
        List<SaleDetail> saleDetails = JSONArray.parseArray(JSONArray.toJSONString(noteResult.getData()), SaleDetail.class);
        Response response = new Response();
        logger.info("[AutoSource] 获取数据库表数据,总用时:" + (System.currentTimeMillis() - beginTime) + "ms");
        try {
            String customerId = keyList.substring(0, keyList.indexOf("_"));
            final String filePath = saleDetailReportExcelPath + customerId + "/SalesDetailReport/";//指定文件保存路径
            String path = parseToSaleDetail.createSaleDetailReport(saleDetails, filePath);
            response.setStatus(Response.Status.SUCCEED);
            response.setData(path);
            response.setErrorMessage("[AutoSource] 生成报表成功,总用时:" + (System.currentTimeMillis() - beginTime) + "ms");
            logger.info("[AutoSource] 生成销售明细报表,总用时:" + (System.currentTimeMillis() - beginTime) + "ms");
            return response;
        } catch (Exception e) {
            logger.error("[AutoSource] 生成报表发生异常", e);
            return Response.error("[AutoSource] 生成报表发生异常");
        }
    }

}